fn

useMutationObserver

v0.0.14testeddemo

Watch for changes to the DOM tree via MutationObserver. Accepts a single target, an array of targets, or a getter returning either.

Examples

ts
useMutationObserver(el, (records) => {
  console.log(records);
}, { attributes: true });
ts
const { pause, resume } = useMutationObserver([elA, elB], onMutate, { childList: true });

Demo

Loading demo…

Signature

ts
export function useMutationObserver(
  target: MaybeComputedElementRef | MaybeComputedElementRef[] | MaybeRefOrGetter<MaybeElement[]>,
  callback: MutationCallback,
  options: UseMutationObserverOptions ={ ... }

Parameters

ParameterTypeDescription
targetMaybeComputedElementRef | MaybeComputedElementRef[] | MaybeRefOrGetter<MaybeElement[]>Element(s) to observe
callbackMutationCallbackInvoked with the mutation records
options?UseMutationObserverOptionsObserver options (childList, attributes, …)

Returns

UseMutationObserverReturnisSupported, isActive, pause, resume, stop, and takeRecords
PropertyTypeDescription
isSupportedReadonly<Ref<boolean>>
isActiveReadonly<Ref<boolean>>Whether the observer is currently active (not paused or stopped)
pause() => voidTemporarily disconnect the observer without tearing down the watcher. Re-observe with resume.
resume() => voidRe-attach the observer to the current target(s) after a pause.
stop() => voidPermanently stop observing and dispose the watcher.
takeRecords() => MutationRecord[] | undefinedSynchronously take and clear the observer's record queue