Search code examples
javascriptjqueryscrollsmooth-scrolling

Automatic scroll javascript


I want the viewer to scroll automatic to a section, when he scrolls. So that the viewer can't see a screen between two sections (each section has the height of 1 vh). Only the last section #contact has not the size of 1 vh.

I have a script working, but there has to be a better and cleaner way. This code works in Chrome, but I have to wait a while untill I can scroll again. It is not working with Firefox

Could someone tell me how it can be done properly or tell me if there is a plug-in for this? I can't find anything!

var lastScrollTop = 0;
$(window).scroll(function(event){
var height = $(window).scrollTop();
var vheight = $(window).height();

if (height >= lastScrollTop){

if(height > 1  && height < 100) {
    $('html,body').animate({
      scrollTop: $('#mission').offset().top
    }, 500); 
}


if(height > 2 * vheight + 1 && height < 2 * vheight + 200){
    $('html,body').animate({
      scrollTop: $('#about').offset().top
    }, 500); 
}

if(height > 3 * vheight + 1 && height < 3 * vheight + 200){
    $('html,body').animate({
      scrollTop: $('#contact').offset().top
    }, 500); 
    $('#scrollAbout').hide(500);

}

} else {
  var docheight = $(document).height(); 
  docheight -= vwheight;

  if(height < vheight - 1  && height > vheight - 200) {
      $('html,body').animate({
        scrollTop: $('#home').offset().top
      }, 500); 
  }



  if(height < 3 * vheight - 1 && height >  3 *vheight - 200){
      $('html,body').animate({
        scrollTop: $('#case-studies').offset().top
      }, 500); 
  }

  if(height < docheight - 1 && height > docheight - 100){
      $('html,body').animate({
        scrollTop: $('#about').offset().top
      }, 500); 
      $('#scrollAbout').show(500);

  }


}
lastScrollTop = height;

Solution

  • It sounds like you are looking for something like the fullPage.js library.

    More specifically this scenario, where the last section is not full screen but yet, it still being scrolled automatically. You can achieve that by using the fp-auto-height class as detailed in the documentation.

    Here's a codepen