Use DOM events and event modifiers in Svelte 3

Tomasz Łakomy
InstructorTomasz Łakomy

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

The whole magic of webapps is that users can interact with our code via various DOM events and Svelte is no exception in that regard.

In this quick lesson we're going to learn how to use DOM events in Svelte 3 as well as how to use event modifiers to alter DOM event behaviour (such as once and preventDefault)

Instructor: [0:00] We would like to build a simple app that whenever I type a name in this input field, after I click the button, I am going to see an alert saying Hello Name.

[0:08] In order to do that, attach input handlers to both input and the button. What we're going to do right now, I am going to do on:change, that is going to be equal to handleInput function. I am going to do something similar to the button, but I am going to use the on:click event and I am going to call on the handleClick function.

[0:24] Let me create a variable first on the name. Inside those handleInput, I am going to use the event in order to override the name value. I am going to do name equals event.target.value.

[0:35] In this handle click function, we're going to do alert("Hello " + name). Now we have the desired effect. If I type in Mike and click on the button, I am going to see an alert, Hello Mike.

[0:45] In Svelte, DOM events have modifiers that can alter their behavior. For instance, we would like to be able to only introduce ourselves once. To do that, we can pass in an once modifier to this on:click handler.

[0:57] Right now, if I type in another name, such as John and click on the button, I am going to be able to introduce myself. This can happen only once. I am no longer able to introduce myself because this event handler is going to trigger only once. We can also do other things such as preventDefault and we can also change those modifiers.

[1:15] If I did preventDefault and once, this event default behavior is going to be prevented and this event is going to be trigger only once.