Infinite scroll in Ruby on Rails and jQuery

Infinite scroll in Ruby on Rails and jQuery

Recently, the use of pagination in the web has been slowly dropping and a new approach called “Infinite scroll” has increased in popularity. The idea is simple, instead of having several buttons to go back and forward, you can navigate through the results by scrolling down to the end of the page. The more you scroll the more results you see.

Implementing an infinite scroll using javascript and jquery is not hard at all. However, making sure that it works in every browser can be a little bit of a pain.

Basically what you need to do is to handle the situation when the user scroll down to the end of the page. In jquery this is done like this:

$(window).on("scroll", scrollHandler);

var scrollHandler = function(){

function scrollBottom(offset){
    if (  document.documentElement.clientHeight + 
          $(document).scrollTop() >= document.body.offsetHeight - offset)
	// your code here

The offset is used to make the results to appear before the user reach to the end of the page.

The problem is that the “scroll” event doesn’t work correctly in mobile, so you need to also handle a equivalent event in mobile.

$(window).on("touchmove", scrollHandlerMobile);

var scrollHandlerMobile = function(){

It is recommendable to have different offsets for the mobile and the regular handler so you make sure both methods doesn’t get fired at the same time. Also, remember to disable the other handler when one is fired.

You can find a working example in Ruby on Rails following the next link:

Leave a Reply

Your email address will not be published. Required fields are marked *