Infinite Scroll
Load more content automatically as the user approaches the bottom of the page — replaces traditional pagination for feeds.
Load more content automatically as the user approaches the bottom of the page — replaces traditional pagination for feeds.
let page = 1, loading = false;
$(window).on("scroll", function() {
const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
if (scrollTop + clientHeight >= scrollHeight - 300 && !loading) {
loading = true;
$.getJSON(`/api/posts?page=${++page}`, function(data) {
if (data.posts.length === 0) { $(window).off("scroll"); return; }
data.posts.forEach(p => $("#feed").append(`<article class="post">${p.title}</article>`));
loading = false;
});
}
});
Use a 300px threshold so content loads before the user reaches the absolute bottom — smoother UX.