javascriptjqueryscrollscrolltoscroller

JQuery scroll to next instance of class


so all I want is to scroll from the current visible class to the next instance of the class.

HTML Looks something like this

<div class="container"> 
 <div class="section">
` <p> lorem ipsum </p>
  <a href="javascript:void(null)" class="next"> next section </a>
 </div>
<div>

^ Repeat 'x' times

My js:

$(.next).click(function(e){
 $('html,body').animate({}, 
  scrollTop: $(this).parent().next().offset().top
  },'slow');

});

So obviously that code doesn't work as it just takes you to the next div but I'm quite rookie and would really appreciate some help.

Fiddle: http://jsfiddle.net/o1wjedd5/


Solution

  • You need to use .closest(".container") inorder to reach the parent container. Then use .next()

    $(".next").click(function(e){
    
        $('html, body').animate({
            'scrollTop' : $(this).closest(".container").next().position().top
        });
    });
    

    Fiddle