How to scroll to next div using Javascript? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to scroll to next div using Javascript? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

So I’m making a website with a lot of Divs that take 100% height. And I want to make a button so when it’s clicked to smoothly scroll to next div. I’ve coded something so when its clicked, it scrolls to specific div.

$(".next").click(function() {
    $('html,body').animate({
        scrollTop: $(".p2").offset().top},
        'slow');
});
body{
  margin: 0;
  height: 100%;
}

.p1{
  height: 100vh;
  width: 70%;
  background-color: #2196F3;
}
.p2{
  height: 100vh;
  width: 70%;
  background-color: #E91E63;
}
.p3{
  height: 100vh;
  width: 70%;
  background-color: #01579B;
}

.admin{
  background-color: #B71C1C;
  height: 100vh;
  position: fixed;
  right: 0%;
  top: 0%;
  width: 30%;
  float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="p1">
  
</div>
<div class="p2">
  
</div>
<div class="p3">
  
</div>

<div class="admin">
  
  <button class="next">NEXT</button>
  
</div>

Answer

To make this work you need to identify the currently displayed div. For that you can apply a class to the element which is currently shown. Then you can use next() to traverse through them all.

Also note in the below example the addition of a common class on all elements, .p, in order to DRY up the CSS and make DOM traversal easier.

$(".next").click(function() {
  var $target = $('.p.active').next('.p');
  if ($target.length == 0)
    $target = $('.p:first');
    
  $('html, body').animate({
    scrollTop: $target.offset().top
  }, 'slow');

  $('.active').removeClass('active');
  $target.addClass('active');
});
body {
  margin: 0;
  height: 100%;
}

.p {
  height: 100vh;
  width: 70%;
}
.p1 {
  background-color: #2196F3;
}
.p2 {
  background-color: #E91E63;
}
.p3 {
  background-color: #01579B;
}

.admin {
  background-color: #B71C1C;
  height: 100vh;
  position: fixed;
  right: 0%;
  top: 0%;
  width: 30%;
  float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="p p1 active"></div>
<div class="p p2"></div>
<div class="p p3"></div>
<div class="admin">
  <button class="next">NEXT</button>
</div>
We are here to answer your question about How to scroll to next div using Javascript? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji