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

Handling Events

Svep för att visa menyn

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?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 6

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 3. Kapitel 6
some-alt