Infinite scrolling using Intersection Observer

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


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 id="infinite-indicator">
  <h2 class="text-center">Loading More ...</h2>

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.


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


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

// array of images
var img_arr = [

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');
  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.

Share this!

Leave a Reply

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