Chapter 6: Handling Events

Svelte connects DOM events and custom component events through a unified on: directive, with declarative modifiers that eliminate boilerplate around propagation and form submission.

Basic Event Handlers

Attach DOM listeners to any HTML element using on:<event>={handler}. Pass a function reference rather than invoking the function in the template, and use native interactive elements like <button> instead of clickable <div> tags so keyboard focus and screen-reader roles work automatically:

<script>
  let clicks = 0;

  function handleClick() {
    clicks += 1;
  }
</script>

<button type="button" on:click={handleClick}>Clicked {clicks} times</button>

Inline Event Handlers

When a handler needs item-specific arguments—such as deleting a specific row inside an {#each} loop—use an inline arrow function. Unlike some runtime frameworks, Svelte compiles inline handlers efficiently without penalty:

<button type="button" on:click={() => deleteItem(item.id)}>Delete</button>

Event Modifiers

Instead of repeating event.preventDefault() or event.stopPropagation() inside every handler body, chain pipe-separated modifiers directly onto the directive:

  • preventDefault: Calls event.preventDefault() before running the handler (essential for on:submit).
  • stopPropagation: Prevents the event from bubbling to ancestor elements.
  • passive / nonpassive: Controls scroll-blocking behavior on touch and wheel listeners.
  • capture: Fires the handler during the capture phase instead of bubbling.
  • once: Automatically removes the listener after its first invocation.
  • self: Fires only when event.target is the element itself (useful for modal backdrop clicks).
<form on:submit|preventDefault={handleSubmit}>
  <input type="text" bind:value={query} />
  <button type="submit">Search</button>
</form>

Keyboard Events

Use on:keydown or on:keyup to support keyboard shortcuts, escape-to-close dialogs, or arrow-key list navigation. Always inspect event.key (rather than deprecated numeric keyCode values):

<input
  type="text"
  placeholder="Press Enter to add"
  on:keydown={(e) => {
    if (e.key === 'Enter' && e.currentTarget.value.trim()) {
      addTodo(e.currentTarget.value.trim());
    }
  }}
/>

Custom Events

Child components communicate upward by creating a dispatcher with createEventDispatcher() and calling dispatch(eventName, detail). Parent components listen with the exact same on: syntax and read the payload from event.detail:

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

  const dispatch = createEventDispatcher();

  function notifyParent() {
    dispatch('confirm', { timestamp: Date.now() });
  }
</script>

<button type="button" on:click={notifyParent}>Confirm Action</button>

Practice: Build a modal dialog that closes when clicking its backdrop (on:click|self) or pressing Escape, and dispatches a custom confirm event when the primary button is clicked.