Svelte and SvelteKit course Β· Module 1: Introduction to Svelte

Event Handling

4 min read Β·
In this lesson7

In Svelte 5 we handle events with event attributes: onclick, oninput, onkeydown, onsubmit... They are ordinary attributes with a function in curly braces. It is like responding to signals from a war horn!

Basic Syntax

<script>
  function handleClick() {
    alert('The Viking attacked!');
  }
</script>

<button onclick={handleClick}>
  Attack!
</button>

The attribute name is on + the event name, in lowercase: onclick listens for the click event. Letter case matters - onClick is something else!

Inline Functions

You can also write functions directly:

<button onclick={() => alert('SKAL!')}>
  Toast!
</button>

Shorthand: {onclick}

When the function has the same name as the attribute, you can use the shorthand:

<script>
  function onclick() {
    alert('The war horn sounded!');
  }
</script>

<button {onclick}>Blow the horn</button>

The Event Object

The function receives an event object as an argument:

<script>
  function handleClick(event) {
    console.log('Clicked on:', event.target);
    console.log('Position X:', event.clientX);
    console.log('Position Y:', event.clientY);
  }
</script>

<button onclick={handleClick} class="battlefield">
  Click on the battlefield
</button>

Common Events

<script>
  let message = $state('');
  let isHovering = $state(false);

  function handleSubmit(event) {
    event.preventDefault(); // the form will not reload the page
    message = 'Form submitted!';
  }
</script>

<!-- Mouse events -->
<button onclick={() => message = 'Clicked!'}>Click</button>
<button ondblclick={() => message = 'Double click!'}>Double</button>

<button
  onmouseenter={() => isHovering = true}
  onmouseleave={() => isHovering = false}
  class:hovering={isHovering}
>
  {isHovering ? 'Hovered!' : 'Hover over me'}
</button>

<!-- Keyboard events -->
<input
  onkeydown={(e) => message = `Pressed: ${e.key}`}
  onfocus={() => message = 'Input active'}
  onblur={() => message = 'Input inactive'}
  placeholder="Type something..."
>

<!-- Form events -->
<form onsubmit={handleSubmit}>
  <button type="submit">Submit</button>
</form>

<p>{message}</p>

Instead of Modifiers - Plain JavaScript

In Svelte 4 you added modifiers to events, such as on:submit|preventDefault. Event attributes in Svelte 5 have no modifiers - you write all the logic in the handler function, in one place:

<script>
  let log = $state([]);

  function handleSubmit(event) {
    event.preventDefault(); // instead of |preventDefault
    log.push('Order sent');
  }

  function handleShield(event) {
    event.stopPropagation(); // instead of |stopPropagation
    log.push('The shield stopped the blow');
  }

  function handleBoard(event) {
    if (event.target !== event.currentTarget) return; // instead of |self
    log.push('Deck clicked');
  }

  // instead of |once - a function that calls the handler only once
  function once(fn) {
    return function (event) {
      if (fn) fn.call(this, event);
      fn = null;
    };
  }
</script>

<form onsubmit={handleSubmit}>
  <button type="submit">Send order</button>
</form>

<button onclick={once(() => log.push('The horn sounded'))}>Only once!</button>

<!-- capture: add "capture" at the end of the event name -->
<div onclickcapture={() => log.push('Capture phase')}>
  <button onclick={handleBoard}>Deck</button>
  <button onclick={handleShield}>Shield</button>
</div>

<ul>
  {#each log as entry}
    <li>{entry}</li>
  {/each}
</ul>

Cheat sheet - the older syntax (Svelte 4) and its Svelte 5 equivalent:

  • on:click={fn} β†’ onclick={fn}
  • the preventDefault modifier β†’ event.preventDefault() in the function
  • the stopPropagation modifier β†’ event.stopPropagation() in the function
  • the once modifier β†’ a wrapper function, e.g. once(fn)
  • the self modifier β†’ if (event.target === event.currentTarget)
  • the capture modifier β†’ onclickcapture={fn}

You will still see the on: directive in older code - in Svelte 5 it is deprecated, and you must not mix it with event attributes in one component.

Example: Interactive Warrior

<script>
  let health = $state(100);
  let energy = $state(100);
  let log = $state([]);

  function attack() {
    if (energy >= 20) {
      energy -= 20;
      log.push('Attack! -20 energy');
    }
  }

  function defend() {
    if (energy >= 10) {
      energy -= 10;
      health = Math.min(100, health + 5);
      log.push('Defend! +5 health');
    }
  }

  function rest() {
    energy = Math.min(100, energy + 30);
    log.push('Rest! +30 energy');
  }
</script>

<div class="warrior-panel">
  <h2>Warrior Panel</h2>

  <div class="stats">
    <div class="stat">
      <span>Health:</span>
      <progress value={health} max="100"></progress>
      <span>{health}/100</span>
    </div>
    <div class="stat">
      <span>Energy:</span>
      <progress value={energy} max="100"></progress>
      <span>{energy}/100</span>
    </div>
  </div>

  <div class="actions">
    <button onclick={attack} disabled={energy < 20}>Attack (20 energy)</button>
    <button onclick={defend} disabled={energy < 10}>Defend (10 energy)</button>
    <button onclick={rest}>Rest</button>
  </div>

  <div class="log">
    <h3>Log:</h3>
    {#each log.slice(-5) as entry}
      <p>{entry}</p>
    {/each}
  </div>
</div>

These are the basics of events in Svelte. Simple, right? Like a well-sharpened axe!

Code for this lesson: App.svelte
<script>
  // Exercise: Event handling with event attributes (onclick, onkeydown)

  let health = $state(100);
  let energy = $state(100);
  let log = $state([]);
  let warriorName = 'Ragnar';

  function attack() {
    if (energy >= 20) {
      energy -= 20;
      addLog('Attack! -20 energy');
    }
  }

  function defend() {
    if (energy >= 10) {
      energy -= 10;
      health = Math.min(100, health + 10);
      addLog('Defend! +10 health');
    }
  }

  function rest() {
    energy = Math.min(100, energy + 30);
    addLog('Rest! +30 energy');
  }

  function handleKeydown(event) {
    if (event.key === 'a') attack();
    if (event.key === 'd') defend();
    if (event.key === 'r') rest();
  }

  function addLog(message) {
    log = [...log.slice(-4), message];
  }
</script>

<svelte:window onkeydown={handleKeydown} />

<main class="battle-panel">
  <h1>Battle Panel: {warriorName}</h1>

  <div class="bars">
    <div class="bar">
      <span class="bar-label">Health</span>
      <div class="bar-track">
        <div class="bar-fill health" style="width: {health}%"></div>
      </div>
      <span>{health}/100</span>
    </div>

    <div class="bar">
      <span class="bar-label">Energy</span>
      <div class="bar-track">
        <div class="bar-fill energy" style="width: {energy}%"></div>
      </div>
      <span>{energy}/100</span>
    </div>
  </div>

  <div class="actions">
    <button
      onclick={attack}
      disabled={energy < 20}
      class="attack"
    >
      Attack (A) - 20 energy
    </button>

    <button
      onclick={defend}
      disabled={energy < 10}
      class="defend"
    >
      Defend (D) - 10 energy
    </button>

    <button
      onclick={rest}
      class="rest"
    >
      Rest (R)
    </button>
  </div>

  <div class="log">
    <h3>Log:</h3>
    {#each log as entry}
      <p>{entry}</p>
    {:else}
      <p class="empty">No actions...</p>
    {/each}
  </div>

  <p class="hint">Use keys A, D, R to control!</p>
</main>

<style>
  .battle-panel {
    font-family: 'Georgia', serif;
    max-width: 500px;
    margin: 0 auto;
    padding: 2rem;
    background: linear-gradient(135deg, #1a0f0a 0%, #2c1810 100%);
    color: #e8d5b7;
    min-height: 100vh;
  }

  h1 {
    color: #d4af37;
    text-align: center;
    margin-bottom: 2rem;
  }

  .bars {
    margin-bottom: 2rem;
  }

  .bar {
    margin-bottom: 1rem;
  }

  .bar .bar-label {
    display: block;
    margin-bottom: 0.25rem;
    font-size: 1rem;
    color: inherit;
  }

  .bar-track {
    height: 24px;
    background: rgba(0,0,0,0.5);
    border-radius: 4px;
    overflow: hidden;
    border: 1px solid #3d2914;
  }

  .bar-fill {
    height: 100%;
    transition: width 0.3s;
  }

  .bar-fill.health {
    background: linear-gradient(90deg, #8b0000, #ff4444);
  }

  .bar-fill.energy {
    background: linear-gradient(90deg, #1e3a5f, #4a90d9);
  }

  .bar span {
    font-size: 0.8rem;
    color: #8b7355;
  }

  .actions {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    margin-bottom: 2rem;
  }

  button {
    padding: 1rem;
    font-size: 1rem;
    border: 2px solid #d4af37;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;
    color: white;
  }

  button.attack { background: #8b0000; }
  button.defend { background: #1e3a5f; }
  button.rest { background: #2d5016; }

  button:hover:not(:disabled) {
    transform: scale(1.02);
    filter: brightness(1.2);
  }

  button:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .log {
    background: rgba(0,0,0,0.3);
    border: 1px solid #3d2914;
    border-radius: 4px;
    padding: 1rem;
  }

  .log h3 {
    color: #d4af37;
    margin: 0 0 0.5rem 0;
  }

  .log p {
    margin: 0.25rem 0;
    padding: 0.25rem 0.5rem;
    background: rgba(212, 175, 55, 0.1);
    border-radius: 2px;
  }

  .log .empty {
    color: #8b7355;
    font-style: italic;
  }

  .hint {
    text-align: center;
    margin-top: 1rem;
    color: #8b7355;
    font-size: 0.9rem;
  }
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How do we listen for a button click in Svelte 5?

  2. 2. How do you prevent the browser's default action in Svelte 5, e.g. a page reload after a form is submitted?

  3. 3. How do you stop both the default action and the propagation of an event in Svelte 5?

Hands-on tasks in the game

  • Code editor

    Complete the code so that clicking the button shows an alert saying 'SKΓ…L!'

  • Click in order

    Click the Svelte 5 replacements for the old modifiers in order: preventing the default action, stopping propagation, listening in the capture phase

Useful articles