Basic Usage
Import the intersectionObserver
function from @splendidlabz/utils/dom
.
import { intersectionObserver } from '@splendidlabz/utils/dom'
Grab the element you want to listen to, and pass that into intersectionObserver
. Three properties will be available in the callback:
entries
— a list of all observed entriesentry
— the current entryobserver
— theintersectionObserver
instance
const node = document.querySelector('.my-element')const observer = intersectionObserver(node, { callback({ entries, entry, observer }) { // Do something with the resize observer },})
Observing additional elements
You can observe additional elements after the initial setup with the observe
method.
const observer = intersectionObserver(node, /* ... */)
// Observe additional elementsconst node2 = document.querySelector('.my-element-2')observer.observe(node2)
Listening to multiple elements
Grab the elements you want to listen to — either as an array or nodelist — and pass them to intersectionObserver
. It’ll listen to them all.
const nodes = document.querySelectorAll('.elements')const observer = intersectionObserver(nodes, { callback({ entry }) { // Do something with the resize observer },})
Event Listener Pattern
You can also listen for intersectionObserver
changes via the event listener pattern. Just listen to the mutate
event.
const observer = intersectionObserver(node, /* ... */)
node.addEventListener('mutate', ({ detail }) => { const { entries, entry, observer } = detail // Do something with the resize observer})
Observer Options
You can pass in all intersectionObserver
options to intersectionObserver
via the second argument.
const observer = intersectionObserver(node, { callback({ entry }) { /* ... */ }, // Other options go here ...})
IntersectionObserver takes in three options:
root
: The element used to check if observed elements are visiblerootMargin
: Lets you specify an offset amount from the edges of the rootthreshold
: Determines when to log an observer entry
Stop observing
Stop observing one element
To stop observing one element, use the unobserve
method.
const observer = intersectionObserver(nodes, /* ... */)observer.unobserve(node)
Stop observing multiple elements
To stop observing multiple elements, you can pass the elements to unobserve to the unobserve
method.
const observer = intersectionObserver(nodes, /* ... */)observer.unobserve(nodes)
Alternatively, you can use the disconnect
method to stop observing all elements.
Disconnect the observer
Disconnects the intersection observer and stops observing all elements.
While disconnecting, intersectionObserver
will automatically call takeRecords
to process any unprocessed intersections.
const obs = intersectionObserver(nodes, /* ... */)
// Disconnects the observerobs.disconnect()