How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?
html, javascript
Solution
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 of `jQuery.Event` and it will be the jQuery version of `.preventDefault()`. If you're using `addEventListener` to bind your handlers, it will be an `Event` and the raw DOM version of `.preventDefault()`. Either way will do what you need.
Examples:
$('#ma_link').click(function($e) {
$e.preventDefault();
doSomething();
});
document.getElementById('#ma_link').addEventListener('click', function (e) {
e.preventDefault();
doSomething();
})
Option 2: `return false;`
In jQuery:
Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault()
So, with jQuery, you can alternatively use this approach to prevent the default link behaviour:
$('#ma_link').click(function(e) {
doSomething();
return false;
});
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.
Problem
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.