Svelte.js Event modifiers tutorial

by Sai gowtham1min read
Svelte.js Event modifiers tutorial

In this tutorial, we are going to learn about event modifiers in svelte by using examples.

Event Modifiers

In svelte.js event modifiers helps us to modify the default behavior of the dom events.

once modifier

The once modifier helps us to trigger the event only one time.


   function handleClick(){
       alert('You can see me once')


<button on:click|once={handlerClick}>Click me</button>

In the above code, we have added once modifer to on:click event so that we can only fire the click event once.


The preventDefault modifier helps us to solve the default loading behavior of the browser whenever we submit a form.


  function handleSubmit() {

<form on:submit|preventDefault={handleSubmit}>  <input type="text" placeholder="Name" />

stopPropagation modifier

stopPropagation modifier helps us to stop reaching the event to the next element.


  div {
    padding: 1rem;
    border: 1px solid;

<div on:click={() => console.log('Outer div')}>
  <h1>Outer div</h1>
  <div on:click|stopPropagation={() => console.log('inner div')}>
    <h1>Inner div</h1>

In the above code, if we click on an Inner div it only fires the event on it instead of propagating it to Outer div

capture Modifier

It helps us to fire the event in capture phase instead of the bubbling phase.