Open In App

How to create Infinite Scrolling using onScroll Event in JavaScript ?

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

We have seen many shopping sites that list some limited number of products(using a back-end API) when we open the website and scroll down to the bottom, we see that more products are fetched and displayed, and as we scroll even further even more products are loaded and fetched and it keeps happening till there are no more products to be displayed. This is something that we call Infinite Scrolling. We will implement this similar feature in Javascript using the onScroll event.

Now let’s implement Infinite Scrolling.

Approach:

  • We will declare a variable pageNum and initialize its value as 1.
  • We will create a scrollable div element with the class container, inside this div we will show all the results fetched from an API. We will use a paginated API with endpoint https://api.github.com/repositories/1300192/issues?page=${pageNum}.
  • We will create a function fetchData which will be responsible for fetching data from the API.
  • To this container element, we will attach onscroll event and we will check that when we have reached the end of the container we will increment pageNum by 1 and fetch more data by calling the function fetchData. We will check that if Math.ceil(container.clientHeight + container.scrollTop) >= container.scrollHeight then it means that we have reached the end of the container.
     

 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Page Title</title>
    <link rel="stylesheet" href="./src/styles.css" />
</head>
  
<body>
    <div class="container">
        <h1>GeeksforGeeks Infinite Scrolling</h1>
        <div class="result-container"></div>
        <div class="loading-container"></div>
    </div>
    <script src="src/index.js"></script>
</body>
  
</html>


CSS




body {
    font-family: sans-serif;
    background-color: green;
}
  
.container {
    background-color: white;
    width: 500px;
    height: 300px;
    border: 2px solid black;
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
    padding: 30px;
    overflow-y: scroll;
}
  
.loading-container {
    margin-top: 10px;
    font-family: Cambria, Cochin, Georgia, 
        Times, "Times New Roman", serif;
    font-size: 30px;
    text-align: center;
}
  
.search-data {
    margin-top: 10px;
    height: 30px;
    font-family: Verdana, Geneva, 
        Tahoma, sans-serif;
}


Javascript




let pageNum = 1;
let isLoading = false;
const container = document.querySelector(".container");
const loadingContainer =
    document.querySelector(".loading-container");
const resultContainer =
    document.querySelector(".result-container");
  
function fetchData() {
    if (isLoading) return;
    isLoading = true;
    loadingContainer.innerHTML = "Loading ...";
    fetch(`https://api.../issues?page=${pageNum}`)
        .then((res) => {
            res.json().then((finalRes) => {
                finalRes.forEach((item) => {
                    const resultDiv = document.createElement("div");
                    resultDiv.textContent = item.title;
                    resultDiv.classList.add("search-data");
                    resultContainer.appendChild(resultDiv);
                });
                isLoading = false;
                loadingContainer.innerHTML = "";
            })
                .catch((e) => {
                    isLoading = false;
                    loadingContainer.innerHTML = "";
                });
        })
        .catch((err) => {
            isLoading = false;
            loadingContainer.innerHTML = "";
        });
}
  
container.onscroll = () => {
    if (isLoading) return;
  
    if (
        Math.ceil(container.clientHeight 
            + container.scrollTop) >=
            container.scrollHeight
    ) {
        pageNum++;
        fetchData();
    }
};
  
fetchData();


Output:

Infinite Scrolling with onscroll event

Explanation: For the first time some result is fetched and displayed and as we scroll down further more data is fetched and displayed.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads