Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Handling Events | Reactivity and User Interaction
Introduction to Svelte

Handling Events

Glissez pour afficher le menu

Frontend applications respond to user interactions constantly. Clicking buttons, typing into inputs, submitting forms, and hovering over elements all trigger events.

Svelte makes event handling simple by allowing developers to connect user actions directly to JavaScript functions.

What Are Events?

Events are actions performed by the user or the browser.

Common frontend events include:

  • Clicking buttons;
  • Typing into inputs;
  • Submitting forms;
  • Moving the mouse;
  • Pressing keyboard keys.

Applications listen for these events and respond with interactive behavior.

Handling a Click Event

Open App.svelte and add the following code:

<script>
  let count = 0;

  function increaseCount() {
    count += 1;
  }
</script>

<button on:click={increaseCount}>
  Click Me
</button>

<h2>Total Clicks: {count}</h2>

When the button is clicked, the increaseCount function runs and updates the value of count.

The interface updates automatically because the variable is reactive.

Inline Event Handlers

Svelte also allows inline event logic.

<button on:click={() => count += 1}>
  Increase
</button>

This approach is useful for small actions directly inside the component.

Working with Input Events

Events are commonly used with form elements.

<script>
  let message = "";
</script>

<input
  on:input={(event) => message = event.target.value}
/>

<p>{message}</p>

As the user types, the displayed text updates dynamically.

question mark

What happens when the button is clicked in the following code?

Sélectionnez la réponse correcte

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 3. Chapitre 6

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 3. Chapitre 6
some-alt