iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Events

In Svelte 5 the idiomatic way to expose events is to pass a callback prop (e.g. onsave). For DOM events, use lower-case attributes (onclick, oninput). Modifiers from Svelte 4 (|preventDefault) are gone — call the method explicitly.

Native + custom events

EXAMPLE
<!-- Button.svelte -->
<script>
    let { label = 'OK', onclick, type = 'button' } = $props();
</script>

<button {type} {onclick}>{label}</button>

<!-- Usage -->
<script>
    import Button from './Button.svelte';

    let count = $state(0);
    function bump() { count++; }

    function submit(e) {
        e.preventDefault();   // explicit — no |preventDefault modifier
        console.log('submit');
    }
</script>

<Button label="Bump" onclick={bump} />
<p>Clicked {count}</p>

<form onsubmit={submit}>
    <input oninput={(e) => console.log(e.target.value)}>
    <Button label="Save" type="submit" />
</form>

<!-- Capture phase / once / passive -->
<button oncapturefocus={() => …}>capture</button>
<button onclick_capture={() => …}>same, alternate syntax</button>
<button onclick={onceOnly}>fires once</button>
<script>
    let onceOnly = $state(() => { console.log('once'); onceOnly = () => {}; });
</script>

Why it matters

Svelte 5 events are just props. That makes them easy to pass through, easy to spread, and easy to type — no special createEventDispatcher needed.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
<button onclick={inc}>+</button>
<!-- inline -->
<button onclick={() => count++}>+</button>
Try it Yourself »

Test yourself

Q1. In Svelte 5, you handle a click with…
Q2. A component emits to its parent by…
Q3. Event modifiers (in Svelte 4) include…

Discussion

Loading…