I previously posted a question where my jQuery wasn’t working when a HREF was specified in a link (original question here).
The most common suggested answer was to use preventDefault, but for some reason, this doesn’t work if there’s a hash/anchor in the HREF; so for example if the URL is “http://www.google.com“, it prevents the default behaviour and runs the jQuery as expected, but if it’s “http://www.google.co.uk#whatever“, it ignores the preventDefault and follows the link.
The link I’m using has a target (indeed, is only a target within the same page). Is there a workaround for this quirky behaviour?
HTML
<li><a id="OfficeNav-Bath" class="first" href="#bath" >Bath</a></li>
Jquery
<script> <!--Offices jquery -->
$(function() {$("#OfficeNav-Bath").click(function(e){e.preventDefault(); $('.office').removeClass('visible');});});
</script>
Without any information on the exact version of jquery you are using having a
#in thehrefseems to be no issue using jQuery 1.8.2.Using jsFiddle
#within a href has no impact andevent.PreventDefault()is working as expected.DEMO –
event.PreventDefault()and#inhrefCode from DEMO above is below in-case of link-rot.
HTML:
Script: