Code Alex Code Alex - 6 months ago 69
jQuery Question

How to scroll automatically to the next section in jQuery?

See the snippet.. got some sections containing the full size of the viewport. When the user is scrolling it should scroll automatically to the next one of the class ".section"

English isn't my main language, sorry for some mistakes in grammar or sth like that.



$(document).ready(function(e){

var position = $(window).scrollTop();

$(window).scroll(function() {

var scroll = $(window).scrollTop();

if(scroll > position) {

//scrolling down

} else {
//scrolling up
}

position = scroll;

});
});

html,body { margin:0;padding:0;width: 100%;}

.section {
width: 100%;
height:100vh;
background-color:#000;
}

.section:nth-child(odd) { background-color:#fff;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="Home" class="section"></section>
<section id="Home" class="section"></section>
<section id="Home" class="section"></section>
<section id="Home" class="section"></section>
<section id="Home" class="section"></section>




Answer Source

First, I would number the DIVs, after I would use the Jquery code with animate atribute, I use buttons to invoke the function and a counter to go the next div

<section id="H1" class="section"><button>btn</button></section>

 <section id="H2" class="section"><button>btn</button></section>

 <section id="H3" class="section"><button>btn</button></section>

 <section id="H4" class="section"><button>btn</button></section>


<script>
var ndiv=1;
   $("button").on('click', function(event) {

  event.preventDefault();

  // Store hash
  var hash = "#H"+ ndiv;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
        }, 800, function(){

        window.location.hash ="H"+ ndiv;
      } );

ndiv++;
});
</script>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download