createEventListener
Attach typed DOM event listeners that clean up automatically when the Solid owner scope disposes.
createEventListener and createEventListenerMap attach DOM event listeners to a Window, Document, MediaQueryList, element, or other EventTarget. Each registers its removal with onCleanup in the active Solid owner, so the listener detaches when that scope disposes.
Import#
Signatures#
EventListenerMap maps event types to either a listener or a [listener, options] tuple. A tuple’s options replace the shared options for that event.
Usage Example#
Single Event with createEventListener#
src/EscapeListener.tsx
Multiple Events with createEventListenerMap#
src/DragObserver.tsx
Features#
- The event type and
eventargument narrow from the target:windowkeydowngives aKeyboardEvent,windowresizegives aUIEvent. - Cleanup registers through
onCleanupin the active owner, including when you call the hook fromonMount. - A
nullorundefinedtarget is a no-op; no listener is attached. - The hooks are not reactive. They read
target,type, andoptionsonce. To follow a changing target, call them insidecreateEffect(on(target, ...)). - Call them from a component body,
onMount, or an effect. Do not call them inside arefcallback.