0
0
Svelteframework~5 mins

DOM event listeners (on:click) in Svelte

Choose your learning style9 modes available
Introduction

We use DOM event listeners to make web pages interactive. The on:click lets us run code when someone clicks a button or element.

When you want to run code after a user clicks a button.
To change something on the page when a user clicks an image or link.
To submit a form or show a message after a click.
To toggle a menu or open a popup when clicked.
Syntax
Svelte
<button on:click={handleClick}>Click me</button>

<script>
  function handleClick() {
    // code to run on click
  }
</script>

The on:click attribute listens for click events on the element.

The function inside { } runs when the click happens.

Examples
This example shows a quick alert popup when the button is clicked.
Svelte
<button on:click={() => alert('Hello!')}>Say Hello</button>
This example increases a number each time the button is clicked.
Svelte
<button on:click={increment}>Add 1</button>

<script>
  let count = 0;
  function increment() {
    count += 1;
  }
</script>
If you set on:click to null, clicking does nothing.
Svelte
<button on:click={null}>No action</button>
Sample Program

This Svelte component shows a message and a button. When you click the button, the message changes. The button has an aria-label for accessibility.

Svelte
<script>
  let message = 'Click the button';
  function handleClick() {
    message = 'Button clicked!';
  }
</script>

<main>
  <p>{message}</p>
  <button on:click={handleClick} aria-label="Click to change message">Click me</button>
</main>
OutputSuccess
Important Notes

Click event listeners run very fast and respond immediately to user clicks.

Remember to use descriptive function names like handleClick to keep code clear.

Use aria-label on clickable elements for better accessibility.

Summary

on:click lets you run code when an element is clicked.

Use it to make buttons and other elements interactive.

Always keep accessibility in mind by adding labels and clear text.