How to implement infinite scrolling with jQuery and AJAX?

To implement infinite scrolling with jQuery and AJAX, you can follow these steps:

  1. Include jQuery library in your HTML file. You can use a CDN link or download the library and include it locally.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  1. Create a container element to hold the dynamically loaded content and add a placeholder for the loading indicator.
<div id="content"></div> <div id="loading" style="display: none;">Loading...</div>
  1. Write the JavaScript code to handle the infinite scrolling. This code will make an AJAX request to fetch new content whenever the user scrolls to the bottom of the page.
$(window).scroll(function() { // Check if we are near the bottom of the page if($(window).scrollTop() + $(window).height() >= $(document).height() - 100) { // Display the loading indicator $('#loading').show(); // Make an AJAX request to load new content $.ajax({ url: 'load-more.php', // Replace with the URL to fetch more content type: 'GET', dataType: 'html', success: function(response) { // Append the new content to the container $('#content').append(response); // Hide the loading indicator $('#loading').hide(); }, error: function(xhr, ajaxOptions, thrownError) { // Handle error } }); } });
  1. In the above code, load-more.php is the server-side script that returns the additional content to be loaded. You need to create this script and modify it according to your needs.

  2. Style the loading indicator and the content as desired using CSS.

#loading { text-align: center; padding: 10px; background-color: #f0f0f0; border: 1px solid #ccc; } /* Add styles for the content container */

That's it! Now, whenever the user scrolls to the bottom of the page, new content will be fetched and appended to the container element, providing the illusion of infinite scrolling.