by Sai gowtham

How to handle the events in Svelte

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.

How to pass arguments to the event handler function?

In some cases, we need to pass an argument to an event handler function let’s see an example.

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

<div>
   <h1>{count}</h1>
   //incrementing the count value by 2.   <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)
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