JavaScript Intersection Observer

Find out when an element scrolls into view, without a slow scroll listener.

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"));
Output
Triggers callback whenever target enters view
Free sign-in required · Google login available
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services