We generally have lots of content to present but can not load all of it at once as it may take too long.

I always loved the dZone’s Ajax content loading while scrolling feature and created a similar one using jQuery.

I’m pleased to share with WebResourcesDepot readers (Check the demo – scroll down to see new content in the demo)

This Ajax auto content loading can very be handy in almost every project. Don’t forget to bookmark it (del.icio.us link).

jQuery Load Content While Scrolling

Download Load Content While Scrolling With jQuery

Download package includes a working demo coded with ASP with a test MySQL database. ASP code is just a simple query so you can switch it with a one you like easily.

 

What is loading content while scrolling?

When we are scrolling down a webpage, the code recognizes that you are at the bottom and auto-loads new content.

Why to use it?

It helps increasing the initial load speeds of pages faster and users will have to load only the content they see.

How it works? (Check the demo)

In our case, we have DIVS holding contents where every DIV ID is content’s database ID.

  • Content structure is like:

<div class="wrdLatest" id=9>content</div>
<div
class="wrdLatest" id=8>content</div>

  • We create a function sending a query to a dynamic file with the DIV ID of the latest wrdLatest DIV (and also put a loader image):

function lastPostFunc()
{
    $('div#lastPostsLoader').html('<img src="bigLoader.gif">');
    $.post("scroll.asp?action=getLastPosts&lastID=" + $(".wrdLatest:last").attr("id"),
   

    function(data){
        if (data != "") {
        $(".wrdLatest:last").after(data);           
        }
        $('div#lastPostsLoader').empty();
    });
}; 

  • When a user scrolls down, we understand that the scroller is at the bottom with teh function below and fire the lastPostFunc function.

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

I have applied the demo to the DNSPinger service. Simply scroll down to see new content loading.

Dependencies

This is a very simple code that uses jQuery’s great dimensions plugin that helps us understand that we are at the bottom of the page. Update: Dimensions plugin is included with jQuery 1.2.6 and no need to include it as an extra.

Besides that, you can improve the code to detect the users sceen-size and load your initial content according to that screen size.

Answerbase
WebResourcesDepot Feed