Tags

, , ,

To see the code in action there’s a demo here

If you want to load content via AJAX when you scroll down a page the code over on web resources depot might help. In its current state it will make the call for new content when the user scrolls to the bottom of the page, this can make the loading process a little jerky as you get to the bottom of the page then wait for the request to be fulfilled. I’ve made some changes (below) that will fire the request when the user gets near the bottom of the page rather than right at the limit:

$(document).ready(function(){
   var fetching = false;

   function lastPostFunc()
   {
      fetching = true;
      $.post("/page_to_request/"

      ,function(data){
         if (data != "") {
           $(data).appendTo('.wrdLatest');
           setTimeout(function(){
             fetching = false;
           },500);
         }
     });
  };

  $(window).scroll(function(){
    var bufferzone = $(window).scrollTop() * 0.20;
    if  (!fetching && ($(window).scrollTop() + bufferzone > ($(document).height()- $(window).height() ) )){
    lastPostFunc();
  }
});
});

The main change is to fire the request when the user is within the last 20% of the scroll position of the page:

 

 
var bufferzone = $(window).scrollTop() * 0.20;
if  (!fetching && ($(window).scrollTop() + bufferzone > ($(document).height()- $(window).height() ) )){

I’m using the > incase we go past the 20% position but don’t get an event raised. The fetching var is included so we only make one request per update to the page. Otherwise while we’re waiting for the request to come back we can make repeat calls if the scroll position is still at the bottom.

 

To see the code in action there’s a demo here

Advertisements