Intersection Observer API
The intersectionObserver
function creates an IntersectionObserver
instance that watches for when elements enter or exit the viewport.
const observer = intersectionObserver(target, options)
Parameters
Parameter | Type | Description |
---|---|---|
target | Element Element[] NodeList | The element(s) to observe |
options | object | Configuration options for the observer |
Options
Option | Type | Default | Description |
---|---|---|---|
callback | function | - | Function called when intersection changes occur. Receives { entry, entries, observer } |
root | Element | null | The element that is used as the viewport for checking visibility |
rootMargin | string | "0px" | Margin around the root. Can have values similar to the CSS margin property |
threshold | number number[] | 0 | Either a single number or an array of numbers between 0.0 and 1.0, specifying a ratio of intersection area to total bounding box area |
For more details about these options, see the MDN documentation.
Callback Parameters
When an intersection change occurs, the callback receives an object with:
Property | Type | Description |
---|---|---|
entry | IntersectionObserverEntry | The current intersection entry being processed |
entries | IntersectionObserverEntry[] | All intersection entries being observed |
observer | IntersectionObserver | The observer instance |
Return Value
Returns an object with the following methods:
Method | Parameters | Return Value | Description |
---|---|---|---|
observe | Element Element[] NodeList | - | Starts observing new elements for intersection changes |
unobserve | Element Element[] NodeList | - | Stops observing elements for intersection changes |
takeRecords | - | IntersectionObserverEntry[] | Returns all pending intersection entries and clears the queue |
disconnect | - | - | Stops observing all elements, processes any pending entries through the callback, and then disconnects the observer |
destroy | - | - | Alias for disconnect() |
Event Listener Alternative
If no callback is provided, the observer will dispatch an intersect
event on the target element. You can listen for this event:
element.addEventListener('intersect', ({ detail }) => { const { entry, entries, observer } = detail // Handle intersection change})