Load Content While Scrolling With jQuery

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.

cdl_capture_2011-09-20-47_ 000

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).

 

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.

 

Sources

http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/

http://www.webresourcesdepot.com/dnspinger/

http://www.9lessons.info/2009/07/load-data-while-scroll-with-jquery-php.html

http://webdeveloperplus.com/jquery/create-a-dynamic-scrolling-content-box-using-ajax/

Leave a comment