Svelte logo

Svelte by Example: Events

Register event listeners on HTML elements and Svelte components with the on: directive.

In this example, we'll call alert('Good job!') when a task is completed.

Event handlers are defined as functions.

Event handlers are registered as listener with on: followed by the event name.

Todo.svelte
<script>
  export let task;
  export let completed = false;

  function handleInput(event) {
    if (event.target.checked) {
      alert('Good job!');
    }
  }
</script>

<p>
  <input
    type="checkbox"
    checked={completed}
    on:input={handleInput}
  >
  {task}
</p>

Components can dispatch events to parent components with Svelte's built-in createEventDispatcher helper.

Provide an event name and data for your component to dispatch.

Create a handler for your custom event.

Register your handler as a listener for your custom event.

Todo.svelte
<script>
  import { createEventDispatcher } from 'svelte';

  const dispatch = createEventDispatcher();

  export let task;
  export let completed = false;

  function handleInput(event) {
    dispatch('checked', {
      checked: event.target.checked,
    });
  }
</script>

<p>
  <input
    type="checkbox"
    checked={completed}
    on:input={handleInput}
  >
  {task}
</p>
TodoList.svelte
<script>
  import Todo from './Todo.svelte';

  function handleChecked(event) {
    if (event.detail.checked) {
      alert('Good job!');
    }
  }
</script>

<Todo
  task="Mow lawn"
  on:checked={handleChecked}
/>

Svelte also supports event modifiers on native DOM events.

<script>
  function clear() {
    // …
  }
</script>

<button on:click|preventDefault={clear}>
  Clear todo list
</button>