views:

439

answers:

6

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. Thanks for the help!

+10  A: 

You need to return false; in the jQuery click handler to prevent the default action from happening:

<a href="#" id="ma_link">Do something fancy</a>

Then with jQuery:

$('#ma_link').click(function(e) {
     // do something fancy
     return false; // prevent default click action from happening!
     e.preventDefault(); // same thing as above
});
Paolo Bergantino
That's exactly it! Thanks man!
Achilles
+2  A: 

Try this:

<a href="#" onclick="return false;">My Link</a>
mikeluby
+2  A: 

Link to something more sensible than the top of the page in the first place. Then cancel the default event.

See rule 2 of pragmatic progressive enhancement.

David Dorward
This also makes you site more SEO friendly.
Frankie
A: 

Returning false from the code your calling will work and in a number of circumstances is the prefered method but you can also so this

<a href="javascript:;">Link Title</a>

When it comes to SEO it really depends on what your link is going to be used for. If you are going to actually use it to link to some other content then I would agree ideally you would want something meaningful here but if you are using the link for functionality purposes maybe like stackoverflow does for the post toolbar (bold, italic, hyperlink, etc) then it probably doesn't matter.

Dean
A: 

An easy approach is to leverage this code:

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

This approach doesn't force a page refresh, so the scrollbar stays in place. Also, it allows you to programmatically change the onclick event and handle client side event binding using jQuery.

For these reasons, the above solution is better than:

<a href="javascript:myClickHandler();">Link Title</a>
<a href="#" onclick="myClickHandler(); return false;">Link Title</a>

where the last solution will avoid the scroll-jump issue if and only if the myClickHandler method doesn't fail.

phreeskier
A: 

Link Title

Easy and very VERY VERY effective loved it! thanks!

davidrp