0
0
SvelteHow-ToBeginner · 3 min read

How to Use Event Modifiers in Svelte: Syntax and Examples

In Svelte, you use event modifiers by adding a pipe and the modifier name after the event name in your event handler, like on:click|preventDefault. These modifiers let you control event behavior such as stopping propagation or preventing default actions without writing extra code.
📐

Syntax

Event modifiers in Svelte are added by appending a pipe | and the modifier name directly after the event name in the event handler. For example, on:click|stopPropagation means the click event will not bubble up to parent elements.

Common modifiers include:

  • preventDefault: stops the default browser action
  • stopPropagation: stops the event from bubbling up
  • once: runs the handler only once
  • capture: uses event capturing instead of bubbling
  • passive: hints that the event listener will not call preventDefault()
svelte
<button on:click|preventDefault|stopPropagation={handleClick}>Click me</button>
💻

Example

This example shows a button that prevents the default action and stops the click event from bubbling up. It also uses once so the handler runs only the first time the button is clicked.

svelte
<script>
  let count = 0;
  function handleClick() {
    count += 1;
  }
</script>

<button on:click|preventDefault|stopPropagation|once={handleClick}>
  Click me
</button>
<p>Clicked {count} {count === 1 ? 'time' : 'times'}</p>
Output
Button labeled 'Click me' and text 'Clicked 0 times' initially; clicking the button increments count once and updates text to 'Clicked 1 time', further clicks do nothing.
⚠️

Common Pitfalls

Beginners often forget that event modifiers must be added directly after the event name with a pipe |. Writing them incorrectly like on:click.preventDefault will not work.

Also, chaining multiple modifiers is allowed but order matters for readability. Using preventDefault without understanding the default action can cause unexpected behavior.

svelte
<!-- Wrong way -->
<button on:click.preventDefault={handleClick}>Wrong</button>

<!-- Right way -->
<button on:click|preventDefault={handleClick}>Right</button>
📊

Quick Reference

ModifierEffect
preventDefaultPrevents the default browser action
stopPropagationStops event bubbling to parent elements
onceRuns the event handler only once
captureUses event capturing phase instead of bubbling
passiveIndicates handler will not call preventDefault

Key Takeaways

Use event modifiers by adding a pipe and modifier name after the event, like on:click|preventDefault.
Modifiers simplify event control without extra code for stopping propagation or preventing defaults.
Common modifiers include preventDefault, stopPropagation, once, capture, and passive.
Always use the correct syntax with pipes; incorrect syntax will not work.
Chaining multiple modifiers is allowed and helps combine behaviors cleanly.