Infinite scrolling using Intersection Observer

Spread the love

In a previous blog post, we introduced the Intersection Observer API , which is used to asynchronously tell us when an element intersects with another.

 In this post, we will show just how easy it is to add infinite scrolling to dynamically load more content to when the user scrolls to the bottom of the page. The code for this demo is available here

HTML

For the HTML, we need a container to add elements to and we need an element to tell us when the user has reached the bottom of the page.

div id="infinite-container">
</div>

<div id="infinite-indicator">
  <h2 class="text-center">Loading More ...</h2>
</div>

In the above code, we have a div with id “infinite-container” which will hold all the content and an div with id “infinite-indicator”  which when visible means that the user has scrolled to the bottom of the page.

Javascript

First, we create an instance of the intersection observer

// create an intersection observer, it calls the loadMore function when the intersection of the element changes
const observer = new IntersectionObserver(loadMore);

Next we create references to the div elements

// element to detect end of page
var indicator = document.querySelector('#infinite-indicator');

// element which contains the images
var container = document.getElementById('infinite-container');

Next we start observing

observer.observe(indicator);

We also have an array of images which will be loaded by the loadMore function

// array of images
var img_arr = [
'images/ishan-seefromthesky-1113275-unsplash.jpg',
'images/eberhard-grossgasteiger-1254739-unsplash.jpg',
'images/paula-russell-1253027-unsplash.jpg',
'images/artem-sapegin-1252570-unsplash.jpg',
'images/sylas-boesten-1253896-unsplash.jpg',
'images/will-turner-1254397-unsplash.jpg'
]

Next we have to implement the loadMore function which is called when the infinite-indicator div is visible.

function loadMore(arr) {
  // if the element is intersectingif(arr[0].isIntersecting){
  // get a random index from the array
  var random = Math.floor(Math.random()*6);

  // create an image and append it to the container and set the source of the image
  var img = document.createElement('img');
  container.append(img);
  img.src = img_arr[random];
  }
}

In the above code, we first check if the element isIntersecting, which means that its visible, if it is ,we then get a random index, create a new image and add it to the container.