1

To explain, if I scroll down once, the page shouldn't move based on the amount I scrolled but it should smooth scroll to the next id directly. If I scroll down once, it should scroll to the id below and if I scroll up, I want to scroll to the id above and not anywhere in between.

For reference, in the pen below, if I am on top section of this pen and I scroll down once, it shouldn't scroll a bit but instead scroll such that middle is in the view.

$(document).ready(function() {
  $('div.top').click(function() {
      $('html, body').animate({
        scrollTop: $("div.middle").offset().top
      }, 1000)
    }),
    $('div.middle').click(function() {
      $('html, body').animate({
        scrollTop: $("div.bottom").offset().top
      }, 1000)
    }),
    $('div.bottom').click(function() {
      $('html, body').animate({
        scrollTop: $("div.top").offset().top
      }, 1000)
    })
});
body,
html {
  width: 100%;
  height: 100%;
  margin: 0;
  display: inline;
}

.top {
  background-color: green;
  height: 100%;
  width: 100%;
  display: flex;
}

.middle {
  background-color: yellow;
  height: 100%;
  width: 100%;
  display: flex;
}

.bottom {
  background-color: red;
  height: 100%;
  width: 100%;
  display: flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top">
  <h1>Top</h1>
</div>
<div class="middle">
  <h1>Middle</h1>
</div>
<div class="bottom">
  <h1>Bottom</h1>
</div>

2 Answers2

0

I took this from a website I have created with an animated scroll which scrolls a whole page at a time. I did update it to work for your specific request.

var scroll = $(window).scrollTop();
$(document).scroll(function(){
  if((window).scrollTop() > scroll){
    //Scroll Down
    if(window.scrollTop() == $('.top').position().top)
      $("HTML, BODY").animate({ scrollTop: $('.middle').position().top }, 500);
    else $("HTML, BODY").animate({ scrollTop: $('.bottom').position().top }, 500);
  } else {
    //Scroll Up
    if(window.scrollTop() == $('.bottom').position().top)
      $("HTML, BODY").animate({ scrollTop: $('.middle').position().top }, 500);
    else $("HTML, BODY").animate({ scrollTop: $('.top').position().top }, 500);
  }
});

Hope it works for you.

Seann
  • 81
  • 1
  • 6
0

An alternative to Seann's answer, found here, is to use a handler on the mousewheel event, so that you don't have to keep track of the previous scroll position:

$(window).bind('mousewheel', function(event) {
    if (event.originalEvent.wheelDelta >= 0) {
        console.log('Scroll up');
    }
    else {
        console.log('Scroll down');
    }
});

There are some drawbacks of this method (most notably that it only works if your users are using a mouse), but depending on your specific needs it might work for you.

Also, as Alex Vand mentioned in the comments, fullpage.js is an excellent library to achieve what you're going for.

Matthew Schlachter
  • 3,250
  • 1
  • 12
  • 26