To implement infinite scrolling with jQuery and AJAX, you can follow these steps:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="content"></div>
<div id="loading" style="display: none;">Loading...</div>
$(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
}
});
}
});
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.
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.