Last Updated: February 25, 2016
·
471
· one-aalam

How i'd infinitely scroll

A vanilla Javascipt solution i discovered pretty useful while implementing stuff which reacts to window scroll.

Define a method to calculate if user is low enough on a page for our action trigger...

function canNext() {
      var offset = 30, // distance from page bottom
             pageHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight),
             viewportHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0,
             scrollHeight = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
     // Trigger for scroll, or any thing i'd like to call as user reaches bottom
     return pageHeight - viewportHeight - scrollHeight < offset; 
}

...and a method that utilises this:

function doScroll(){
     if(!canNext()) return checkScroll();
     // my scroll action....
}

Observe clock instead of scroll for triggering this

function checkScroll(){
         setTimeout(doScroll, 100);
)

checkScroll();