← Back to all snippets
JAVASCRIPT

Detect Element Visibility with Intersection Observer API

Optimize performance for lazy loading, infinite scrolling, or animations by efficiently detecting when elements enter or exit the viewport using the JavaScript Intersection Observer API.

<style>
  .box {
    height: 150px;
    width: 150px;
    background-color: lightblue;
    margin: 200px 0;
    border: 1px solid blue;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: sans-serif;
  }
  .in-view { background-color: lightgreen; }
  body { min-height: 1500px; } /* Ensure page is scrollable */
</style>

<div class="box" id="box1">Scroll down to see me!</div>
<div class="box" id="box2">I'm further down.</div>
<div class="box" id="box3">I'm way down here!</div>

<script>
  const observerOptions = {
    root: null, // Use the viewport as the root
    rootMargin: '0px', // No margin around the root
    threshold: 0.5 // Trigger when 50% of the target is visible
  };

  const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('in-view');
        console.log(`${entry.target.id} is now visible!`);
        // Optionally, stop observing once it's visible
        // observer.unobserve(entry.target);
      } else {
        entry.target.classList.remove('in-view');
        console.log(`${entry.target.id} is no longer visible.`);
      }
    });
  }, observerOptions);

  // Target multiple elements
  document.querySelectorAll('.box').forEach(box => {
    observer.observe(box);
  });
</script>
How it works: The Intersection Observer API provides an efficient way to asynchronously observe changes in the intersection of a target element with an ancestor element or with the top-level document's viewport. This snippet sets up an observer to watch for when a '.box' element becomes 50% visible within the viewport. When an element intersects (or stops intersecting) at this threshold, a callback function is executed, allowing you to add or remove a CSS class for visual feedback, trigger animations, or lazy load content without continuous polling or scroll event listeners, which are performance-intensive.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs