Search code examples
javascripthtmlcssscroll

How to scroll to next div with full page?


when it's clicked to smoothly scroll to next div and Divs that take 100% height but I want to scroll to the next div instead of the "next" button who can help me to edit this code? pleas help guys to make my web site

$(".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>


Solution

  • I think CSS's Scroll Snap feature can help you;

    https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Scroll_Snap/Basic_concepts https://caniuse.com/?search=scroll-snap

    $(".next").click(function() {
      $('html,body').animate({
          scrollTop: $(".p2").offset().top
        },
        'slow');
    });
    body {
      margin: 0;
    }
    
    .container {
      height: 100vh;
      overflow-y: scroll;
      scroll-snap-type: y mandatory;
    }
    
    div[class*=p] {
      scroll-snap-align: start;
    }
    
    .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="container">
      <div class="p1">
      </div>
      <div class="p2">
      </div>
      <div class="p3">
      </div>
      <div class="admin">
        <button class="next">NEXT</button>
      </div>
    </div>