Approach to Implement Infinite Scroll using JavaScript Intersection Observer API

  • HTML Structure: The HTML structure contains a div element with the id “list” where dynamically generated items will be appended. There’s also a p element with the id “watch_end_of_document” which serves as a sentinel element to observe the end of the document.
  • CSS Styling: Some basic CSS styling is applied to the items displayed in the list. Even indexed items have a light gray background for better visibility.
  • Function addItems(): This function dynamically creates p elements with the class “item” and appends them to the “list” div. It creates a document fragment to optimize performance by reducing DOM manipulations. Each item’s text content is set to a formatted string including the item index and “w3wiki“.
  • An Intersection Observer instance is created to observe the sentinel element with the id “watch_end_of_document“. When the sentinel element comes into view (i.e., when it intersects with the viewport), the addItems() function is called to load more items.
  • When the page loads, the initial set of items is loaded. As the user scrolls down, triggering the intersection of the sentinel element with the viewport, more items are dynamically loaded.

Example: Below is an example to implement Infinite Scroll using JavaScript Intersection Observer API:

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="styles.css" />
</head>

<body>
    <div id="list"></div>
    <p id="watch_end_of_document"></p>
    <script src="script.js"></script>
</body>

</html>
CSS
/* styles.css */

.item {
    margin: 0;
    padding: 20px 0;
    text-align: center;
}

.item:nth-child(even) {
    background: #eee;
}

#watch_end_of_document {
    height: 10px;
    margin: 0;
}
JavaScript
//script.js

const count = 10;
let index = 0;

function addItems() {
    const fragment = document.createDocumentFragment();

    for (let i = index + 1; i <= index + count; ++i) {
        const item = document.createElement("p");

        item.classList.add("item");
        item.textContent = `${i} w3wiki`;

        fragment.appendChild(item);
    }

    document.getElementById("list").appendChild(fragment);
    index += count;
}

const io = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
        if (!entry.isIntersecting) {
            return;
        }
        addItems();
    });
});

io.observe(document.getElementById("watch_end_of_document"));

addItems();

Output:

Final Infinite Scroll using JavaScript Intersection Observer APIOutput



Infinite Scroll using JavaScript Intersection Observer API

The API observes the changes on the page and checks if our target element intersects with the viewport or some other element known as the root element or not. As soon as the element intersects, the API invokes a callback function. Creating an infinite scroll using the JavaScript Intersection Observer API involves detecting when the user has scrolled to the bottom (or near the bottom) of a page, and then dynamically loading more content.

Similar Reads

How to use Intersection Observer?

The Intersection Observer API allows you to monitor the visibility of an element within an ancestor or the document viewport. Here are the key components and concepts:...

Approach to Implement Infinite Scroll using JavaScript Intersection Observer API:

HTML Structure: The HTML structure contains a div element with the id “list” where dynamically generated items will be appended. There’s also a p element with the id “watch_end_of_document” which serves as a sentinel element to observe the end of the document.CSS Styling: Some basic CSS styling is applied to the items displayed in the list. Even indexed items have a light gray background for better visibility.Function addItems(): This function dynamically creates p elements with the class “item” and appends them to the “list” div. It creates a document fragment to optimize performance by reducing DOM manipulations. Each item’s text content is set to a formatted string including the item index and “GeeksForGeeks“.An Intersection Observer instance is created to observe the sentinel element with the id “watch_end_of_document“. When the sentinel element comes into view (i.e., when it intersects with the viewport), the addItems() function is called to load more items.When the page loads, the initial set of items is loaded. As the user scrolls down, triggering the intersection of the sentinel element with the viewport, more items are dynamically loaded....

Contact Us