IntersectionObserver

What is IntersectionObserver?

IntersectionObserver is an API that allows JavaScript to observe changes in the intersection of a target element with an ancestor element or the browser’s viewport. It is useful when you want to know if an element is visible on the screen or not.

How does it work?

The IntersectionObserver API works by creating an instance of the IntersectionObserver class and passing in a callback function, as well as an options object. The callback function will be called every time the observed element intersects with another element, or when it becomes visible or hidden on the screen.

const observer = new IntersectionObserver((entries, observer) => {
  // Do something when target element intersects with other element or viewport
}, options);

observer.observe(targetElement);

The entries parameter in the callback function is an array of IntersectionObserverEntry objects, which provide information about each observation. The observer parameter is a reference to the observer object itself.

Options

The options object passed to the IntersectionObserver constructor can contain several properties:

  • root: The element that is used as the viewport for checking visibility. Defaults to the browser viewport if not specified.
  • rootMargin: A string representing the margin around the root element. Can have values similar to CSS margin property, e.g. "10px 20px".
  • threshold: A number or array of numbers indicating at what percentage of the target's visibility the observer's callback should be executed.

Examples

Here are some examples of using IntersectionObserver:

// Observe when an element enters or leaves the viewport
const observer = new IntersectionObserver((entries, observer) => {
  for (const entry of entries) {
    if (entry.isIntersecting) {
      // Element is now visible on the screen
    } else {
      // Element is no longer visible on the screen
    }
  }
});

observer.observe(targetElement);

// Observe when an element intersects with another element
const observer = new IntersectionObserver((entries, observer) => {
  for (const entry of entries) {
    if (entry.intersectionRatio > 0) {
      // Element is intersecting with other element
    } else {
      // Element is not intersecting with other element
    }
  }
}, { root: document.querySelector('#container') });

observer.observe(targetElement);

You can also unobserve and disconnect an observer:

// Stop observing a target element
observer.unobserve(targetElement);

// Disconnect the observer completely
observer.disconnect();

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe