Last Updated: February 25, 2016
·
552
· 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();

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside