Chapter 6: Handling Events
In this chapter, you'll learn how to handle user interactions in Svelte. From simple click handlers to complex event management, we'll cover the essentials of working with events.
Basic Event Handlers
Attach event handlers using the on: directive:
<script>
function handleClick() {
alert('Button clicked!');
}
</script>
<button on:click={handleClick}>Click me</button>
Inline Event Handlers
You can also define inline event handlers:
<button on:click={() => alert('Clicked!')}>Click me</button>
Event Modifiers
Svelte provides useful event modifiers for common patterns:
- preventDefault: Prevents default browser behavior
- stopPropagation: Stops event bubbling
- passive: Improves scroll performance
- nonpassive: Explicitly non-passive
- capture: Fires during capture phase
- once: Fires only once
- self: Only fires if the event target is the element itself
<form on:submit|preventDefault={handleSubmit}>
<input type="text" />
<button type="submit">Submit</button>
</form>
Keyboard Events
Handle keyboard events with the on:keydown and on:keyup directives:
<input
on:keydown={(e) => {
if (e.key === 'Enter') {
console.log('Enter pressed');
}
}}
/>
Custom Events
Dispatch custom events from components:
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function notifyParent() {
dispatch('custom-event', { data: 'Hello parent!' });
}
</script>
<button on:click={notifyParent}>Send Event</button>
Event handling in Svelte is intuitive and flexible!