Handling DOM Events
Wiring up click, input, and other DOM events with Svelte's onevent attribute syntax.
読了時間 2 分
Svelte 5 handles DOM events as plain attributes: prefix any DOM event name with on and assign it a function.
<script>
let count = $state(0);
function increment() {
count++;
}
</script>
<button onclick={increment}>
Clicked {count} times
</button>onclick, oninput, onkeydown, onsubmit — any event the DOM supports has a matching attribute, and you pass it a function reference just like you'd pass any other prop. If you've used older Svelte code (or tutorials still showing Svelte 4), you may see on:click={increment} instead — that colon-based directive syntax still works, but onclick={...} is the current, preferred form: events are treated the same way as any other prop, rather than as a special directive with its own syntax.
Inline handlers
For small handlers, an inline arrow function is often clearer than naming a separate function:
<script>
let count = $state(0);
</script>
<button onclick={() => count++}>Increment</button>
<button onclick={() => (count = 0)}>Reset</button>Reading event details
The handler receives the native DOM event object, exactly as it would in vanilla JavaScript:
<script>
let value = $state('');
function handleInput(event) {
value = event.target.value;
}
</script>
<input oninput={handleInput} />
<p>You typed: {value}</p>(In practice, this particular pattern — syncing an input to a variable — is common enough that Svelte has a dedicated shorthand for it, bind:value, covered in the next lesson. But it's worth seeing the manual version first, since it's the same mechanism every other event ultimately uses.)
Event modifiers become plain code
Older Svelte versions had special modifiers like on:submit|preventDefault. In Svelte 5, since events are just function props, you call the native methods yourself:
<script>
function handleSubmit(event) {
event.preventDefault();
// ...submit logic
}
</script>
<form onsubmit={handleSubmit}>
<button type="submit">Save</button>
</form>This is a deliberate simplification: rather than learning a set of modifier keywords, you write the same event.preventDefault() or event.stopPropagation() you'd already use in plain JavaScript, and it behaves exactly as you'd expect.