Prevent Default Behaviour of Hashed Anchor Tag with jQuery
by Bandicoot Marketing on | Posted in Tutorials | 14 comments
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.
14 comments for “Prevent Default Behaviour of Hashed Anchor Tag with jQuery”