onClickOutside

Category Sensors

Runs a callback when a click occurs outside the target element.

Demo

click outside of me

See the logs for details...

Usage

<script>
	import { onClickOutside } from '@sv-use/core';
 
	let divNode = $state();
 
	onClickOutside(() => divNode, (event) => {
        console.log('outside');
    });
</script>
 
<div bind:this={divNode}>
    i'm the target element
</div>
<p>i'm outside the target element</p>
Type definitions
import { type ConfigurableWindow } from '../../__internal__/configurable.js';
import type { Arrayable, CleanupFunction, Getter } from '../../__internal__/types.js';
interface OnClickOutsideOptions extends ConfigurableWindow {
    /**
     * Whether to auto-cleanup the event listeners or not.
     *
     * If set to `true`, it must run in the component initialization lifecycle.
     * @default false
     */
    autoCleanup?: boolean;
    /**
     * Use capturing phase for internal event listener.
     * @default true
     */
    capture?: boolean;
    /**
     * Element(s) that will not trigger the event.
     * @default []
     */
    ignore?: Arrayable<Getter<HTMLElement | null | undefined>>;
}
/**
 * Runs a callback when a click occurs outside the element or its ignore list.
 * @param element The main element on which not to trigger a click.
 * @param callback The callback to run when an outside click is valid.
 * @param options Additional options to customize the behavior.
 * @see https://svelte-librarian.github.io/sv-use/docs/core/sensors/on-click-outside
 */
export declare function onClickOutside<T extends HTMLElement>(element: Getter<T | null | undefined>, callback: (event: PointerEvent) => void, options?: OnClickOutsideOptions): CleanupFunction;
export {};

Sources