SyntaxStudy
Sign Up
jQuery Intermediate 4 min read

Infinite Scroll

Infinite Scroll

Load more content automatically as the user approaches the bottom of the page — replaces traditional pagination for feeds.

Example
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;
    });
  }
});
Pro Tip

Use a 300px threshold so content loads before the user reaches the absolute bottom — smoother UX.