A friendlier wrapper for MutationObserver

MutationObserver exposes almost the same surface as ResizeObserver, so the wrapper written for the resize observer can be carried over almost unchanged:

export function mutationObserver(node, options = {}) {
  const observer = new MutationObserver(observerFn)
  const { callback, ...opts } = options
  observer.observe(node, opts)

  function observerFn(entries) {
    for (const entry of entries) {
      // Callback pattern
      if (options.callback) options.callback({ entry, entries, observer })
      // Event listener pattern
      else {
        node.dispatchEvent(
          new CustomEvent('mutate', {
            detail: { entry, entries, observer },
          })
        )
      }
    }
  }
}

The result supports both the callback pattern and the event listener pattern:

const node = document.querySelector('.some-element')

// Callback pattern 
const obs = mutationObserver(node, {
  callback ({ entry, entries }) {
    // Do what you want with each entry
  }
})

// Event listener pattern
node.addEventListener('mutate', event => {
  const { entry } = event.detail
  // Do what you want with each entry
})

Tearing down a mutation observer

Where ResizeObserver offers two ways to stop watching elements, MutationObserver offers only one: disconnect.

export function mutationObserver(node, options = {}) {
  // ... 
  return {
    disconnect() {
      observer.disconnect()
    }
  }
}

There is, however, a takeRecords method that retrieves unprocessed records. Because those records should be collected before disconnecting, the wrapper can call it inside disconnect, and then expose the method as part of a complete API:

export function mutationObserver(node, options = {}) {
  // ... 
  return {
    // ...
    disconnect() {
      const records = observer.takeRecords()
      observer.disconnect()
      if (records.length > 0) observerFn(records)
    }
  }
}

Disconnecting then looks like this:

const node = document.querySelector('.some-element')
const obs = mutationObserver(/* ... */)

obs.disconnect()

What observe can watch for

The observe method accepts seven options, each defaulting to false:

  • subtree: monitors the entire subtree of nodes
  • childList: monitors additions and removals of child elements; with subtree set to true, all descendant elements are monitored
  • attributes: monitors attribute changes
  • attributeFilter: an array of specific attributes to monitor
  • attributeOldValue: records the previous attribute value when it changes
  • characterData: monitors changes to character data
  • characterDataOldValue: records the previous character data value

Adapting IntersectionObserver

The general shape is familiar: construct an observer with new and a callback, react to changes inside that callback, call observe on an element, and optionally stop with unobserve or disconnect, depending on the observer. The difference for IntersectionObserver is that its options are passed at construction time rather than to observe:

// Step 1: Create a new observer and pass in relevant options
const options = {/*...*/}
const observer = new IntersectionObserver(observerFn, options)

// Step 2: Do something with the observed changes
function observerFn (entries) {
  for (const entry of entries) {
    // Do something with entry
  }
}

// Step 3: Observe the element
const element = document.querySelector('#some-element')
observer.observe(element)

// Step 4 (optional): Disconnect the observer when we're done using it
observer.disconnect(element)

The mutation observer wrapper therefore transfers nearly as-is, with one correction: the options must go to the IntersectionObserver constructor, not to observe.

export function mutationObserver(node, options = {}) {
  const { callback, ...opts } = options
  const observer = new MutationObserver(observerFn, opts)
  observer.observe(node)

  function observerFn(entries) {
    for (const entry of entries) {
      // Callback pattern
      if (options.callback) options.callback({ entry, entries, observer })
      // Event listener pattern
      else {
        node.dispatchEvent(
          new CustomEvent('intersect', {
            detail: { entry, entries, observer },
          })
        )
      }
    }
  }
}

The wrapped version is used the same way:

const node = document.querySelector('.some-element')

// Callback pattern 
const obs = intersectionObserver(node, {
  callback ({ entry, entries }) {
    // Do what you want with each entry
  }
})

// Event listener pattern
node.addEventListener('intersect', event => {
  const { entry } = event.detail
  // Do what you want with each entry
})

Combining the teardown methods

IntersectionObserver carries the union of the methods found on the other two observers—observe for a single element, unobserve to stop watching one element, disconnect to stop watching all of them, and takeRecords for unprocessed records. The wrapper can merge the versions already written for the resize and mutation observers:

export function intersectionObserver(node, options = {}) {
  // ...
  return {
    unobserve(node) {
      observer.unobserve(node)
    },

    disconnect() {
      // Take records before disconnecting.
      const records = observer.takeRecords()
      observer.disconnect()
      if (records.length > 0) observerFn(records)
    },
    
    takeRecords() {
      return observer.takeRecords()
    },
  }
}

Stopping observation then works through either unobserve or disconnect:

const node = document.querySelector('.some-element')
const obs = intersectionObserver(node, /*...*/)

// Disconnect the observer
obs.disconnect()

Intersection options

IntersectionObserver takes three options: root, the element used to check whether observed elements are visible; rootMargin, an offset from the edges of that root; and threshold, which determines when an observer entry is logged.

Prebuilt versions and caveats

The utils library at Splendid Labz ships resizeObserver, mutationObserver and IntersectionObserver for anyone who would rather not paste the snippets into each project:

import { 
  resizeObserver, 
  intersectionObserver, 
  mutationObserver 
} from 'splendidlabz/utils/dom'

const mode = document.querySelector(‘some-element’)

const resizeObs = resizeObserver(node, /* ... */)
const intersectObs = intersectionObserver(node, /* ... */)
const mutateObs = mutationObserver(node, /* ... */)

Beyond the code above, each observer there can observe and stop observing multiple elements at once—except mutationObserver, since MutationObserver has no unobserve method:

const items = document.querySelectorAll('.elements')
const obs = resizeObserver(items, {
  callback ({ entry, entries }) {
    /* Do what you want here */
  }
})

// Unobserves two items at once
const subset = [items[0], items[1]]
obs.unobserve(subset)

The documentation for the library was still in progress at the time of writing.