0
0
Svelteframework~5 mins

Why events drive user interaction in Svelte

Choose your learning style9 modes available
Introduction

Events let your app respond when users do things like click, type, or move the mouse. They make your app interactive and alive.

When you want to run code after a button is clicked.
When you need to update the screen as the user types in a form.
When you want to react to mouse movements or keyboard presses.
When you want to show or hide parts of the page based on user actions.
When you want to validate input as soon as the user changes it.
Syntax
Svelte
<button on:click={handleClick}>Click me</button>

<script>
  function handleClick() {
    alert('Button clicked!');
  }
</script>
Use on:eventName to listen for events in Svelte.
The event handler is a function that runs when the event happens.
Examples
This listens for typing in an input box and logs what you type.
Svelte
<input on:input={handleInput} placeholder="Type here" />

<script>
  function handleInput(event) {
    console.log(event.target.value);
  }
</script>
This runs code when the mouse moves over the box.
Svelte
<div on:mouseover={handleHover}>Hover over me</div>

<script>
  function handleHover() {
    console.log('Mouse is over the div');
  }
</script>
You can use an inline function directly in the event handler.
Svelte
<button on:click={() => alert('Clicked!')}>Click me</button>
Sample Program

This simple Svelte component shows a button that counts how many times you click it. Each click triggers the increment function via the on:click event.

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 and add aria-label for accessibility.

Events are the main way to make your app respond to users.

Use browser DevTools to watch events and debug your handlers.

Summary

Events let your app listen and respond to user actions.

In Svelte, use on:eventName to handle events.

Event handlers run code that updates your app or UI.