How to Handle Events in Svelte: Simple Event Binding Guide
on:eventName directives to elements, like on:click for clicks. You assign a function to run when the event happens, for example, <button on:click={handleClick}>. This binds the event cleanly and updates your component reactively.Why This Happens
Beginners often try to handle events in Svelte like plain HTML or React, using attributes like onclick or calling functions directly without the on: directive. This causes the event not to trigger or errors because Svelte expects its special syntax for event binding.
<script> function sayHello() { alert('Hello!'); } </script> <button onclick="sayHello()">Click me</button>
The Fix
Use Svelte's event binding syntax with on:eventName. Replace onclick with on:click and pass the function directly without quotes. This tells Svelte to listen for the event and run your function properly.
<script> function sayHello() { alert('Hello!'); } </script> <button on:click={sayHello}>Click me</button>
Prevention
Always use on:eventName for event handlers in Svelte. Avoid inline JavaScript strings for events. Use descriptive function names and keep handlers outside the markup for clarity. Enable Svelte linting tools to catch incorrect event usage early.
Related Errors
Common related issues include forgetting curly braces around the handler function, like on:click=sayHello instead of on:click={sayHello}, which causes errors. Another is trying to pass arguments directly in the markup, which requires wrapping the call in an arrow function.
<button on:click={sayHello('Hi')}>Click me</button> <!-- Incorrect -->
<button on:click={() => sayHello('Hi')}>Click me</button> <!-- Correct -->Key Takeaways
on:eventName syntax to bind events properly.