0
0
Svelteframework~5 mins

Inline event handlers in Svelte

Choose your learning style9 modes available
Introduction

Inline event handlers let you run code right where you write your HTML. This makes it easy to respond to user actions like clicks or typing.

You want to run a simple action when a button is clicked.
You need to update a value immediately when a user types in a box.
You want to call a function directly from an element without extra setup.
You want to keep your code easy to read by putting event logic close to the element.
Syntax
Svelte
<element on:eventName={handlerFunction} />

Use on: followed by the event name, like click or input.

The handler can be a function or inline code inside curly braces.

Examples
This runs the handleClick function when the button is clicked.
Svelte
<button on:click={handleClick}>Click me</button>
This updates the name variable as the user types.
Svelte
<input on:input={(e) => name = e.target.value} placeholder="Type your name" />
This logs a message when the mouse moves over the div.
Svelte
<div on:mouseover={() => console.log('Hovered!')}>Hover over me</div>
Sample Program

This Svelte component shows a button that counts how many times you click it. The on:click inline event handler calls the increment function each time you click.

It also uses an aria-label for accessibility, so screen readers can describe the button.

Svelte
<script>
  let count = 0;
  function increment() {
    count += 1;
  }
</script>

<button on:click={increment} aria-label="Increment counter">Clicked {count} times</button>
OutputSuccess
Important Notes

Always use semantic HTML elements and add aria-label or other accessibility attributes when needed.

Inline handlers keep your code simple but avoid putting complex logic directly inside them.

Use Svelte DevTools in your browser to see events and state changes live.

Summary

Inline event handlers in Svelte use on:eventName={handler} syntax.

They let you respond quickly to user actions like clicks or typing.

Keep handlers simple and use accessibility attributes for better user experience.