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.
Also, you can use event.preventDefault inside onclick attribute.
No need to write exstra click event.
You can set your href to
#!
instead of#
For example,
will not do any scrolling when clicked.
Beware! This will still add an entry to the browser's history when clicked, meaning that after clicking your link, the user's back button will not take them to the page they were previously on. For this reason, it's probably better to use the
.preventDefault()
approach, or to use both in combination.Here is a Fiddle illustrating this (just scrunch your browser down until your get a scrollbar):
http://jsfiddle.net/9dEG7/
For the spec nerds - why this works:
This behaviour is specified in the HTML5 spec under the Navigating to a fragment identifier section. The reason that a link with a href of
"#"
causes the document to scroll to the top is that this behaviour is explicitly specified as the way to handle an empty fragment identifier:Using a href of
"#!"
instead works simply because it avoids this rule. There's nothing magic about the exclamation mark - it just makes a convenient fragment identifier because it's noticeably different to a typical fragid and unlikely to ever match theid
orname
of an element on your page. Indeed, we could put almost anything after the hash; the only fragids that won't suffice are the empty string, the word 'top', or strings that matchname
orid
attributes of elements on the page.More exactly, we just need a fragment identifier that will cause us to fall through to step 8 in the following algorithm for determining the indicated part of the document from the fragid:
As long as we hit step 8 and there is no indicated part of the document, the following rule comes into play:
which is why the browser doesn't scroll.
You can simply write like this also:-
this will work fine . no need to add href="#"
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.
An easy approach is to leverage this code:
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:
where the last solution will avoid the scroll-jump issue if and only if the myClickHandler method doesn't fail.