SyntaxStudy
Sign Up
jQuery Infinite Scroll with .data()
jQuery Advanced 5 min read

Infinite Scroll with .data()

Infinite Scroll

Track the current page number with .data() on the container and load more items as the user scrolls to the bottom.

Example
$("#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);
    });
  }
});
Pro Tip

Use a loading flag in .data() to prevent multiple concurrent AJAX requests.