Ask your JavaScript questions! Pay money and get answers fast! (more info)

How to provide infinite scrolling like Facebook or Pinterest? JavaScript

  • SOLVED

Client wants page to:

1.) show 20 items

2.) if visitor scrolls to the bottom of the page, then do an Ajax query and get another 20 items.

The Ajax call is easy enough, but I can't remember how to detected that someone has scrolled to the bottom.

Answers can be either jquery or pure Javascript.

Answers (1)

2012-08-17

Ross Wilson answers:

This assumes that the page can scroll to begin with (otherwise document.height and window.height are always equal)

$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
//get more posts here
}
});


If you want to detect when the user is with 100 pixels of the bottom of the page just do this

$(window).scroll(function(){
if ($(window).scrollTop() +100 == $(document).height() - $(window).height()){
//get more posts here
}
});


Basically $(document).height() - $(window).height() gives you the amount of scrolling that can be done, and scrollTop gives you the current scroll position.


Lawrence Krubner comments:

That worked perfectly. Thank you.