Implementing Infinite Scroll in jQuery

Share this article

For as long as I can remember, web developers have turned to good old fashioned pagination when there is a lot of content to show. Don’t get me wrong, pagination is still a very effective way of displaying content, but, in this post, we will discuss an alternative – infinite scroll. This technique, also known as lazy scroll or unpaginate, loads new content via Ajax when the user has finished scrolling through the page’s existing content. Infinite scrolling is used by some of the biggest names on the Internet, including Facebook and Pinterest. In this post, we will talk about building your own jQuery plugin to implement infinite scroll.

Tradeoffs

The advantages are obvious. To get more content, you don’t need to be redirected to a new page (which has a tendency to shift your focus to a different area while the page is loading). By implementing infinite scroll, you are basically controlling the user’s focus on the page! Infinite scroll is not effective in all situations. For example, if a user clicks a link and then uses the browser’s Back button, the user loses his/her position in the stream of data that was loaded over Ajax. One precaution while implementing this feature is to load new content on a new tab or window. A related drawback of infinite scrolling is its inability to save the position on the stream. Suppose you want to share something on a infinite scroll page with your friend via email. You are unable to do so because the URL takes you back to the initial position. Therefore, before you decide to go ahead with it, think about the usability of your website. Additionally, before you implement infinite scrolling, remember that it’s not very search engine friendly. To avoid any issues with respect to visibility on search engines, make sure you provide an alternative with pagination or a sitemap.

Getting Started

We’ll begin by laying out a very simple page. The important parts of the example HTML and CSS are shown below. The remainder of the files can be seen by clicking on the demo link at the end of this tutorial. HTML
<div id="data-container">
  <div class="data-item">
    Hi! I am the first item.
  </div>
  <div class="data-item">
    Hi! I am the second item.
  </div>
  <div class="data-item">
    Hi! I am the third item.
  </div>
  <div class="data-item">
    Ok, this is getting boring.
  </div>
  <div class="data-item">
    Let's try something new.
  </div>
  <div class="data-item">
    How about loading some more items through AJAX?
  </div>
  <div class="data-item">
    Click the button below to load more items.
  </div>
</div>
<div id="button-more" onclick="lazyload.load()">
  Load more items
</div>
<div id="loading-div">
  loading more items
</div>
CSS
#data-container {
  margin: 10px;
}

#data-container .data-item {
  background-color: #444444;
  border-radius: 5px;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  padding: 5px;
  margin: 5px;
  color: #fff;
}

#loading-div {
  display: none;
}

#button-more{
  cursor: pointer;
  margin: 0 auto;
  background-color: #aeaeae;
  color: #fff;
  width: 200px;
  height: 50px;
  line-height: 50px;
}

Basic Workflow

If you have a look at the document that we’ve created, new posts should be loaded when you click on the “load more” button. Here are a few points to consider.
  • A request needs to be made to a URL which returns the new items to be appended to your page.
  • This process should repeat if the button is clicked again, but newer posts should be returned the second time.
  • New posts should be provided at every subsequent request, until there are no more posts to show.
  • When there are no more posts left, you should tell the user that he has reached the end.

Ajax Pattern

Ideally, you must declare a variable to store the page number, which in turn changes the URL to send the request to. In our demo, we have three such pages – 2.html, 3.html, and an empty 4.html for demonstration purposes. When you click on the button to load more posts, there is some time before the request goes through successfully and new items are loaded. In this case, we hide the load button, and show some text saying that the new items are being loaded:
$(buttonId).hide();
$(loadingId).show();

Appending Data to the Page

First, we need to undo the changes that we performed when the request was in progress, namely, showing the “load more” button again and hiding the text. Secondly, we need to append the response that we received to the list of items already present on the page. Note that in the demo, we receive HTML markup directly to keep things simple. You can send a JSON response too, adding more variables like a message or a status. The append code is shown below.
$(buttonId).show();
$(loadingId).hide();
$(response).appendTo($(container));
page += 1;

Handling End of Data

Once you reach the end of your posts, you need to show your user that there are no more posts to load on the page. This can be done in many ways. We can send the status through a code or message embedded within the response itself. However, as we use HTML markup directly in this example, an empty response marks the end of the stream.
$.ajax({
...
  success: function(response) {
    // What to do if the response is empty
    if (response.trim() == "") {
      $(buttonId).fadeOut();
      $(loadingId).text("No more entries to load!");
      return;
    }
    // Do something if the response is right.
  },
...
});

Conclusion

The demo that we have come up with is very basic in nature, and we can do far better if we put in some more effort. First, we can remove the button altogether and call the function when the user scrolls down to the end of the page. This would remove an extra step of the user clicking the button and make the whole process faster. Secondly, we can just send the raw data through JSON and create the markup using jQuery itself. For example:
$.each(response.items, function(index, value) {
  $("<div />", {
    "class" : "data-item",
    "text" : value
  });
});
Finally, the JSON response could consist of a message stating whether the request went through correctly, the data, and whether there are more posts to load. This is a more efficient way of sending a response in this case. For more information on infinite scroll, you could visit this website dedicated to the cause. It contains general information about the idea and existing tools that you can use to implement it in your website. A live demo can be found on GitHub pages. The code is also available on GitHub.

Frequently Asked Questions on Implementing Infinite Scroll with jQuery

How can I implement infinite scroll with jQuery and AJAX?

Implementing infinite scroll with jQuery and AJAX involves a few steps. First, you need to set up your HTML structure. This will include a container for your content and a loading spinner that will be displayed while new content is being loaded. Next, you need to set up your AJAX call. This will be responsible for fetching new content when the user scrolls to the bottom of the page. You’ll need to specify the URL of the server-side script that will return the new content, as well as a success function that will append the new content to your container. Finally, you need to set up your scroll event listener. This will detect when the user has scrolled to the bottom of the page and trigger the AJAX call.

What are the benefits of using infinite scroll?

Infinite scroll offers a seamless browsing experience for users. It eliminates the need for pagination and allows users to consume content continuously without any interruptions. This can be particularly beneficial for websites with a lot of content, such as social media platforms or news sites. It can also help to keep users engaged and on your site for longer periods of time.

Can I use infinite scroll with any type of content?

Yes, you can use infinite scroll with any type of content that can be loaded dynamically. This includes text, images, videos, and even complex HTML structures. However, it’s important to note that infinite scroll may not be suitable for all types of content. For example, if your content needs to be consumed in a specific order, or if users need to be able to easily navigate back to specific points in the content, then infinite scroll may not be the best choice.

How can I handle errors when implementing infinite scroll?

When implementing infinite scroll, it’s important to handle potential errors that may occur during the AJAX call. This can be done by including an error function in your AJAX setup. This function will be called if the AJAX request fails for any reason. You can use this function to display an error message to the user, or to retry the AJAX call.

How can I test my infinite scroll implementation?

Testing your infinite scroll implementation can be done in a few ways. One way is to manually scroll through your content and ensure that new content is being loaded correctly. You can also use developer tools in your browser to monitor the AJAX calls and ensure that they are being made correctly. Additionally, you can use automated testing tools to simulate user scrolling and verify that your implementation is working as expected.

Can I customize the loading spinner in my infinite scroll implementation?

Yes, you can customize the loading spinner in your infinite scroll implementation. This can be done by modifying the CSS for the spinner element. You can change the size, color, and animation of the spinner to match the look and feel of your website.

How can I implement a “Load More” button with infinite scroll?

Implementing a “Load More” button with infinite scroll involves a few modifications to the standard infinite scroll setup. Instead of triggering the AJAX call when the user scrolls to the bottom of the page, you would trigger it when the user clicks the “Load More” button. You would also need to hide the loading spinner until the “Load More” button is clicked.

Can I use infinite scroll with a database?

Yes, you can use infinite scroll with a database. The server-side script that you specify in your AJAX call would be responsible for querying the database and returning the new content. This allows you to dynamically load content from your database as the user scrolls through your site.

How can I prevent duplicate content when using infinite scroll?

Preventing duplicate content when using infinite scroll can be achieved by keeping track of the last piece of content that was loaded. This can be done by including a parameter in your AJAX call that specifies the ID or timestamp of the last piece of content. Your server-side script would then use this parameter to ensure that it only returns new content.

Can I implement infinite scroll without jQuery?

Yes, it’s possible to implement infinite scroll without jQuery. You can use pure JavaScript to set up your scroll event listener and AJAX call. However, jQuery simplifies the process and makes your code more concise and easier to read. If you’re comfortable with JavaScript and prefer not to use jQuery, you can certainly implement infinite scroll without it.

Shaumik DaityariShaumik Daityari
View Author

Shaumik is a data analyst by day, and a comic book enthusiast by night (or maybe, he's Batman?) Shaumik has been writing tutorials and creating screencasts for over five years. When not working, he's busy automating mundane daily tasks through meticulously written scripts!

infinite scroll
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week