Sometimes, we want to tell if a DOM element is visible in the current viewport with JavaScript.
In this article, we’ll look at how to tell if a DOM element is visible in the current viewport with JavaScript.
How to tell if a DOM element is visible in the current viewport with JavaScript?
To tell if a DOM element is visible in the current viewport with JavaScript, we use the intersection observer.
For instance, we write
const el = document.querySelector("#el");
const observer = new window.IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
console.log("ENTER");
return;
}
console.log("LEAVE");
},
{
root: null,
threshold: 0.1,
}
);
observer.observe(el);
to create an IntersectionObserver
object with a callback and an object.
The callback is run wwhen the element we’re oberving enters or leaves the container.
We can check if it’s intersecting with the container with isIntersecting
.
The object has the root
property that specifies the container to watch for intersection for.
threshold
has the threshold of the intersection before the callback is run.
Conclusion
To tell if a DOM element is visible in the current viewport with JavaScript, we use the intersection observer.