How to Use Event Modifiers in Svelte: Syntax and Examples
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 actionstopPropagation: stops the event from bubbling uponce: runs the handler only oncecapture: uses event capturing instead of bubblingpassive: hints that the event listener will not callpreventDefault()
<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.
<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>
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.
<!-- Wrong way -->
<button on:click.preventDefault={handleClick}>Wrong</button>
<!-- Right way -->
<button on:click|preventDefault={handleClick}>Right</button>Quick Reference
| Modifier | Effect |
|---|---|
| preventDefault | Prevents the default browser action |
| stopPropagation | Stops event bubbling to parent elements |
| once | Runs the event handler only once |
| capture | Uses event capturing phase instead of bubbling |
| passive | Indicates handler will not call preventDefault |