Introduction
Events let your app respond when users do things like click, type, or move the mouse. They make your app interactive and alive.
Events let your app respond when users do things like click, type, or move the mouse. They make your app interactive and alive.
<button on:click={handleClick}>Click me</button>
<script>
function handleClick() {
alert('Button clicked!');
}
</script>on:eventName to listen for events in Svelte.<input on:input={handleInput} placeholder="Type here" />
<script>
function handleInput(event) {
console.log(event.target.value);
}
</script><div on:mouseover={handleHover}>Hover over me</div>
<script>
function handleHover() {
console.log('Mouse is over the div');
}
</script><button on:click={() => alert('Clicked!')}>Click me</button>This simple Svelte component shows a button that counts how many times you click it. Each click triggers the increment function via the on:click event.
<script> let count = 0; function increment() { count += 1; } </script> <button on:click={increment} aria-label="Increment counter">Clicked {count} times</button>
Always use semantic HTML and add aria-label for accessibility.
Events are the main way to make your app respond to users.
Use browser DevTools to watch events and debug your handlers.
Events let your app listen and respond to user actions.
In Svelte, use on:eventName to handle events.
Event handlers run code that updates your app or UI.
on:click directive do?on:clickon:click directive in Svelte listens for when the user clicks on an element.on:eventName to listen to events, so on:submit is correct.<script>
let count = 0;
function increment() {
count += 1;
}
</script>
<button on:click={increment}>Clicked {count} times</button>countlet are reactive, so updating count updates the UI.increment(), which adds 1 to count, updating the displayed text.<script>
let name = '';
function updateName(event) {
name = event.target.value;
}
</script>
<input type="text" on:input={updateName} />
<p>Hello, {name}!</p>on:input event fires whenever the user types, which is appropriate here.event.target.value correctly accesses the input's current value.shiftKey boolean indicating if Shift was pressed during the click.event.shiftKey before incrementing count, which is correct.count.shiftKey; { if(event.key === 'Shift') count++ }}>Click me checks event.key which is undefined on click events.Pass the test and this pattern moves unknown