Detect pointer events outside a DOM element. Zero dependencies, SSR-safe, ESM + CJS.
pnpm add @kembec/outside-click-jsimport { outsideClick } from "@kembec/outside-click-js";
const cancel = outsideClick("my-dropdown", () => {
console.log("clicked outside");
});
cancel();
outsideClick("my-modal", closeModal, { timeout: 100 });
const controller = new AbortController();
outsideClick("my-menu", closeMenu, { signal: controller.signal });
controller.abort();
const el = document.querySelector("#panel")!;
outsideClick(el, handleOutside);outsideClick(
target: string | HTMLElement,
onOutsideClick: () => void,
options?: { timeout?: number; signal?: AbortSignal }
): () => voidtarget— element ID string orHTMLElementreferenceonOutsideClick— called once on the firstpointerdownoutsidetargetoptions.timeout— ms to wait before attaching the listener (default0)options.signal—AbortSignalto cancel the listener externally- Returns a
cancel()function — call it to remove the listener before it fires
| v1 | v2 |
|---|---|
outsideClick('id', cb, 500) |
outsideClick('id', cb, { timeout: 500 }) |
Return value was void |
Now returns () => void (cleanup) |
AGPL-3.0