Can the user see this?

IntersectionObserver allows you to know exactly when an element enters or leaves the visible area of the screen (or another scrollable container).

Why is this useful?

  1. Lazy Loading: Only load heavy images or videos when the user scrolls down to them.
  2. Infinite Scroll: Load new posts from the server when the " footer " becomes visible on the screen.
  3. Animations: Trigger CSS animations exactly when the user scrolls to a specific section.
let observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      console.log("The element is now visible on screen!");
    }
  });
});

observer.observe(document.querySelector('.my-target'));
Important

The setting threshold: 0.5 means the event will trigger only when the element is at least 50% visible on the screen. By default, it triggers at 0 (the exact moment a single pixel becomes visible).