Use IntersectionObserver when you need to know that a box has scrolled into view. The browser tells you. You do not have to listen to every scroll tick.
This is the usual way to lazy load images. It is also how infinite scroll knows to fetch the next page. The page stays smooth because the check is cheap.
You pick a target, such as a card or an image. You can also pick a root, which is the scroll box. The viewport is the default. When the target crosses that edge, your function runs.
💡 Key Takeaways: JavaScript Intersection Observer
Mastering JavaScript Intersection Observer helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
JavaScript Intersection Observer Code Example
JavaScript
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log("Element is now visible on screen:", entry.target.id);
}
});
});
// observer.observe(document.querySelector("#promoBanner"));