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.
Best Answer
You need to prevent the default action for the click event (i.e. navigating to the link target) from occurring.
There are two ways to do this.
Option 1:
event.preventDefault()
Call the
.preventDefault()
method of the event object passed to your handler. If you're using jQuery to bind your handlers, that event will be an instance ofjQuery.Event
and it will be the jQuery version of.preventDefault()
. If you're usingaddEventListener
to bind your handlers, it will be anEvent
and the raw DOM version of.preventDefault()
. Either way will do what you need.Examples:
Option 2:
return false;
In jQuery:
So, with jQuery, you can alternatively use this approach to prevent the default link behaviour:
If you're using raw DOM events, this will also work on modern browsers, since the HTML 5 spec dictates this behaviour. However, older versions of the spec did not, so if you need maximum compatibility with older browsers, you should call
.preventDefault()
explicitly. See event.preventDefault() vs. return false (no jQuery) for the spec detail.