Recently I was looking around for a quick way to implement infinite scrolling and found the jscroll plugin for jquery.
The problem was that all the examples online were broken and they all seemed to copy and paste from each other which made it difficult to figure out what worked. Finally I got something working and just wanted to post the options that I was using for anyone else that needs help with it.
The HTML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>Welcome To the Site</h1> | |
<div class="infinite-scroll"> | |
This is a sentence | |
<a class="next-link" href="/path/to/next/page">Link to next page response</a> | |
</div> |
The JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log('Starting the scrolling script'); | |
$('.infinite-scroll').jscroll({ | |
debug: false, // Show debugging info in console | |
autoTrigger: true, // Start fetching without clicking a "next" link | |
autoTriggerUntil: false, // How many pages to auto trigger until requiring "next" click | |
loadingHtml: '<img src="/images/loading.gif" alt="Loading" />', // What to show when loading responses | |
padding: 20, | |
nextSelector: 'a.next-link:last', // The link with an href to the next response to load | |
callback: function () { | |
// Function called when the response is loaded | |
console.log('callback was called'); | |
} | |
}); |
Backend API
Depending on your framework, create an endpoint that returns a response containing your content and a link to the next item to load (a link element) at the end. It is important that this response contains the HTML necessary for the item you are rendering and is not just a JSON response.