Facebook Like Automatic Content Loading on Scrolling

8

We have all seen the automatic content loading used in Facebook. Let’s see how easily it can be implemented using jQuery.

View Demo

What we do to achieve this is whenever a scroll event is fired, check if we have reached the bottom of the page, and if we are at the bottom, call our ajax function to load the content.

 

$(document).scroll(function(){
    if ($(window).scrollTop() + $(window).height() == $(document).height()) {
        // Reached page bottom. Call the ajax function or any other foo here.
    }
});

 

.scroll() is fired every time the user scrolls the page.
$(window).scrollTop() returns the number of pixels hidden ‘above’ when the page is scrolled.
$(window).height() gives the height of the window. Same as window.innerHeight
$(document).height() gives the total height of the page.

Well, that’s that. Cool, right?

Facebook content Loading

Automatic Content Loading in Facebook

Incoming search terms:

If you like this post, please share it with your friends
    • http://www.euqueroaprender.ismywebsite.com/ Eduardo Oliveira

      Worked good to me. I had used some part from this too: http://tomsbigbox.com/wordpress-load-more-posts-on-page-scroll/
      all php was from there (because i wanted to load wordpress posts), and i had used the “halfway” variable too and to load post in the middle of the page, not in the end only.
      Your post was very useful to me, thank you!

    • George

      What about the ajax_processor.php file? What does it contents?, btw great post.

    • Saurabh

      @George, thanks :) ajax_processor.php is just a simple file that generates random paragraphs of text and outputs it. I put it so new random content is shown each time page is scrolled. Try opening that file in browser here -> http://rebugged.com/code/auto-content-loading-on-scroll/ajax_processor.php

    • http://www.example.com Rich

      Would this work in an iFrame – ie a Facebook application?

      Thanks

    • Chayan

      what will happen when the content is finished.

    • http://rebugged.com/ Jsx

      In the case of this example, the content will neverffinish, as we are dynamically generating content.

    • Chayan

      But in my case, the content will finished. Could you pls help me to solve this situation.

    • http://rebugged.com/ Jsx

      If you are using a limit query to fetch the content, once the content is finished, the limit query will be returning null. So you can check if the ajax call is returning null or empty string and do the appropriate action.

    © Written by JSX
    Hosted by Intellwiz