Categories
JavaScript Answers jQuery

How to Add Infinite Scrolling with jQuery?

Spread the love

To add infinite scrolling with jQuery, we can detect when we scrolled to the bottom of the page with the scroll method.

To do this, we write the following HTML to contain our content:

<div id="lipsum">
</div>

Then we can add some content into the div when we scrolled to the bottom of the page by writing:

const arr = [...Array(30)].fill().map((_, i) => i)
for (const n of arr) {
  $('#lipsum').append(`<p>${n}</p>`)
}

$(window).scroll(() => {
  if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
    for (const n of arr) {
      $('#lipsum').append(`<p style='background-color: red'>${n}</p>`)
    }
  }
});

We first add some content to the div with:

const arr = [...Array(30)].fill().map((_, i) => i)
for (const n of arr) {
  $('#lipsum').append(`<p>${n}</p>`)
}

Then we detect when we scroll to the bottom of the page by calling $(window).scroll with a callback.

In the callback, we check if we scrolled to the bottom of the page with:

$(window).scrollTop() >= $(document).height() - $(window).height() - 10

And if that’s true , we add some content with the for-of loop.

scrollTop gets the scroll position of the page.

And $(document).height() — $(window).height() — 10 is the position at the bottom of the page in pixels.

Now we should see new content displayed when we scrolled to the bottom of the page.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *