Simple infinite scroll

Let's suppose that you have a container containing article teasers and a button labeled "Load More".

This situation is perfect for a straightforward solution. We can use the intersection observer to detect when the "Load More" or next button is in view and click it accordingly. :)

<div class="articles">
<article class="teaser">...</article>
<article class="teaser">...</article>
<article class="teaser">...</article>
<button class="load-more-button">Load more teasing content!</button>
</div>
<div class="scroll-mark"></div>

In the preceding HTML snippet, you can observe a basic scenario along with an additional div named scroll-mark. This is the element that we will be intersecting with.

const observer = new IntersectionObserver((entries, observer) => {
// Loop through the entries. This is 'all' scroll marks,
// but because it's only 1 (since it is an ID) it should be unique.
for (const entry of entries) {
// Check if the entry is intersecting the viewport.
if (entry.isIntersecting) {
// Find the load more button and clickity clack cluck click it. 🐔
document.querySelector('.articles')?.querySelector(".load-more-button")?.click();
}
}
});

const scrollMark = document.querySelector("#scroll-mark");
observer.observe(scrollMark);

So, it is incredibly easy to incorporate this method onto an existing "Load More" button structure.

However, there are some potential drawbacks to consider:

  1. If there are not enough items to load, the intersection will not occur, and the button will remain in the intersecting state, without triggering another click.
  2. If you have already implemented an XHR load more setup, you might not find this method necessary or useful.