How to implement infinite scroll

January 6, 2015

Infinite scroll, one of those things you either hate or love. If you’re unfamiliar with the name, I’m pretty sure you’ve seen the concept. It’s basically loading data asynchronously while the user is scrolling. Usually it’s used instead of pagination, so when the user reaches down to say 80% of the page, you load the next set of items without the need of user input.

The good thing with this approach is that it’s usually faster than reloading the page for the next page, the browser doesn’t need to re-render the whole page, it’s a continuous flow. The bad thing, the user needs Javascript.

I’m working on a side project, where I wanted to implement infinite scroll. There’s a lot of plugins out there that one can use, but usually when I’m building something of my own, I reinvent the wheel, why? Because I like building things.

The concept is fairly easy to understand, and so is the coding. All we need is an event binded to the scrolling of the page, and then every time the scroll position is near the end of the page, load in more content. We’ll be using scrollTop to get the scroll position (which is relative to the top of the window) and then we’ll need the body height (the height of the document), offset the body height with the window height and we’ll get a figure that we can compare against the body’s height. Easy right?

// Fetch variables
var scrollTop = $(document).scrollTop();
var windowHeight = $(window).height();
var bodyHeight = $(document).height() - windowHeight;
var scrollPercentage = (scrollTop / bodyHeight);

// if the scroll is more than 90% from the top, load more content.
if(scrollPercentage > 0.9) {
	// Load content
}

I’ve created a quick-and-dirty wrapper around this concept as a gist. This is almost the identical code that I used for my infinite scroll, but I’ve removed some project specific code (pagination counter, ajax request, fetch vars from attributes etc.) that wasn’t needed to show the concept.

Tags