by Sai gowtham

How to handle the events in Svelte

In this tutorial, we are going to learn about event handling in svelte with the help of an example.

Svelte offers us an on: directive which helps us to listen the dom events.

Counter Example

Counter.svelte
<script>
  let count = 1;
  function inc(){
      count = count+1;
  }
</script>

<div>
   <h1>{count}</h1>
   //listening click event on a button   <button on:click={inc}>Increment</button></div>

In the above code, we are listening for a click event on a button so that whenever a user clicks on a button we are invoking the inc handler method attached to it.

Passing arguments to event handler

To pass the arguments to an event handler, we need to use a arrow function which is invoking the event handler with an argument.

Counter.svelte
<script>
  let count = 1;
  function inc(num){      count = count+num;
  }
</script>

<div>
   <h1>{count}</h1>
   <button on:click={() => inc(2)} >Increment</button></div>

Inline event handlers

In svelte, we can also use inline event handlers without losing any performance in the app.

example:

<button
    on:click={() => {count = count + 1;}}>    Increment
  </button>

How to create custom events in svelte

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 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)
284,472 students enrolled
40 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)
130,921 students enrolled
21 hours of video content
View Course