On double click of li element jQuery scroll goes to top of the screen

I am trying to finish my portfolio but when I click on a list element in my navbar it takes me to where I want to go, but when I click on the same element again it takes me back to the top. I think it's because jQuery is scrolling to the href and in the list element I have an anchor with href. How can I stop this?

The jQuery -

  $('a').click(function(){
    $('html, body').animate({
      scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 500); 
  });

JSFiddle.

Answers 1

  • I believe the issue is that you haven't accounted for the current scroll position of the window.

    When you've scrolled to one of your sections, its $.offset().top is 0, even though its not at the top of the page, its at the top of the screen.

    Adding the current scrollbar position to your scrollTop function worked for me:

    $('a').click(function(){
    
        var scrollToName = $(this).attr("href").substr(1);
        var scrollTo = $("body").scrollTop() + $('[name="' + scrollToName + '"]').offset().top;
    
        $('html, body').animate({
            scrollTop: scrollTo
        }, 500);
    });
    

    Here is the fiddle


Related Articles