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

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 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 - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course