Svelte logo

Svelte by Example: Events

Register event listeners on HTML elements with event attributes like onclick and oninput. Components can receive functions as callback props.

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

Event handlers are defined as functions. They receive the native DOM event.

Register a handler with on followed by the event name.

Todo.svelte
<script>
  let { task, completed = false } = $props();

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

<p>
  <input
    type="checkbox"
    checked={completed}

    oninput={handleInput}
  >
  {task}
</p>

Components can receive callbacks like any other prop.

Call the callback with the data the parent needs. Here, we pass a boolean, not an event.

Todo.svelte
<script>
  let {
    task,
    completed = false,
    onchecked,
  } = $props();



  function handleInput(event) {
    onchecked(event.target.checked);
  }
</script>

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

The parent defines a callback to receive the data.

Pass the callback as a prop. The onchecked name is our choice, not a built-in event.

TodoList.svelte
<script>
  import Todo from './Todo.svelte';

  function handleChecked(completed) {
    if (completed) {
      alert('Good job!');
    }
  }
</script>

<Todo
  task="Mow lawn"

  onchecked={handleChecked}
/>

To prevent a browser's default behavior, call event.preventDefault() in the handler. Event attributes don't use modifiers.

AddTodo.svelte
<script>
  let { onadd } = $props();

  function submit(event) {
    event.preventDefault();
    onadd({ task: 'Mow lawn', completed: false });
  }
</script>

<form onsubmit={submit}>
  <button>Add todo</button>
</form>