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

Handling Events

Sveip for å vise menyen

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?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 6

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 3. Kapittel 6
some-alt