Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 35 ยท Templates and Markup

Events and Bindings

Handle DOM events with onclick-style attributes in Svelte 5 and bind form values with bind:value, bind:checked, bind:group and bind:this.

Interactivity has two directions. Users act on the page, and the page reflects data. In Svelte 5, event attributes react to actions and bindings connect form controls and DOM properties to variables. Together they replace the glue code you would write by hand.

Event handlers

An event handler is a normal attribute whose name starts with on:

SVELTE
<script>
  let count = $state(0);

  function handleClick(event) {
    count += 1;
    console.log(event.clientX, event.clientY);
  }
</script>

<button onclick={handleClick}>Clicked {count}</button>
<button onclick={() => (count = 0)}>Reset</button>

The handler gets the browser event as its first argument. Inline arrow functions are fine; Svelte does not create extra work for them.

Other events work the same: oninput, onchange, onsubmit, onkeydown, onpointermove, and so on.

preventDefault and friends

Svelte 4 had modifiers like on:submit|preventDefault. Svelte 5 removed them; call the method yourself:

SVELTE
<form onsubmit={(event) => {
  event.preventDefault();
  save();
}}>
  <button>Save</button>
</form>

You can also write a small helper that wraps a handler: const prevent = (fn) => (e) => { e.preventDefault(); fn(e); }.

Event delegation

For some events (click, input, keydown, ...) Svelte attaches one listener at the app root and handles them there, which saves memory with big lists. This is invisible, but there is one catch: if you call event.stopPropagation() on a delegated event, listeners added to the document or window yourself may not see it. Use a native addEventListener inside an effect if you need exact control.

bind:value

bind:value connects an input to a variable in both directions:

SVELTE
<script>
  let name = $state('');
  let age = $state(30);
  let bio = $state('');
</script>

<input bind:value={name} placeholder="Name" />
<input type="number" bind:value={age} />
<textarea bind:value={bio}></textarea>
<p>{name} is {age}</p>

For type="number" and type="range" the value is a number (or null when empty), not a string. Binding is nicer than writing oninput handlers yourself, but you may still need oninput if you want to react to each change with side effects. For that, use an event handler next to the binding, or an effect.

Checkboxes, radios and selects

SVELTE
<script>
  let subscribed = $state(false);
  let size = $state('M');
  let toppings = $state([]);
  let country = $state('fr');
</script>

<label><input type="checkbox" bind:checked={subscribed} /> Subscribe</label>

<label><input type="radio" bind:group={size} value="S" /> S</label>
<label><input type="radio" bind:group={size} value="M" /> M</label>
<label><input type="radio" bind:group={size} value="L" /> L</label>

<label><input type="checkbox" bind:group={toppings} value="cheese" /> Cheese</label>
<label><input type="checkbox" bind:group={toppings} value="olives" /> Olives</label>

<select bind:value={country}>
  <option value="fr">France</option>
  <option value="jp">Japan</option>
</select>
  • bind:checked is for a single checkbox.
  • bind:group with radios keeps the selected value; with checkboxes it keeps an array of the checked values.
  • bind:value on <select> gives the selected option's value; add multiple to get an array.

Other useful bindings

Binding Applies to Gives you
bind:this any element the DOM node itself
bind:clientWidth, bind:clientHeight any element (read-only) its current size
bind:innerHeight, bind:scrollY <svelte:window> window metrics
bind:currentTime, bind:paused <audio> / <video> playback state
bind:files <input type="file"> the selected FileList
SVELTE
<script>
  let box;
  let width = $state(0);
</script>

<div bind:this={box} bind:clientWidth={width}>I am {width}px wide</div>

Function bindings

When you need to transform the value on the way in or out, pass two functions to bind:: a getter and a setter.

SVELTE
<script>
  let celsius = $state(20);
  const toF = (c) => c * 9 / 5 + 32;
  const toC = (f) => (f - 32) * 5 / 9;
</script>

<input type="number"
  bind:value={() => toF(celsius), (f) => (celsius = toC(f))} />
<p>{celsius.toFixed(1)} C</p>

This is a Svelte 5 feature for cases where a plain variable is not the right shape.

Stand-in: two-way binding

A binding is two wires: model to view (render) and view to model (listener). This runnable page wires a text box, a checkbox and a group of radios by hand, which shows what bind: saves you from.

Binding by hand (stand-in page)
JS Group binding with checkboxes (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Using bind:value on a number input and expecting a string; it is a number.
  • Binding to a prop the parent did not mark $bindable (see callbacks and bindable props).
  • Expecting on:click|preventDefault; call event.preventDefault().

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you attach a click handler in Svelte 5?

    Event handlers are plain attributes starting with on. The on: directive is deprecated.
  2. 2. What does bind:group on several checkboxes produce?

    With checkboxes, bind:group collects the values of the checked ones into an array.
  3. 3. What is the type of an <input type="number" bind:value> value?

    Svelte converts numeric and range inputs to numbers.
  4. 4. How do you prevent a form's default submit in Svelte 5?

    Modifiers were removed; call the event method yourself.
  5. 5. What does bind:this give you?

    bind:this assigns the element to a variable once it exists.

Summary

  • Event handlers are on* attributes; call event.preventDefault() yourself.
  • bind:value, bind:checked, bind:group and bind:this link controls and elements to variables.
  • Number inputs bind to numbers; checkbox groups bind to arrays.
  • Function bindings (getter and setter) transform values on the way through.

Next: Component Props