Svelte Event Handling
Svelte provides a straightforward way to handle DOM events and create custom events. This page demonstrates various ways to work with events in Svelte.
Basic DOM Events
Click Event
<button on:click={handleClick}>Click Me</button>
<script>
function handleClick() {
alert('Button clicked!');
}
</script>Inline Event Handlers
Counter with Inline Events
0
<button on:click={() => count -= 1}>-</button>
<span class="count">{count}</span>
<button on:click={() => count += 1}>+</button>
<script>
let count = 0;
</script>Event Modifiers
Event Modifier Examples
Svelte provides these event modifiers:
- preventDefault - calls event.preventDefault()
- stopPropagation - calls event.stopPropagation()
- passive - improves scrolling performance on touch/wheel events
- capture - fires the handler during the capture phase instead of bubbling
- once - fires the handler only once
- self - only trigger handler if event.target is the element itself
<button on:click|once={handleClick}>Click Once Only</button>
<button on:contextmenu|preventDefault={handleRightClick}>Right Click Me</button>Custom Component Events
Creating and Dispatching Events
<!-- In parent component -->
<Button on:buttonClick={handleCustomEvent} />
function handleCustomEvent(event) {
alert(`Custom event received: ${event.detail.message}`);
}
<!-- In Button.svelte -->
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function handleClick() {
dispatch('buttonClick', {
message: 'Hello from Button component'
});
}
</script>
<button on:click={handleClick}>
Click to Dispatch Event
</button>Component Communication Example
Todo List with Events
<!-- Parent Component -->
{#each todos as todo (todo.id)}
<TodoItem
{...todo}
on:delete={handleDelete}
on:toggle={handleToggle}
/>
{/each}
<!-- TodoItem.svelte -->
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let id;
export let text;
export let completed;
function deleteTodo() {
dispatch('delete', { id });
}
function toggleComplete() {
dispatch('toggle', { id });
}
</script>