How to implement infinite scrolling in Javascript

Infinite scrolling is a feature that allows you to load some pics on a website and then load more once the user reaches the end of the webpage (like we see on Pinterest).

We will start off by creating three files, index.html, style.css, and app.js. Just to let you know, I will be using the random Dog API (a free API) in order to generate random dog pictures.

Then, we will add a simple markup on the index.html file, like this:

<div>
</div>

We don’t need much in index.html and style.css since the main logic will go in the app.js file. Our style.css is also simple; it has the following styles:

.container{
    display: flex;
    flex-wrap: wrap;
}

img{
    margin:5px;
    width:200px;
    height:200px;
}

You can always add more styles to make the webpage look fancier.

Next, we’ll start with the app.js file, which is this project’s backbone. But, first, we need to select our container from the HTML file because that is where we will be showing our images:

const container = document.querySelector('.container');

Then, we’ll define a function (loadImages()) and give it a default numImages parameter to 10 (to show 10 images):

function loadImages(numImages = 10){
   let i=0;
    while(i < numImages){
    fetch('https://dog.ceo/api/breeds/image/random')
    .then(response=>response.json())
    .then(data=>{
    const img =  document.createElement('img');
    img.src = `${data.message}`
    container.appendChild(img)
    })
    i++;
   }   
  }

loadImages();

Notice that we’ve used a while loop here to load 10 images at first. Once 10 image elements have been created, we can check for the scroll event of the window to see if we need to load more images.

To achieve this behavior, we will be make use of three window properties:

  • window.scrollHeight: Indicates the height of the entire document
  • window.scrollY: Indicates how far the document has been scrolled from the top
  • window.innerHeight: Indicates the visible part of the window

The diagram below better illustrates these properties:

widget

Looking at the diagram above, we can work out a formula:

If the sum of scrollY and innerHeight is greater or equal to the scrollHeight, it means we have reached the end of the document, and we need to load more images.

window.addEventListener('scroll',()=>{
    console.log(window.scrollY) //scrolled from top
    console.log(window.innerHeight) //visible part of screen
    if(window.scrollY + window.innerHeight >= 
    document.documentElement.scrollHeight){
    loadImages();
    }
})

Code

Copyright ©2024 Educative, Inc. All rights reserved