Intersection Observer API

The Intersection Observer API is a tool in web development that helps you check if an element is visible on the screen or near another element. It’s great for things like loading images only when needed known as lazy loading, adding effects when scrolling, or showing messages at the right time. It works in the background, so your website runs faster and smoother without extra work like constantly checking where things are.

Intersection Observer API Screen Representation

Create Intersection Observer

Creating an Intersection Observer lets you track when an element appears on the screen and when it disappears from the screen, making it easy to add cool effects or load content only when needed.

const observer = new IntersectionObserver(items=> {
  console.log(items)
  //perform some action
})

The IntersectionObserver is being created and assigned to a variable called observer. It watches for changes in the visibility of elements on the screen.

The function inside Intersection Observer API runs every time the visibility of the observed elements changes. The items parameter is a list of those elements and their visibility details.

In this example, it logs the items to the console and is ready to perform actions (like animations or loading content) whenever the visibility changes.

Let’s take a look at a simple implementation of this IntersectionObserver:-

const observer = new IntersectionObserver(items=> {
  items.forEach(item=> {
    const intersecting = item.isIntersecting
    item.target.style.backgroundColor = intersecting ? "yellow" : "red"
    // changes on intersection
  })
})

observer.observe(document.getElementById("checkIntersection"))
//element to observe

The steps involving in the above example are:-

Create an Observer:
The IntersectionObserver is created and assigned to the variable observer. It watches elements and detects when they appear or disappear from the visible part of the screen (the viewport).

Handle Each Observed Item:
The items.forEach loop goes through each element the observer is tracking. For each element:

  • The item.isIntersecting checks if the element is currently visible on the screen.
  • If it is visible (true), the element’s background color is changed to yellow. If not (false), the background color is changed to red.

Observe an Element:
The observer.observe line tells the observer to start watching a specific element, which is selected using document.getElementById("checkIntersection").

Intersection Observer API Controls Features

We will now take a look at how we can control the Intersection Observer API and make it function to our liking.

Threshold

The threshold in Intersection Observer API is a key setting that determines when the observer should trigger an action based on how much of the target element is visible in the viewport (or within a specified root container).

How Threshold Works:

  • Value Range: The threshold value can range from 0 to 1.
    • A value of 0 means the observer will trigger as soon as any part of the element is visible, even just one pixel.
    • A value of 1 means the observer will only trigger when the entire element is fully visible in the viewport.
  • Array of Values: You can also provide multiple threshold values as an array, like [0, 0.5, 1]. This lets you track specific levels of visibility. For example, you could perform different actions when 50% or 100% of the element is visible.

Example:

If you set the threshold to 0.5, the observer will trigger when at least 50% of the element is visible. The observer will not trigger again unless the visibility changes to below 50% or reaches another threshold value.

Similar Topics:

Why Threshold is Useful:

  • Precise Control: It gives you fine-grained control over when to trigger actions, like starting animations or loading images.
  • Performance Optimization: By using specific thresholds, you can avoid unnecessary triggers and improve performance.
  • Custom Behavior: It allows developers to define what “visible” means for their use case, making it versatile for tasks like progress indicators, or video autoplay.
const observer = new IntersectionObserver(items=> {
  items.forEach(item=> {
    const intersecting = item.isIntersecting
    item.target.style.backgroundColor = intersecting ? "yellow" : "red"
  })
}, { threshold: 1 }) // set threshold 1

observer.observe(document.getElementById("checkIntersection"))

In this code, the threshold: 1 setting means the Intersection Observer will only trigger when the entire element is fully visible in the viewport—100% of its area must intersect with the visible area. This is useful when you want to perform actions only when the element is completely in view. Actions may include effects such as highlighting it or triggering animations. If any part of the element is outside the viewport, the observer won’t react until the full element becomes visible. This precise control ensures that the action only happens under the exact condition of full visibility.

Root Margin

The rootMargin in Intersection Observer API is like adding extra space around the area being watched to control when visibility changes are detected. It works like a margin in CSS, letting you expand or shrink the boundary of the viewport. For example, if you set rootMargin: "100px", the observer will trigger when the element is within 100px of the visible area, even if it’s not yet fully in view. Similarly, a negative value like "-50px" means the element has to be deeper inside the viewport to trigger. This is helpful for tasks like starting animations earlier or delaying actions until the element is more visible.

Example:

const observer = new IntersectionObserver(items=> {
  items.forEach(item=> {
    const intersecting = item.isIntersecting
    item.target.style.backgroundColor = intersecting ? "yellow" : "red"
  })
}, { rootMargin: 100px }) // set rootMargin

observer.observe(document.getElementById("checkIntersection"))

In this code, the rootMargin: "100px" expands the observation area by 100 pixels beyond the viewport in all directions. This means the Intersection Observer will detect the element with the ID checkIntersection even when it is 100 pixels away from being visible in the viewport. The added margin gives an early trigger, allowing actions like changing the background color to start before the element fully enters the screen. This is especially useful for creating a smoother user experience by preparing content or animations in advance.

Value Range:

  • 0: The observer triggers as soon as any part of the element is visible, even just one pixel.
  • 1: The observer triggers only when the entire element is fully visible.

Multiple Thresholds:
You can set an array of thresholds like [0, 0.5, 1], allowing the observer to react at different levels of visibility, like when 50% or 100% of the element is in view.

Why It’s Useful:

  • Performance: It helps optimize performance by triggering actions only when necessary.
  • Control: It gives you precise control over when to trigger events like loading images or animations based on how much of the element is visible.
  • Engaging Interactions: You can create smoother, more interactive user experiences by responding to partial visibility instead of waiting for full visibility.

Root

The root in Intersection Observer API refers to the element within which the visibility of target elements is being observed. By default, the root is the viewport, meaning the browser window. However, you can specify a different element as the root by passing it into the observer options. This is useful for tracking visibility within a specific container, such as a scrollable div, instead of the entire page. The root defines the boundaries for visibility checks, so when an element intersects with the root (or the area around it, depending on rootMargin), the observer is triggered. This flexibility allows you to control how and where visibility changes are detected. Making it ideal for scenarios like lazy loading images within a specific section or triggering animations in a scrollable area.

 const container = document.getElementById("scrollableContainer");

  const observer = new IntersectionObserver(items => {
    items.forEach(item => {
      const intersecting = item.isIntersecting;
      item.target.style.backgroundColor = intersecting ? "yellow" : "red";
    });
  }, { root: container, rootMargin: "0px" });

  observer.observe(document.getElementById("checkIntersection"));

How It Works:

  • Custom Root: The root is set to the #scrollableContainer div, which is a scrollable container with a fixed height of 300px.
  • Observer Behavior: The Intersection Observer will now track when the element with the ID checkIntersection enters or leaves the visible area of the scrollableContainer.
  • Visibility Trigger: As you scroll the #scrollableContainer, the background color of checkIntersection will change to yellow when it’s fully visible inside the container and to red when it’s not.

Unobserve

The unobserve method in Intersection Observer API is used to stop observing a specific target element that was previously being tracked. Once unobserve is called on an element, the observer will no longer monitor that element for visibility changes, meaning no further callbacks will be triggered for that element.

When you set up an Intersection Observer, you use observe to tell it to start monitoring an element. If at some point you no longer need to track the element—perhaps because it’s been removed from the DOM, or it’s no longer relevant to the task—you can call unobserve to stop the monitoring.

Here is an example of it’s implementation:-

const observer = new IntersectionObserver(items=> {
  items.forEach(item=> {
    console.log(item.target, item.isIntersecting);
  });
});

const targetElement = document.getElementById("target");
observer.observe(targetElement);

// Stop observing the element
observer.unobserve(targetElement);

Advantages:

  • Performance: Unobserving elements that no longer need tracking helps improve performance, especially if you’re observing many elements.
  • Dynamic Content: In applications where content changes dynamically (e.g., elements being added or removed from the page), unobserve ensures that you don’t continue monitoring elements that are no longer in the DOM or relevant.
  • Cleaner Code: It prevents unnecessary callbacks from firing, keeping your logic cleaner and more efficient.

Disconnect

The disconnect method in Intersection Observer API is used to completely stop the observer from watching all elements it was tracking. Unlike unobserve, which only stops monitoring a specific element, disconnect removes the observer’s ability to track any element, effectively deactivating it.

When you call disconnect, the observer stops receiving visibility changes for all elements it was observing, and any associated callback functions will no longer be triggered. It’s like turning off the observer entirely, making it stop its work.

Let’s look at an example:-

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    console.log(entry.target, entry.isIntersecting);
  });
});

observer.observe(document.getElementById("element1"));
observer.observe(document.getElementById("element2"));

observer.disconnect();

Advantages:

  • Performance: It efficiently stops all observations when no longer needed, preventing unnecessary checks and callbacks.
  • Dynamic Applications: In applications where the observer is only temporarily needed (e.g., during a specific page interaction or after a certain event), disconnect ensures that the observer isn’t continuously tracking elements when it’s not needed.
  • Cleaner Resource Management: Using disconnect helps free up resources by deactivating the observer, especially in cases where multiple observers are being created and you want to remove them completely.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *