View RSS feed

Intersection Observer API

Published: Sep 30, 2024Source

Overview

Detect when a DOM intersects a specific ancestor element. A common use case can be detecting when an element enters the viewport.

Syntax

const observer = new IntersectionObserver((entries) => {
const [entry] = entries;
// Logic
}, options);

observer.observe(target);

// Cleanup
observer.disconnect();

Options

root

The ancestor element that we want to detect when the target element intersects. Defaults to the browser viewport.

rootMargin

Must by a number with pixel or percent units. You can grow/shrink the root element's bounding box before computing intersections. Defaults to 0.

threshold

Percentage amount of the target element that should be visible before the intersection is detected. Defaults to 0 which means any part of the target will be detected. Setting to 1 will require the entire target element to be within the root before begin detected.