We would normally track if a DOM element is visible in the viewport or not to understand user behavior or to operate on the element based on visibility (animation, AJAX calls, etc).
The Old Way
We would normally apply a function like this to detect if an element is visible:
const isInView = (elm, {top, height} = elm.getBoundingClientRect()) =>
top <= innerHeight && top + height >= 0;
Later we would mostly add it on scroll events to trigger the checks as the user scrolls, which is a costly operation.
Intersection Observer API
That’s where the Intersection Observer API comes to the rescue:
const observer = new IntersectionObserver(changes => {
for (const change of changes) {
console.log(change.time); // Timestamp when the change occurred
console.log(change.rootBounds); // Unclipped area of root
console.log(change.boundingClientRect); // target.boundingClientRect()
console.log(change.intersectionRect); // boundingClientRect, clipped and intersected
console.log(change.intersectionRatio); // Ratio of intersectionRect to boundingClientRect
console.log(change.target); // The Element target
}
}, {});
// Watch for intersection
observer.observe(target);
// Stop watching
observer.unobserve(target);
// Stop observing
observer.disconnect();
Example
Say, if we were to observe the element #catBox for visibility:
let options = {
root: document.querySelector('#catBox'),
rootMargin: '0px',
threshold: 1.0
}
let observer = new IntersectionObserver(callback, options);
#javascript#dom#performance
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.