November 23, 2015 2:30 pm

Load data while Scrolling Page down with jQuery AJAX

In this tutorial, I will be showing you how to load data while scrolling the page down (the so-called infinite scrolling that Facebook and other companies employ). In this particular article, I will only be showing you how to trigger certain application logic when the user scrolls to the bottom of the page or to the bottom of a particular scrollable element. The examples would include infinite scrolling with jQuery and with Vanilla JavaScript.

infinite-scroll

[wpdm_file id=155]DEMO

Data

As I am not going to make the back-end now (this will arrive in a future article) the data would be contained in a JSON file which we are going to request with Ajax and load certain items from it.

{

  "products" : [
    {
      "name": "Beggar Sandwich",
      "price": 0.50,
      "image" : "beggar-sandwich.png",
      "description" : "Especially nice if you are unemployed or a student"
    },
    //more items}

Here is how the products.json file looks. It consists of a products array which contains objects with data related to different fictional products.

Infinite scrolling with jQuery when page’s bottom has been reached

We create an object and we add the infiniteScroll.handleScroll method to execute each time the user scroll the page and we load our initial items to the page.

var infiniteScroll = {

initialize: function() {
$(document).on("scroll", this.handleScroll);
this.loadStuff('products.json');
},

The handleScroll method checks if the currently scrolled distance from the top, combined with the height of the screen is greater than the total height of our body element and if they are greater – we know the user has reached the bottom of our page. So, we load more products in or whatever you want to present to your users.

handleScroll: function() {

if ($(document).scrollTop() + window.innerHeight >= document.getElementsByTagName("body")[0].scrollHeight ) {
//logic when user has scrolled to the bottom of the page
++infiniteScroll.data.currentPage;
infiniteScroll.loadStuff('products.json');
}
},

Finally, we call the initialize method as soon as the DOM has loaded (we do this because otherwise the elements on the page that we may want to select and change may not exist yet)

$(function() {
infiniteScroll.initialize();

})

Infinite scrolling with Vanilla JavaScript when page’s bottom has been reached

The process is quite similar except some minor differences in function/method/property names.

We again create the initialize method but this time we use the document.addEventListener method to execute handleScroll when the user scrolls.

var infiniteScroll = {

initialize: function() {
document.addEventListener("scroll", this.handleScroll);
this.loadStuff('products.json');
},

In our handleScroll method, we check for the same thing but this time use document.getElementsByTagName(“body”)[0].scrollTop instead of $(document).scrollTop() since the latter is a jQuery method.

handleScroll: function() {

if (document.getElementsByTagName("body")[0].scrollTop + window.innerHeight >= document.getElementsByTagName("body")[0].scrollHeight ) {
//logic when user has scrolled to the bottom of the page
++infiniteScroll.data.currentPage;
infiniteScroll.loadStuff('products.json');
}
},

Finally, we use document.addEventListener one more time, this time to initialize our logic when the DOM is available for manipulation (as an alternative to $(function() { ).

document.addEventListener("DOMContentLoaded", function() {
infiniteScrollinitialize();
})

Infinite scrolling with Vanilla JavaScript when the bottom of a scrollable element is reached

Again, we need to implement several minor tweaks for this.

Starting our logic again happens when the DOM tree is available for manipulation:

document.addEventListener("DOMContentLoaded", function() {

infiniteScroll.initialize();
})

This time, we do not add the event listener for scrolling to the document but to our scrollable div:

initialize: function() {
document.getElementById("products").addEventListener("scroll", this.handleScroll);
this.loadStuff('products.json');
},

In our handleScroll method we check if the currently scrolled distance from the top of our products element, combined with the height of our products element is greater than the total height of our products element and if they are greater – we know for certain that the user needs to see more beautiful things.

handleScroll: function() {

if (document.getElementById("products").scrollTop + parseInt(document.getElementById("products").style.height, 10) >= document.getElementById("products").scrollHeight ) {
//logic when user has scrolled to the bottom of the page

++infiniteScroll.data.currentPage;
infiniteScroll.loadStuff('products.json');
}
},

Finally, I should mention that for this to work your desired element has to be scrollable; which means that it needs to have the overflow property set to auto or scroll.

Here is a demo of the CSS properties of our scrollable element:

<div id="products" style="display:inline-block;border:1px solid #eee;background-color:crimson;height: 600px;overflow-y:auto;"></div>

Conclusion

In an upcoming article, I am going to write how to combine this ability of jQuery and front-end JavaScript to create infinite scrolling that we have discussed here with the PHP’s ability to show data from a database when needed to create truly infinite scrolling.

I hope you have learned a thing or two and if you have any tips, suggestions, critique or ideas, do not hesitate to write a comment in the form below.

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories:

3 responses to “Load data while Scrolling Page down with jQuery AJAX”

  1. Max John says:

    How about if I want the page to start loading when the scroll reaches half of the page or 70 percent of the page instead of completely down ?

  2. Max John says:

    How about if I want the page to start loading when the scroll reaches half of the page or 70 percent of the page instead of completely down ?

    • Ivan Dimov says:

      For half of the page, you just have to divide the scroll height by two:
      $(document).scrollTop() + window.innerHeight >= document.getElementsByTagName(“body”)[0].scrollHeight / 2

      Similarly, you can do such a change with 70 percent of the page.

      Note that the article was not entirely ready for launch so some issues may arise.

Leave a Reply

Your email address will not be published. Required fields are marked *