How to Use Event Listeners in Svelte
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>
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>
Apart from once
, you can also specify the following modifiers:
preventDefault
stopPropagation
passive
- this is tend to improve scrolling performance for scroll eventscapture
- use event capturing instead of event bubblingself
- 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>
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews