0
0
SvelteHow-ToBeginner · 3 min read

How to Use on:click in Svelte 5: Simple Event Handling

In Svelte 5, use on:click to listen for click events on elements. Attach it directly in your markup like <button on:click={handler}> where handler is a function called when the element is clicked.
📐

Syntax

The on:click directive attaches a click event listener to an HTML element. The value inside the curly braces is a JavaScript function that runs when the element is clicked.

  • on:click: The event directive for click events.
  • {handler}: The function to call on click.
svelte
<button on:click={handleClick}>Click me</button>

<script>
  function handleClick() {
    alert('Button clicked!');
  }
</script>
Output
A button labeled 'Click me' that shows an alert 'Button clicked!' when clicked.
💻

Example

This example shows a button that increases a counter each time it is clicked using on:click. It demonstrates how to update component state reactively.

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 displaying 'Clicked 0 times' initially, increasing the number each time it is clicked.
⚠️

Common Pitfalls

Common mistakes include:

  • Not wrapping the handler in curly braces, e.g., on:click=handleClick instead of on:click={handleClick}.
  • Calling the function immediately by adding parentheses, e.g., on:click={handleClick()} runs the function on render, not on click.
  • Forgetting to define the handler function in the <script> block.
svelte
<!-- Wrong: calls function immediately -->
<button on:click={handleClick()}>Wrong</button>

<script>
  function handleClick() {
    alert('This runs on render, not click');
  }
</script>

<!-- Right: pass function reference -->
<button on:click={handleClick}>Right</button>
Output
Two buttons: the first triggers alert immediately on page load (wrong), the second triggers alert only on click (right).
📊

Quick Reference

Tips for using on:click in Svelte 5:

  • Always use curly braces to pass the function: on:click={myFunction}.
  • Use inline arrow functions for simple handlers: on:click={() => count++}.
  • Add aria-label for accessibility on clickable elements.
  • Use event.preventDefault() inside handlers to stop default actions if needed.

Key Takeaways

Use on:click={handler} to attach click events in Svelte 5.
Pass the function reference without parentheses to avoid immediate calls.
Update reactive variables inside the handler to reflect UI changes.
Add accessibility attributes like aria-label on clickable elements.
Use inline arrow functions for simple click handlers when preferred.