Basic Usage

Import the intersectionObserver function from @splendidlabz/utils/dom.

main.js
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 entries
  • entry — the current entry
  • observer — the intersectionObserver instance
main.js
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.

main.js
const observer = intersectionObserver(node, /* ... */)
// Observe additional elements
const 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.

main.js
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.

main.js
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.

main.js
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 visible
  • rootMargin: Lets you specify an offset amount from the edges of the root
  • threshold: Determines when to log an observer entry

Stop observing

Stop observing one element

To stop observing one element, use the unobserve method.

main.js
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.

main.js
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.

main.js
const obs = intersectionObserver(nodes, /* ... */)
// Disconnects the observer
obs.disconnect()