Prevent Default Behaviour of Hashed Anchor Tag with jQuery
by c.bavota | Posted in Tutorials | 13 comments
Jan
29
2013
Way back in the day, I use to always set up my event triggering anchor tags a certain way to prevent their default behaviour of having to click-through to a URL or named anchor:
<a href="javascript:void(0)" class="trigger">Trigger</a>
Usually, a more simple approach was to use a simple hash:
<a href="#" class="trigger">Trigger</a>
That’s the way I should’ve been doing it, but I really hated how it always made the browser window jump to the top.
Solving that wasn’t too complicated. It just took a bit of jQuery.
<script type="text/javascript">
/* <![CDATA[ */
( function( $ ) {
$( 'a[href="#"]' ).click( function(e) {
e.preventDefault();
} );
} )( jQuery );
/* ]]> */
</script>
With that code in place, the browser no longer jumps to the top when using a hashed anchor tag.



Nice story =) Thanks for the post, needed!
Great idea, I often use e.preventDefault() to prevent link redirect to other pages or make page don’t scroll to top.
I also use it to prevent form submit action
It works perfect, thanks for sharing!
I’m using target pseudo class to change click events. I don’t know if I am doing this right but it doesn’t seem to be working for me, the page is still jumping when clicked.
Thank You
Can I see an example of your code somewhere?
c. bavota,
I created a js fiddle of the code.. nevermind that the content doesnt work in the second box ( I had to create different divs/css for it and it was a hassle to upload the specific code for all of it as there are more boxes as well and lots of code for it.)
http://jsfiddle.net/3ASpX/1/
Your help is much appreciated.
Thanks,
Looks like you got it to work.
The page still jumps I didn’t figure it out
No the page is jumping when clicking the buttons!!!!
The jsfiddle example doesn’t have jQuery loaded. Did you load jQuery on the real version?
Yes I have loaded the Jquery..still no luck man
If you load up your “real” version in Chrome and load the dev tools, do you get any JavaScript errors?
Thanks friend.It worked like a charm.