Skip to content

UseOn

katanakit-js / useOn

function useOn<K>(
target,
event,
callback,
options?
): (() => void) | null;

Defined in: infrastructure/dom/dom.service.ts:362

Attaches an event listener to the target element and returns a cleanup function.

Type Parameter Description
K extends keyof HTMLElementEventMap The event type key from HTMLElementEventMap.
Parameter Type Description
target string | EventTarget An EventTarget instance or a CSS selector string.
event K The event name to listen for.
callback (event) => void The event handler.
options? boolean | AddEventListenerOptions Optional addEventListener options.

(() => void) | null

A function that removes the listener, or null if not in a browser.

const off = useOn("#btn", "click", (e) => console.log("clicked", e));
// later:
off?.();