on to elements. Svelte makes event handling simple and performant with automatic delegation for common events.
Basic Event Handlers
Add event handlers usingon followed by the event name:
Event Attribute Syntax
Event attributes are case sensitive:onclicklistens to theclickeventonClicklistens to theClickevent (different event)
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:beforeinputclickchangedblclickcontextmenufocusinfocusoutinputkeydownkeyupmousedownmousemovemouseoutmouseovermouseuppointerdownpointermovepointeroutpointeroverpointeruptouchendtouchmovetouchstart
Delegation Gotchas
Passive Touch Events
ontouchstart and ontouchmove handlers are passive for better scrolling performance:
preventDefault(), use the on function from svelte/events:
Real-World Examples
Form Validation
Keyboard Shortcuts
Click Outside
Drag and Drop
Debounced Search
Best Practices
- Prevent default carefully - Only call
preventDefault()when necessary - Clean up listeners - Remove event listeners in
$effectcleanup functions - Use delegation - Svelte’s delegation optimizes common events automatically
- Avoid stopPropagation - Can interfere with event delegation
- Debounce expensive operations - Use timeouts for search, resize, scroll handlers