Handling Events
Stryg for at vise menuen
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.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat