Photo by Anne Nygård on Unsplash
Sometimes, we want to watch when an element appears on the screen.
In this article, we’ll look at when an element becomes visible on the screen with JavaScript.
Use the IntersectionObserver API
We can use the IntersectionObserver API to watch when an element is visible or not. For instance, if we have the following HTML:
<div></div>
Then we can add the following JavaScript:
const div = document.querySelector("div");
for (let i = 0; i < 100; i++) {
const p = document.createElement("p");
p.textContent = i;
p.id = `el-${i}`;
div.appendChild(p);
}
const options = {
rootMargin: "0px",
threshold: 1.0,
};
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
console.log(entry.intersectionRatio > 0 ? "visible" : "invisible");
});
}, options);
const element = document.querySelector("#el-50");
observer.observe(element);
to add elements into the div with the for
loop.
Then we use the IntersectionObserver
constructor to add the intersection observer.
The options
object has the rootMargin
which is the margin for when the element is considered to be visible.
threshold
is how much of the element is visible on the screen for it to be considered visible.
This value is between 0 and 1.
We pass in a callback into IntersectionObserver
which runs when the element we’re watching appears or disappears from the screen.
We loop through entries
to get the intersection entries object.
And we log entry.intersectionRatio
and check if it’s bigger than 0 to see if the element we’re watching is visible.
Finally, we call observer.observe
to watch the element with ID el-50
to be visible or invisible on the screen.
Conclusion
We can use the IntersectionObserver API to watch when an element is visible or not.