Listening to DOM events in Svelte

In Svelte you can define a listener for a DOM event directly in the template, using the on:<event> syntax.

For example, to listen to the click event, you will pass a function to the on:click attribute.

To listen to the onmousemove event, you’ll pass a function to the on:mousemove attribute.

Here’s an example with the handling function defined inline:

<button on:click={() => {
  alert('clicked')
}}>Click me</button>

and here’s another example with the handling function defined in the script section of the component:

<script>
const doSomething = () => {
  alert('clicked')
}
</script>

<button on:click={doSomething}>Click me</button>

I prefer inline when the code is not too verbose. If it’s just 2-3 lines, for example – otherwise I’d move that up in the script section.

Svelte passes the event handler as the argument of the function, which is handy if you need to stop propagation or to reference something in the Event object:

<script>
const doSomething = event => {
  console.log(event)
  alert('clicked')
}
</script>

<button on:click={doSomething}>Click me</button>

Now, I mentioned “stop propagation”. That’s a very common thing to do, to stop form submit events for example. Svelte provides us modifiers, a way to apply it directly without manually doing it.
stopPropagation and preventDefault are the 2 modifiers you’ll use the most, I think.

You apply a modifier like this: <button on:click|stopPropagation|preventDefault={doSomething}>Click me</button>

There are other modifiers, which are more niche. capture enables capturing events instead of bubbling, once only fires the event once, self only fires the event if the target of the event is this object .

Leave a comment

Your email address will not be published. Required fields are marked *