JQuery code affecting my HTML image links?

$(document).ready(function(){ $('body a').click(function(e){ e.preventDefault(); var goTo = $(this).attr('href').replace('#',''); $('html, body').animate({ scrollTop:$('a[name="'+goTo+'"]').offset().top },1775); window.location.hash = "#"+goTo; }); 

I have this feature in my code to achieve the scroll effect on my page, however I think it affects my image links. When I click on an image, it doesn’t link anywhere. I am sure that the error is here, but I need help finding it.

Thanks.

+6
source share
1 answer

Make sure that href first has a hash # before changing anything so that normal links work anyway.

One way is to check the hash property of an element

 if(this.hash){ e.preventDefault(); // rest of code shown } 

You can also use the attribute selector to filter only c # links in href

  $('body a[href^=#]').click... 

The latter assumes all hash links are relative, and href starts with #

+5
source

All Articles