When I have a link that is wired-up with a jQuery or JavaScript event such as:
<a href="#">My Link</a>
How do I prevent the page from scrolling to the top? When I remove the href attribute from the anchor the page doesn't scroll to the top but the link doesn't appear to be click-able.
You might want to check your CSS. In the example here: https://css-tricks.com/the-checkbox-hack/ there's
position: absolute; top: -9999px;
. This is particularly goofy on Chrome, asonclick="whatever"
still jumps to the absolute position of the clicked element.Removing
position: absolute; top: -9999px;
, fordisplay: none;
might help.You should change the
to
This way when the link is clicked the page won't scroll to top. This is cleaner than using href="#" and then preventing the default event from running.
I have good reasons for this on the first answer to this question, like the
return false;
will not execute if the called function throws an error, or you may add thereturn false;
to adoSomething()
function and then forget to usereturn doSomething();
If you can simply change the
href
value, you should use:Another neat solution I just came up with is to use jQuery to stop the click action from occurring and causing the page to scroll, but only for
href="#"
links.