Skip to main content
Listen to DOM events by adding attributes that start with on to elements. Svelte makes event handling simple and performant with automatic delegation for common events.

Basic Event Handlers

Add event handlers using on followed by the event name:

Event Attribute Syntax

Event attributes are case sensitive:
  • onclick listens to the click event
  • onClick listens to the Click event (different event)
This ensures you can listen to custom events with uppercase characters.

Common Event Handlers

Mouse Events

Keyboard Events

Form Events

Touch Events

Event Object

Handlers receive the event object as the first parameter:

Inline Handlers

Write inline arrow functions for simple handlers:

Handler Shorthand

When the handler variable matches the event name, use shorthand:

Spreading Event Handlers

Event handlers can be spread like other attributes:

Event Timing

Event attributes fire after bindings update:

Event Delegation

Svelte uses event delegation for better performance. A single listener at the application root handles these events:
  • beforeinput
  • click
  • change
  • dblclick
  • contextmenu
  • focusin
  • focusout
  • input
  • keydown
  • keyup
  • mousedown
  • mousemove
  • mouseout
  • mouseover
  • mouseup
  • pointerdown
  • pointermove
  • pointerout
  • pointerover
  • pointerup
  • touchend
  • touchmove
  • touchstart

Delegation Gotchas

When using delegated events:
  • Set { bubbles: true } when manually dispatching events
  • Avoid stopPropagation() or events won’t reach the root
  • Handlers added with addEventListener inside the root run before declarative handlers

Passive Touch Events

ontouchstart and ontouchmove handlers are passive for better scrolling performance:
To call preventDefault(), use the on function from svelte/events:

Real-World Examples

Form Validation

Keyboard Shortcuts

Click Outside

Drag and Drop

Best Practices

  1. Prevent default carefully - Only call preventDefault() when necessary
  2. Clean up listeners - Remove event listeners in $effect cleanup functions
  3. Use delegation - Svelte’s delegation optimizes common events automatically
  4. Avoid stopPropagation - Can interfere with event delegation
  5. Debounce expensive operations - Use timeouts for search, resize, scroll handlers