new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Svelte · Language · all subjects

core/events

61 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

Event handlers in Svelte use on: directive

Event handlers in Svelte components are attached using the directive syntax. In the example, onclick={greet} directly binds a function to a button element's click event.

Custom element event listener syntax

When using a custom element compiled from a Svelte component, event listeners are attached using the 'on' prefix followed by the event name in lowercase. For example, ondecrement and onincrement listen to 'decrement' and 'increment' custom events respectively.

Event attributes are case sensitive

Event attributes are case sensitive in Svelte. `onclick` listens to the `click` event, while `onClick` listens to the `Click` event. This distinction allows listening to custom events that have uppercase characters in them.

Event attribute shorthand form

Event attributes follow the same rules as regular attributes, allowing the shorthand form where `<button {onclick}>click me</button>` is valid.

Event attributes can be spread

Event attributes can be spread onto elements using spread syntax, such as `<button {...thisSpreadContainsEventAttributes}>click me</button>`.

Event attributes fire after bindings

Event attributes always fire after events from bindings. For example, `oninput` always fires after an update to `bind:value`.

Some event handlers are delegated

Under the hood, some event handlers are attached directly with `addEventListener`, while others are delegated for performance and reduced memory footprint.

ontouchstart and ontouchmove are passive listeners

When using `ontouchstart` and `ontouchmove` event attributes, the handlers are passive for better performance. This improves responsiveness by allowing the browser to scroll the document immediately, rather than waiting to see if the event handler calls `event.preventDefault()`.

Use on function for preventing event defaults on passive listeners

In the rare cases where you need to prevent event defaults on passive listeners like `ontouchstart` and `ontouchmove`, use the `on` function imported from `svelte/events` instead (for example inside an action).

Event delegation gotcha: bubbles option

When manually dispatching an event with a delegated listener, ensure the `{ bubbles: true }` option is set or the event won't reach the application root where the delegated handler is registered.

Manual event handlers run before declarative handlers

Handlers added manually inside the application root with `addEventListener` will run before handlers added declaratively deeper in the DOM with event attributes like `onclick={...}`, in both capturing and bubbling phases.

Event listener syntax with on prefix

DOM events are listened to by adding attributes to elements that start with `on`. For example, to listen to the `click` event, add the `onclick` attribute: `<button onclick={() => console.log('clicked')}>click me</button>`.

List of delegated event handlers

The following event handlers are delegated in Svelte: `beforeinput`, `click`, `change`, `dblclick`, `contextmenu`, `focusin`, `focusout`, `input`, `keydown`, `keyup`, `mousedown`, `mousemove`, `mouseout`, `mouseover`, `mouseup`, `pointerdown`, `pointermove`, `pointerout`, `pointerover`, `pointerup`, `touchend`, `touchmove`, `touchstart`.

Use on function from svelte/events for proper handler ordering

It is better to use the `on` function imported from `svelte/events` rather than `addEventListener` directly, as it will ensure that handler order is preserved and `stopPropagation` is handled correctly.

Event delegation gotcha: stopPropagation

When using `addEventListener` directly with delegated events, avoid calling `stopPropagation` or the event won't reach the application root and delegated handlers won't be invoked.

Transition events dispatched by elements

An element with transitions dispatches the following events in addition to standard DOM events: introstart, introend, outrostart, and outroend. These can be handled with on-event listeners like onintrostart, onintroend, onoutrostart, and onoutroend.

Event listeners on any element attribute starting with 'on'

Any element attribute starting with 'on' is treated as an event listener. You can use onclick={() => {...}}, attribute shorthand like {onclick}, or spread attributes like {...props}.

Attach listeners to window or document with svelte:window and svelte:document

If you need to attach listeners to window or document you can use <svelte:window> and <svelte:document> with event handlers like onkeydown and onvisibilitychange. Avoid using onMount or $effect for this.

Replace on:click directive with onclick attribute

Use onclick={...} instead of on:click={...}.

Action type default parameter in Svelte 4

Action and ActionReturn types now have a default parameter type of undefined. You must type the generic if you want to specify that an action receives a parameter: Action<HTMLElement, ParamType> where ParamType is the expected parameter type.

createEventDispatcher stricter typing in Svelte 4

createEventDispatcher now supports specifying that a payload is optional, required, or non-existent (null type), and call sites are checked accordingly. A null type means no argument should be passed, and required types mean the detail argument is mandatory.

Multiple event handlers on same element are not allowed

In Svelte 5, duplicate attributes/properties on elements are not allowed. Multiple handlers for the same event must be combined in a single handler function. Example: onclick={(e) => { one(e); two(e); }}

Event handlers use onevent attributes instead of on: directives

In Svelte 5, event handlers are attached using properties (onevent attributes) instead of on: directives. The colon is removed: onclick instead of on:click.

Event handler shorthand syntax for named functions

When using a named event handler function in Svelte 5, you can use the standard property shorthand syntax. Example: function onclick() { count++; } then <button {onclick}>

createEventDispatcher is deprecated in Svelte 5

In Svelte 5, createEventDispatcher is deprecated. Instead, components should accept callback props, which are functions passed as properties to components.

Component events use callback props instead of custom events

In Svelte 5, component events are implemented by passing callback functions as props rather than creating CustomEvent objects with createEventDispatcher. Example: <Pump inflate={fn} deflate={fn} />

Event modifiers are not applicable to event attributes

Event modifiers (|once, |preventDefault, etc.) cannot be used with event attributes (onclick, onchange, etc.). Instead, handle the logic directly in the handler function or create wrapper functions.

capture modifier becomes onclickcapture event attribute

The capture modifier for event attributes is expressed by appending 'capture' to the event name. Example: onclickcapture instead of on:click|capture

passive and nonpassive modifiers require actions in Svelte 5

The passive and nonpassive event modifiers cannot be expressed as wrapper functions. If needed, you must use an action to apply the event handler yourself with the appropriate options.

Local event handlers must come after spread props

When spreading props that may contain event handlers, local event handlers must be placed after the spread to avoid being overwritten. Example: {...props} onclick={(e) => { doStuff(e); props.onclick?.(e); }}

Touch events are passive by default

In Svelte 5, ontouchstart and ontouchmove event handlers are passive to align with browser defaults. This improves responsiveness by allowing immediate scrolling without waiting for preventDefault().

oneventname attributes no longer accept string values

In Svelte 5, event attributes like onclick no longer accept string values. Use function values instead. String values like onclick="alert('hello')" are no longer valid.

onevent attributes are delegated

In Svelte 5, onevent attributes are delegated, meaning event handlers are attached at a higher level. Be careful not to stop event propagation on delegated events as they may not reach the listener.

Compile warning: event_directive_deprecated

The event_directive_deprecated warning is triggered when using the `on:%name%` directive to listen to events. This syntax is deprecated in Svelte 5. Use the event attribute `on%name%` instead. See the v5 migration guide for more information.

EventDispatcher interface for component events

EventDispatcher is an interface with a call signature that accepts event type and optional parameter based on the EventMap type. When parameter is null or undefined, it is optional. Otherwise it is required. Returns boolean.

createEventDispatcher deprecated, use callback props instead

createEventDispatcher creates an event dispatcher for component events. In Svelte 5, use callback props and/or the $host() rune instead. Component events created with createEventDispatcher create CustomEvents which do not bubble.

on function overload for Document

The on function has an overload for Document targets with signature: function on<Type extends keyof DocumentEventMap>(document: Document, type: Type, handler: (this: Document, event: DocumentEventMap[Type] & { currentTarget: Document }) => any, options?: AddEventListenerOptions | undefined): () => void. The handler receives the document as this context and the event is typed from DocumentEventMap.

on function overload for HTMLElement

The on function has an overload for HTMLElement targets with signature: function on<Element extends HTMLElement, Type extends keyof HTMLElementEventMap>(element: Element, type: Type, handler: (this: Element, event: HTMLElementEventMap[Type] & { currentTarget: Element }) => any, options?: AddEventListenerOptions | undefined): () => void. The handler receives the element as this context and the event is typed from HTMLElementEventMap.

on function overload for generic EventTarget

The on function has a generic overload for any EventTarget with signature: function on(element: EventTarget, type: string, handler: EventListener, options?: AddEventListenerOptions | undefined): () => void. This is the most generic overload that accepts any EventTarget and untyped event handler.

on function overload for MediaQueryList

The on function has an overload for MediaQueryList targets with signature: function on<Element extends MediaQueryList, Type extends keyof MediaQueryListEventMap>(element: Element, type: Type, handler: (this: Element, event: MediaQueryListEventMap[Type] & { currentTarget: Element }) => any, options?: AddEventListenerOptions | undefined): () => void. The handler receives the element as this context and the event is typed from MediaQueryListEventMap.

svelte/events on function signature and purpose

The on function from svelte/events attaches an event handler to a target (window, document, element, or EventTarget) and returns a function that removes the handler. Using on preserves the correct order of handlers relative to declaratively-added handlers (such as onclick attributes), which use event delegation for performance reasons. This function should be preferred over addEventListener for maintaining proper handler ordering.

on function overload for Window

The on function has an overload for Window targets with signature: function on<Type extends keyof WindowEventMap>(window: Window, type: Type, handler: (this: Window, event: WindowEventMap[Type] & { currentTarget: Window }) => any, options?: AddEventListenerOptions | undefined): () => void. The handler receives the window as this context and the event is typed from WindowEventMap.

passive action substitute for passive event modifier

passive is a substitute for the passive event modifier from Svelte 4, implemented as an action. Type signature: function passive(node: HTMLElement, [event, handler]: [event: string, handler: () => EventListener]): void.

createBubbler creates bubble function mimicking Svelte 4 event delegation

createBubbler creates a bubble function that mimics the behavior of on:click without handler available in Svelte 4. It is marked as deprecated and should only be used as a temporary solution to migrate automatically delegated events in Svelte 5. Type signature: function createBubbler(): (type: string) => (event: Event) => boolean.

handlers function combines multiple event listeners from Svelte 4

handlers is a function that mimics the multiple listeners available in Svelte 4. Type signature: function handlers(...handlers: EventListener[]): EventListener.

nonpassive action substitute for nonpassive event modifier

nonpassive is a substitute for the nonpassive event modifier from Svelte 4, implemented as an action. Type signature: function nonpassive(node: HTMLElement, [event, handler]: [event: string, handler: () => EventListener]): void.

once function substitute for once event modifier

once is a substitute for the once event modifier from Svelte 4. Type signature: function once(fn: (event: Event, ...args: Array<unknown>) => void): (event: Event, ...args: unknown[]) => void.

preventDefault function substitute for preventDefault event modifier

preventDefault is a substitute for the preventDefault event modifier from Svelte 4. Type signature: function preventDefault(fn: (event: Event, ...args: Array<unknown>) => void): (event: Event, ...args: unknown[]) => void.

self function substitute for self event modifier

self is a substitute for the self event modifier from Svelte 4. Type signature: function self(fn: (event: Event, ...args: Array<unknown>) => void): (event: Event, ...args: unknown[]) => void.

stopPropagation function substitute for stopPropagation event modifier

stopPropagation is a substitute for the stopPropagation event modifier from Svelte 4. Type signature: function stopPropagation(fn: (event: Event, ...args: Array<unknown>) => void): (event: Event, ...args: unknown[]) => void.

trusted function substitute for trusted event modifier

trusted is a substitute for the trusted event modifier from Svelte 4. Type signature: function trusted(fn: (event: Event, ...args: Array<unknown>) => void): (event: Event, ...args: unknown[]) => void.

event_directive_deprecated warning

The `event_directive_deprecated` warning alerts that using `on:%name%` to listen to events is deprecated. Use the event attribute `on%name%` instead. See the v5 migration guide for more information.

on: directive in legacy mode

In Svelte 4 legacy mode, event handlers are declared using the on: directive. In Svelte 5 runes mode, event handlers are just like any other attribute or prop.

on: directive syntax and inline handlers

Event handlers are attached to elements using on:eventname={handler} syntax. Handlers can be declared inline with no performance penalty, for example on:click={() => (count += 1)}.

Event handler modifiers in legacy mode

The following modifiers are available for event handlers with the | character: preventDefault (calls event.preventDefault() before running the handler), stopPropagation (calls event.stopPropagation()), stopImmediatePropagation (calls event.stopImmediatePropagation()), passive (improves scrolling performance on touch/wheel events), nonpassive (explicitly set passive: false), capture (fires the handler during the capture phase instead of bubbling phase), once (remove the handler after the first time it runs), self (only trigger handler if event.target is the element itself), and trusted (only trigger handler if event.isTrusted is true, meaning the event is triggered by a user action). Modifiers can be chained together, e.g. on:click|once|capture={...}.

Event forwarding with on: directive

If the on: directive is used without a value, the component will forward the event, meaning that a consumer of the component can listen for it. For example, <button on:click> will emit the click event from the component.

Multiple event listeners for the same event

It is possible to have multiple event listeners for the same event on a single element, by using multiple on:eventname directives with different handlers.

createEventDispatcher for component events in legacy mode

Components can dispatch custom events by creating a dispatcher when they are initialized using createEventDispatcher() from 'svelte'. The dispatcher creates a CustomEvent. If a second argument is provided to dispatch(), it becomes the detail property of the event object.

Component event listeners in legacy mode

A consumer of a component can listen for dispatched events using on:eventname syntax. Component events do not bubble — a parent component can only listen for events on its immediate children.

Migration path from createEventDispatcher to Svelte 5

For an eventual migration to Svelte 5, use callback props instead of createEventDispatcher. This will make upgrading easier as createEventDispatcher is deprecated. Replace dispatch() calls with callback props exported from the component.

Give your agent this brain