Skip to content

Svelte Events Explained — Handling DOM Events

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Svelte Events Explained. We cover key concepts, practical examples, and best practices to help you master this topic.

Svelte handles DOM events with the on: directive, event modifiers (preventDefault, stopPropagation), and component-level events dispatched with createEventDispatcher.

What You'll Learn

  • on:click, on:submit event handlers
  • Event modifiers (preventDefault, stopPropagation, once)
  • Inline vs function handlers
  • createEventDispatcher for component events
  • Event forwarding

Why It Matters

Svelte's event system is intuitive and compiles to native addEventListener calls. Event modifiers reduce boilerplate and event forwarding keeps component APIs clean.

<script>
  import { createEventDispatcher } from "svelte";
  const dispatch = createEventDispatcher();

  let count = 0;

  function handleClick() {
    count++;
    dispatch("increment", { count });
  }

  function handleKeydown(e) {
    if (e.key === "Enter") dispatch("submit", { value: e.target.value });
  }
</script>

<button on:click={handleClick}>
  Clicked {count} times
</button>

<input on:keydown={handleKeydown} placeholder="Press Enter" />

<form on:submit|preventDefault={() => dispatch("formSubmit")}>
  <button type="submit">Submit</button>
</form>

<button on:click|once={() => dispatch("oneTimeEvent")}>
  Fire once
</button>

Expected output: Click dispatches increment with current count, Enter dispatches submit with input value, and once button fires only the first click.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro