The old way to do something when an element comes into view is a scroll listener that measures positions dozens of times a second. The browser has a cheaper way.
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
entry.target.classList.add("visible");
observer.unobserve(entry.target);
}
}
}, { rootMargin: "200px" });
document.querySelectorAll(".reveal").forEach((el) => observer.observe(el));
The callback gets a list of entries. isIntersecting is true when the element moved into view. After the first time I call unobserve(), because I only care once; MDN says calling it on an element that is not observed just does nothing.
The options: root is the viewport when you leave it out, rootMargin grows or shrinks that area (default 0px on all sides), and threshold says how much of the element must be visible, default 0. A positive rootMargin like the 200 pixels here starts the work just before the element appears, which is nice for loading content.
I’d use it for loading a heavy widget only when someone scrolls down to it, or for counting which sections people actually reach.
Caveats. The callback runs on the main thread, so keep it short. If you set a root, the observed elements must be inside it. And MDN is not fully clear on the edge case where an element only touches the edge of the viewport, so do not build logic that depends on that exact moment. Test it.
Further reading: MDN: Intersection Observer API, MDN: IntersectionObserver.unobserve()