Search code examples
jqueryjquery-selectorssmooth-scrolling

jQuery go to the next section on every click


What I am trying to achieve is one single button in a position fixed which on every click it will take me to the next section on the page (A section with a class "next-section" in my case)

I started with this code:

var $a = $('.down-btn'), $targets = $('div.next-section').next();
$a.on('click', function(e) {
    e.preventDefault(); 
    console.log($targets);
    var i = $a.index(this);
    var offset = $targets.eq(++i).offset().top;
    $('html, body').stop().animate({ scrollTop: offset }, 400);
});

But this only works with one click - one time I need it to take me to the next section in every click on the button Would appreciate an answer Thanks

Here is a fiddle https://jsfiddle.net/hamergil/jv3ja3wp/12/


Solution

  • You need to change the code like below

    1.Use counter variable and increased it inside click handler before scroll code.

    2.Use .next() inside click handler to get correct element position for scroll.

    var i = 0;
    $('.down-btn').on('click', function(e) {
      e.preventDefault();
      i++;
      var offset = $("div.next-section").eq(i).offset().top;
      $('html, body').stop().animate({
        scrollTop: offset
      }, 400);
    });
    

    Working snippet:- https://jsfiddle.net/uj91djeL/1/