Consider this Svelte component:
<script>
let count = 0;
function increment() {
count += 1;
}
</script>
<button on:click={increment}>Click me</button>
<p>Count: {count}</p>What will the user see after clicking the button three times?
<script>
let count = 0;
function increment() {
count += 1;
}
</script>
<button on:click={increment}>Click me</button>
<p>Count: {count}</p>Each click calls the increment function which adds 1 to count.
Every time the button is clicked, the increment function runs, increasing count by 1. After three clicks, count becomes 3 and the UI updates to show this.
Look at this Svelte code snippet:
<script>
let message = '';
function handleKey(event) {
message = event.key;
}
</script>
<input on:keydown={handleKey} placeholder="Press a key"/>
<p>Last key pressed: {message}</p>If the user presses the 'a' key, what will message show?
<script>
let message = '';
function handleKey(event) {
message = event.key;
}
</script>
<input on:keydown={handleKey} placeholder="Press a key"/>
<p>Last key pressed: {message}</p>The event.key property holds the character of the key pressed.
When a key is pressed, event.key contains the actual character, like 'a'. So message updates to 'a'.
You want to listen to a custom event named myevent on a child component. Which syntax is correct?
Svelte uses on:eventname to listen to events.
Svelte's syntax for event listeners is on:eventname={handler}. Other options are invalid syntax.
Examine this Svelte code:
<script>
let count = {value: 0};
function increment() {
count.value++;
}
</script>
<button on:click={increment}>Add</button>
<p>Count: {count.value}</p>Clicking the button does not update the displayed count. Why?
<script>
let count = {value: 0};
function increment() {
count.value++;
}
</script>
<button on:click={increment}>Add</button>
<p>Count: {count.value}</p>Svelte tracks changes by assignments, not mutations.
Svelte only updates the UI when variables are reassigned. Using count.value++ mutates but does not reassign count. Changing to count = { ...count, value: count.value + 1 } fixes this.
Which statement best explains why events drive user interaction in Svelte?
Think about how user clicks or key presses change what you see.
Events are signals from the user that trigger code in Svelte components. This code changes state and updates the UI, making the app interactive.