The IntersectionObserver API can be used to check the visibility of elements in a web page. This API allows you to perform a number of functions such as lazy loading of images, automatic pausing of videos, and other functions related to changes in visibility.

This article introduces three things I noticed while using the API:

Element visibility is calculated relative to the viewport by default

The syntax for creating an IntersectionObserver instance is as follows:

new IntersectionObserver(callback, option);
Copy the code

When creating this instance, if the option option is not provided, or if the option is used but the root attribute is not specified. Element visibility is then calculated relative to the viewport by default.

As shown below:

The demo address:Codepen. IO/zhangbao/PE…

In the above example, as the blue square scrolls through the parent element, the visibility in the viewport region changes, triggering the callback function. Similarly, the callback is triggered when scrolling externally causes the visible area of the blue square to change.

IntersectionRatio indicates a threshold

The demo address:Codepen. IO/callahad/PE…

The threshold value set for the blue block in the figure is [0, 1].

new IntersectionObserver(handler, { threshold: [0.1]}Copy the code

Take threshold 1 as an example. It is not the value of Entry. IntersectionRatio when the callback is triggered. Therefore, the intersectionRatio value accessed in the callback function is not exactly equal to the threshold value.

From the figure above, it can be seen that when the blue square is fully in the viewport, entry-intersectionRatio is about 1.0123. Upon leaving, entry.intersectionRatio was 0.9757.

So we can make this judgment:

if (ratio >= 1) {
  // The element is fully in the viewport
} else {
  // The element exits from the viewport
}
Copy the code

A callback is executed immediately when observed

Take the code in the example above. When we call the observe() method of the Observer to observe the target element #target,

observer.observe(document.getElementById("target"))
Copy the code

A callback is triggered immediately, which we can see printed in the console.

Some initial state information for #target is printed here.

(after)