How to Use Event Listeners in Svelte

How to Use Event Listeners in Svelte

Ferenc Almasi β€’ Last updated 2020 September 12 β€’ Read time 1 min read
  • twitter
  • facebook

You can use the on:<eventName> directive in Svelte to listen to DOM events:

Copied to clipboard!
<script>
    let answer;

    function handleClick(event) {
        answer = Math.random() * 100;
    }
</script>

<button on:click={getTheAnswer}>
    What is the answer❔ {answer}
</button>
EventListener.svelte

You can also fire events only once, by adding modifiers with a pipe:

Copied to clipboard!
<!-- This will fire once, then the event listener will be removed -->
<button on:click|once="{() => answer = Math.random()}">
    What is the answer❔ {answer}
</button>
EventListener.svelte

Apart from once, you can also specify the following modifiers:

  • preventDefault
  • stopPropagation
  • passive - this is tend to improve scrolling performance for scroll events
  • capture - use event capturing instead of event bubbling
  • self - only trigger the event if the target is the element itself.

You may also notice that I've declared an inline function. Unlike in React, you don't have to worry about performance if you define an inline handler.

You can also have the same event listener attached multiple times to an element:

Copied to clipboard!
<button on:click={getTheAnswer} on:click={trackingClickEvent}>
    What is the answer❔ {answer}
</button>
EventListener.svelte
Event Listeners in Svelte
If you would like to see more Webtips, follow @flowforfrank

Looking into Svelte 3

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.