Table of Contents

  1. What is Intersection Observer API
  2. Some features
  3. Usage
  4. Example

In the past, it’s difficult to determine a element is visible in the viewport or not, or how long the user was reading this content. Intersection Observer API offers some features that help users to improve user exprerience and speed up the website.

❔ What is Intersection Observer API?

Intersection Observer API offers a way to asynchronously observe changes in UI with ancestor elements or high-level document’s viewports. Browser Viewport

🚀 Some features

  • Lazy loading images or content
  • Infinite Scrolling
  • Report on ad visibility to calculate revenue
  • Decide whether to perform actions or animations based on whether the user sees it.

➡️ Usage

1. Create Intersection Observer Object

function handler(entries, observer) {
  console.log(entries);
}

const config = {
  root: null,
  rootMargin: '0px',
  threshold: 1.0
};

const observer = new IntersectionObserver(handler, config);

✍️ Explain:

  • root: a parent elememt of listened element. root: null means the parent is document
  • rootMargin: addding margin to root
  • threshold: This option will limit the callback. Its value is in the range 0-1. Or maybe an array. Example:
    • 1: callback will be called when the element is 100% visible on the viewport.
    • 0: callback will be called when element as soon as the element is 1px visible on the viewport. It’s also default value.
    • 0.5: callback will be called when the element is 50% visible on the viewport.
    • [0, 0.5, 1]: callback will be called when element is 1px, 50%, 100% visible on the viewport.

In the callback handler function, there is an entries parameter, which is the array of elements to be listened to if they change. These entries also have additional counters to check for the occurrence of that element

2. Apply element to Intersection Observer object

const image = document.getElementById('image');

observer.observe(image);

Besides, we can observe many elements at the same time with the same observer object.

const images = document.querySelectorAll('.image');
 
images.forEach(image) {
    observer.observe(image);
});

3. Unsubcribe observer When we dont want to listen anymore, we can use the following ways:

observer.unobserver(element);// unsubcribe for a previously listened element.
observer.disconnect();// unsubcribe for all elements.

⚒️ Example

For example we want to automatically play the video when we scroll to the video and pause when we scroll through it.

<!DOCTYPE html>
<html>
<body>
  <section style="margin-top: 100px; height: 100vh; background-color: yellow;">
    <h1>TOP SECTION</h1>
  </section>
  <video
    id="video"
    data-testid="video-asset"
    style="width:100%;height:auto"
    src="https://media.istockphoto.com/videos/small-cascading-creek-video-id1321347364"
    alt="Lạch tầng nhỏ - Trả phí Bản quyền Một lần Rừng Stock Footage Video"
    controls=""
    controlslist="nodownload"
    autoplay=""
    muted="muted"
    loop="">
  </video>
  <section style="margin-top: 100px; height: 100vh; background-color: red;">
    <h1>BOTTOM SECTION</h1>
  </section>
  <script>
    const video = document.getElementById('video');

    function handler(entries) {
      const videoEntry = entries[0];
      if(videoEntry.isIntersecting) {
          video?.play();
      } else {
          video?.pause();
      }
    }

    const observer = new IntersectionObserver(handler, );
    observer.observe(video);

  </script>
</body>
</html>

You can find the source code on my Github Repo