by Sai gowtham

Svelte.js Event modifiers tutorial

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, we have event modifiers which helps us to modify the default behavior of dom events.

once modifier

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

example:

Modifiers.svelte
<script>
   function handleClick(){
       alert('You can see me once')
   }

</script>

<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.

preventDefault

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

example:

Form.svelte
<script>
  function handleSubmit() {
    console.log("success");
  }
</script>

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

stopPropagation modifier

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

example:

Event.svelte
<style>
  div {
    padding: 1rem;
    border: 1px solid;
  }
</style>

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

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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course