Open In App

How to create Infinite Scrolling using onScroll Event in JavaScript?

Last Updated : 25 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 JavaScript

Output:

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



Next Article

Similar Reads

three90RightbarBannerImg