How to Use on:click in Svelte for Button Click Events
In Svelte, you use
on:click to listen for click events on elements like buttons. Attach it directly in your HTML tag with a function or inline code to run when the element is clicked.Syntax
The on:click directive attaches a click event listener to an element. You write it inside the element tag followed by an equals sign and curly braces containing the function to call.
- on:click: The event directive for click events.
- {handler}: The JavaScript function or inline code to execute on click.
svelte
<button on:click={handleClick}>Click me</button>Output
A button labeled 'Click me' that runs handleClick when clicked.
Example
This example shows a button that updates a counter each time it is clicked. It demonstrates how on:click triggers a function that changes component state.
svelte
<script> let count = 0; function increment() { count += 1; } </script> <button on:click={increment} aria-label="Increment counter">Clicked {count} times</button>
Output
A button showing 'Clicked 0 times' initially, increasing the number each click.
Common Pitfalls
Common mistakes include:
- Forgetting the curly braces around the function name, which breaks the event binding.
- Calling the function immediately by adding parentheses, instead of passing the function reference.
- Not using accessible labels or keyboard support for clickable elements.
svelte
<!-- Wrong: calls function immediately --> <button on:click={increment()}>Click me</button> <!-- Right: passes function reference --> <button on:click={increment}>Click me</button>
Quick Reference
| Usage | Description |
|---|---|
| Runs handler function on click | |
alert('Hi')}> | Runs inline code on click |
| Accessible clickable button |
Key Takeaways
Use
on:click with curly braces to attach click handlers in Svelte.Pass the function reference without parentheses to avoid immediate calls.
Update component state inside the handler to reflect UI changes.
Add accessible labels and consider keyboard navigation for clickable elements.