observeMutation

Category Observers

Watch for changes being made to the DOM tree.

Demo

Usage

<script>
	import { observeMutation } from '@sv-use/core';
 
	let el = $state();
 
	observeMutation(() => el, (mutations) => {
        console.log(mutations[0]);
    });
</script>
 
<div bind:this={el}></div>
Type definitions
import { type ConfigurableWindow } from '../../__internal__/configurable.js';
import type { CleanupFunction, MaybeGetter } from '../../__internal__/types.js';
interface ObserveMutationOptions extends MutationObserverInit, ConfigurableWindow {
    /**
     * Whether to automatically cleanup the observer or not.
     *
     * If set to `true`, it must run in the component initialization lifecycle.
     * @default true
     */
    autoCleanup?: boolean;
}
type ObserveMutationReturn = {
    /**
     * Whether the {@link https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver | `Mutation Observer API`} is supported or not.
     * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#browser_compatibility
     */
    readonly isSupported: boolean;
    /**
     * A function to cleanup the observer.
     * @note Is called automatically if `options.autoCleanup` is set to `true`.
     */
    cleanup: CleanupFunction;
    /** Empties the record queue and returns what was in there. */
    takeRecords: () => void;
};
/**
 * Watch for changes being made to the DOM tree.
 * @param targets The target to observe.
 * @param callback The callback for when a change is detected.
 * @param options Additional options to customize the behavior.
 * @see https://svelte-librarian.github.io/sv-use/docs/core/observers/observe-mutation
 */
export declare function observeMutation(target: MaybeGetter<HTMLElement | undefined>, callback: MutationCallback, options?: ObserveMutationOptions): ObserveMutationReturn;
/**
 * Watch for changes being made to the DOM tree.
 * @param targets The targets to observe.
 * @param callback The callback for when a change is detected.
 * @param options Additional options to customize the behavior.
 * @see https://svelte-librarian.github.io/sv-use/docs/core/observers/observe-mutation
 */
export declare function observeMutation(targets: Array<MaybeGetter<HTMLElement | undefined>>, callback: MutationCallback, options?: ObserveMutationOptions): ObserveMutationReturn;
export {};

Sources