rss feed Twitter Page Facebook Page Github Page Stack Over Flow Page

Add content dynamically by Scrolling using jQuery

One of the new way to efficiently populate a web page is to dynamically load the content when the user reach the bottom of the page or as the user scroll down the page. Many website, like google reader or facebook, are using this technique, and you might consider this concept if you have a website that generates lots of content.

The Concept

jQuery provides all the method we need in order to check where the scroll is located. Since we need the scroll to be at the bottom in order to add contents, we have to find out the position and then validates if we have to trigger the ajax call to load additional content.

Now to reach the bottom, we simply need to calculate if the top of the page equals to the height of the page minus the height of the current window. For example If the height of the page $(document).height()) is 4000 pixels and the height of the window $(window).height() is 500 pixels, so when you reach the bottom of the page the top of the page $(window).scrollTop() will be 3500 pixels.

Easy no? Let's see some code now.

HTML

<section>
  <article>
    <p>some text ....</p>
    <p>some text ....</p>
    <p>some text ....</p>
    <p>some text ....</p>
    <p>some text ....</p>
  </article>
</section>

CSS

article {
  font-size: 13px;
}
div {
  bottom: 10px;
  display: none;
  position: fixed;
}
section {
  margin: 0 auto;
  padding: 10px;
  width: 350px;
}

Javascript

$(window).scroll(function() {
  if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
    $.ajax({
      cache: false  
      url: 'more.html',
      beforeSend: function ( xhr ) {
        $('div').show();
      },
      success: function(data) {
        $('article').append(data);
        $('div').fadeOut();
      }
    });
  }
});