Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 function in my code to achieve a scrolling effect on my page, however I think it is affecting my image links. When I click on an image it doesn't link anywhere. I'm fairly certain the error is somewhere here but need some help finding it.

Thanks.

like image 241
polo111 Avatar asked Jun 04 '16 23:06

polo111


1 Answers

Make sure there is a hash # in the href first before changing anything so normal links will still work.

One way is check hash property of the element

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

Can also use attribute selector to filter out only links with # in href

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

Last one assumes all hash links are relative and href starts with #

like image 152
charlietfl Avatar answered Oct 22 '22 18:10

charlietfl