automatically load older posts when scrolling down like 9gag on blogspot

4.9k Views Asked by At

This is my blog: http://9gago.blogspot.com/ it is a blog made out of bloggger/blogspot I want this feature wherein you scrolldown it will load the older posts so that the user doesnt have to click on older posts everytime it reaches the last post of the page. Here's a site that does exactly that http://9gag.com/ or used to have it.

1

There are 1 best solutions below

0
On

I've got one implementation you might like. There are several ways to do this with several more variations.

First, you need to store the keys of the data that you displaying in the grid somewhere. This assumes that you've got a key that is sequential in nature. An auto incrementing integer would work.

The markup in your grid might look something like this:

<div class="content" id="7">some stuff</div>
<div class="content" id="8">another row of stuff</div>
<div class="content" id="9">another row of stuff</div>

Then you need a function to show a "loading" icon that will also grab the next batch of data. Use the id from the last element in the grid to run a query on the server side that would grab the next 20 (or however many you want) rows of data.

function lastRow()
{
    $('div#lastRowLoader').html('<img src="spinner.gif"/>');
    $.post('dataUrl?action=getNextRows&lastId=' + $('.content:last').attr('id'), 
      function(data){
          if (data != '') {
             $('.content:last').after(data);           
          }
          $('div#lastRowLoader').empty();
      });
  };

Then one last function to detect the user has scrolled down to the end of the page.

$(window).scroll(function(){
    if  ($(window).scrollTop() == $(document).height() - $(window).height()){
      lastRow();
    }
});

Clearly, you need some code to take what you're post returns to load the data into your page through the DOM. I've written this code to show you conceptually what needs to happen. Your markup will be different and your grid could be anything from Sencha Ext JS to something hand rolled.

Hopefully this is enough to get the wheels turning for you.