Skip to content
Shubham JangleResources
JavaScript

Explore topics

Infinite Scroll

Watch the walkthrough
Open on Instagram

Exercise

Append a batch of cards when a bottom sentinel becomes visible.

What the source implements

The source uses IntersectionObserver with threshold 0.9 and adds five mock cards per call. It has no API, loading lock, or end condition, and repeats values 0–4 for each batch. Extend it with stable IDs and pagination before using real data.

Run and revise

Copy the entire fenced HTML into a file with the same name and open it in a browser. It includes the markup, styles, and JavaScript together. Check the console, keyboard behavior, and boundary cases. Remote APIs/assets and CDN scripts need network access.

Original repository source

The complete file below is preserved apart from line endings; the extensions above are not changes to this copied implementation.

2-infinite-scroll.html

Original file on GitHub

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Infinite scroll</title>
    <style>
      .box {
        height: 100px;
        background-color: skyblue;
        margin: 1rem 0;
        padding: 1rem;
      }
      #trigger {
        height: 100px;
        background-color: rebeccapurple;
        color: white;
        padding: 1rem;
      }
    </style>
  </head>
  <body>
    <div id="content-area"></div>
    <div id="trigger">Trigger</div>
  </body>
  <script>
    const contentArea = document.getElementById("content-area");
    const trigger = document.getElementById("trigger");

    function createPostElement(value) {
      const ele = document.createElement("div");
      ele.textContent = value;
      ele.classList = "box";
      contentArea.appendChild(ele);
    }

    function fetchData() {
      let i = 0;
      while (i < 5) {
        createPostElement(i++);
      }
    }

    const observer = new IntersectionObserver(
      (values) => {
        console.log(values);
        if (values[0].isIntersecting) {
          fetchData();
        }
      },
      {
        // rootMargin: "900px",
        threshold: 0.9, // trigger when div visibility is 90%
      }
    );

    observer.observe(trigger);

    fetchData();
  </script>
</html>