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

ParameterTypeDescription
targetElement
Element[]
NodeList
The element(s) to observe
optionsobjectConfiguration options for the observer

Options

OptionTypeDefaultDescription
callbackfunction-Function called when intersection changes occur. Receives { entry, entries, observer }
rootElementnullThe element that is used as the viewport for checking visibility
rootMarginstring"0px"Margin around the root. Can have values similar to the CSS margin property
thresholdnumber
number[]
0Either 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:

PropertyTypeDescription
entryIntersectionObserverEntryThe current intersection entry being processed
entriesIntersectionObserverEntry[]All intersection entries being observed
observerIntersectionObserverThe observer instance

Return Value

Returns an object with the following methods:

MethodParametersReturn ValueDescription
observeElement
Element[]
NodeList
-Starts observing new elements for intersection changes
unobserveElement
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
})