Infinite Scroll
Track the current page number with .data() on the container and load more items as the user scrolls to the bottom.
Track the current page number with .data() on the container and load more items as the user scrolls to the bottom.
$("#feed").data("page", 1);
$(window).on("scroll", function() {
const atBottom = $(window).scrollTop() + $(window).height()
>= $(document).height() - 200;
if (atBottom && !$("#feed").data("loading")) {
const page = $("#feed").data("page") + 1;
$("#feed").data({ page, loading: true });
$.getJSON("/api/posts?page=" + page, function(posts) {
renderPosts(posts);
$("#feed").data("loading", false);
});
}
});
Use a loading flag in .data() to prevent multiple concurrent AJAX requests.