Know your Modern Browser APIs
Chapter 2: The IntersectionObserver API
Another useful API from the browser. Before talking about “Intersection Observer” you should know what is an observer.
Observer is an object which monitors or observes something continuously and it notifies after something is changed.
As it says, we can watch and act on any changes to an element. Observer APIs are very useful to detect changes in the applications. The following are the different types of observer APIs in JavaScript. Each type observes different things.
1. IntersectionObserver — It observes the DOM element’s visibility and positions
2. MutationObserver — It observes the DOM tree. It waits for the changes being made to the DOM.
3. ResizeObserver — It observes changes to the dimensions of an Element
's content or border-box, or the bounding box of an SVGElement
.
4. PerformanceObserver — It used to observe performance measurement events and be notified of new performance entries as they are recorded in the browser’s performance timeline.
5. ReportingObserver — It allows you to collect and access browser reports
Here I am going to discuss the “Intersection Observer” API.
Intersection Observer API
The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport. This means it provides a way to observe changes in the intersection of a specific element it can be a ‘div’, ‘span’, ‘button’, ‘images, etc.
Previously we didn’t have any direct APIs to check the visibility of an element. We were using JS or other JS libraries to achieve this. It was very difficult to implement a solution to this problem.
Where I can use this?
There are multiple use cases for this Observer.
1. Lazy Loading the contents and images when it comes to the viewport or page scroll.
2. We can implement Infinite scroll using intersection Observers.
3. Performing Animations on page scroll.
4. Showing/Playing advertisements based on user activity.
Let’s know some concepts
Now, we’ll use the IntersectionObserver interface to create a new observer.
let options = {
"root" : document.querySelector(‘body'),
"rootMargin": ‘0px’,
"threshold": [0, 0.5, 1] // Array or number
}let observer = new IntersectionObserver(callback, options);
IntersectionObserver creates and returns a new Intersection object when the target element intersects the specified root element.
Callback — this is a function to be run whenever a threshold is crossed in one direction or the other.
Options — This contains the configuration for the Observer
— root: The element that is used as the viewport for checking the visibility of the target. Must be the ancestor of the target. Defaults to the browser viewport if not specified or if null
.
— rootMargin : Margin around the root. Can have values similar to the CSS margin property, e.g. “10px 20px 30px 40px” (top, right, bottom, left). The values can be percentages
— threshold: Either a single number or an array of numbers which indicate at what percentage of the target’s visibility the observer’s callback should be executed.
How to target an Element?
let target = document.querySelector(‘#targetElement');observer.observe(target);
** the callback we set up for the observer will be executed now for the first time
** it waits until we assign a target to our observer (even if the target is currently not visible)
Whenever the target meets a threshold specified for the IntersectionObserver, the callback is invoked. The callback receives a list of IntersectionObserverEntry objects and the observer:
let callback = (entries, observer) => {
entries.forEach(entry => {
// Each entry describes an intersection change
for one observed
});
};
Let's console log an IntersectionObserverEntry object :
Now, let's take one use case. Here I am going to take the Animation thing that is pretty much simple to implement. After watching this we will get more clarity on how to use the Intersection Observer.
Here is an example,
In this example, we can see that the background color for the div is changing based on the visibility in the viewport area.
let options = {
“rootMargin”: ‘0px’,
“threshold”: [0, 0.5, 1]
}// Create a new Observer
let observer = new IntersectionObserver(callback, options);// Start observing the target element
let target = document.querySelector(‘#target’)
observer.observe(target)
Here an Intersection observer is created for watching the “target” element div with a threshold value of [0, 0.5, 1]. The threshold value can accept arrays also. Based on these thresholds, callbacks are executed.
What is in the callback ?
let callback = (entries) => {
if (entries[0].intersectionRatio < 0.5) {
entries[0].target.className = “bg-yellow”;
entries[0].target.innerText = “yellow”;
} else if (entries[0].intersectionRatio >= 0.5 && entries[0].intersectionRatio < 1) {
entries[0].target.className = “bg-red”;
entries[0].target.innerText = “red”;
} else {
entries[0].target.className = “bg-green”;
entries[0].target.innerText = “green”;
}
}
The intersection Observer notifies when the target intersects the viewport. When you scroll down , based on the thresold values, callback function is called. Here in the callback function, “intersectionRatio” property value from the “IntersectionObserver” object is compared with some predefined values and applying some classes for the target element which changes the background color of the element. We can use any of these details such as positions, target elements, isIntersecting for fullfill our requirments.
This is the browser view for each thresholds :
There are 2 more methods available for the API.
1. Unobserved(observer) — Stop the observer.
2. Disconnect() — Stop All Observers
Okay, Everything looks fine. But, we can do this with “onscroll” right?
Ofcourse this use case can be achieved using the ‘onscroll’ event in JavaScript. Using scroll event we can detect a particular element’s position and visibility. But the scroll event is a heavy thing and it will triggers each and every scroll movement. It leads to performance issues. So intersection Observer is the best way to use in such scenarios.
Conclusion
IntersectionObserver API is one of modern browser API which will helps you to achieve various client side requirements like lazy loading, animations, tracking user activity , ad related stuffs, infinite scrolling etc. without affecting the user experience and performance.
Now it’s your turn, try it. Happy Coding… Thank you…