0
0
SvelteDebug / FixBeginner · 4 min read

How to Handle Events in Svelte: Simple Event Binding Guide

In Svelte, you handle events by adding 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.

svelte
<script>
  function sayHello() {
    alert('Hello!');
  }
</script>

<button onclick="sayHello()">Click me</button>
Output
No alert appears when clicking the button because Svelte does not recognize the plain HTML onclick attribute.
🔧

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.

svelte
<script>
  function sayHello() {
    alert('Hello!');
  }
</script>

<button on:click={sayHello}>Click me</button>
Output
When you click the button, an alert box shows 'Hello!'
🛡️

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.

svelte
<button on:click={sayHello('Hi')}>Click me</button> <!-- Incorrect -->

<button on:click={() => sayHello('Hi')}>Click me</button> <!-- Correct -->
Output
The first button causes an error or runs immediately; the second runs sayHello with 'Hi' only when clicked.

Key Takeaways

Use Svelte's on:eventName syntax to bind events properly.
Pass handler functions with curly braces, never as strings.
Wrap calls with arguments in arrow functions inside event bindings.
Keep event handlers outside markup for readability and reuse.
Use Svelte linting to catch event binding mistakes early.