How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

Viewed 190536

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.

16 Answers

If you can simply change the href value, you should use:

<a href="javascript:void(0);">Link Title</a>

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.

<script type="text/javascript">
    /* Stop page jumping when links are pressed */
    $('a[href="#"]').live("click", function(e) {
         return false; // prevent default click action from happening!
         e.preventDefault(); // same thing as above
    });
</script>

event.preventDefault() will stop the scrolling but also not change the link state to visited (color), which I need. The "3 years late" solution is not too late and eliminates unforseen side-effects. The hrefs I create are in a loop (indexed by "i") "#i!", where i is the index to an array containing the text for the anchor tag. Works like a charm. (Just #i would work too, except I have other ids set to i).

While I'd like to use the `href='javascript:function()'` approach, this adds 11 bytes (javascript:) plus the bytes of the function name plus parameters to the page size. Mutiply this by 1000+ hrefs and thats 16kb+ added to the page size. (Yes, pagination would help but not for the user). So maybe in a different situation I'd go with the javascript: solution.

Related