Working with events in Svelte
Learn how to work with events in Svelte
Listening to DOM events
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 can pass a function to the on:click
attribute. Similarly, for the onmousemove
event, you can pass a function to the on:mousemove
attribute. Here are some examples:
1 | <button on:click={() => { |
1 | <script> |
It is generally better to define the handling function inline when the code is not too verbose, typically 2-3 lines. Otherwise, it’s recommended to define the function in the script section.
Svelte passes the event handler as an argument to the function, which is helpful if you need to stop propagation or reference the Event object. Here’s an example:
1 | <script> |
Svelte provides modifiers to apply common actions like stopping propagation or preventing the default behavior. The stopPropagation
and preventDefault
modifiers are typically used. You can apply a modifier like this:
1 | <button on:click|stopPropagation|preventDefault={doSomething}>Click me</button> |
There are also other modifiers like capture
for capturing events instead of bubbling and once
for firing the event only once. self
fires the event only if the target of the event is the object itself, excluding the bubbling/capturing hierarchy.
Creating your events in components
In Svelte, you can create custom events in components using the same syntax as built-in DOM events. To do this, you need to import the createEventDispatcher
function from the svelte
package and call it to get an event dispatcher:
1 | <script> |
Once you have the event dispatcher, you can call the dispatch()
function and pass a string that identifies the event. This string will be used for the on:
syntax in other components that use this event:
1 | <script> |
Other components can use your component and listen to the custom event:
1 | <ComponentName on:eventName={event => { |
You can also pass an object to the event by passing a second parameter to dispatch()
:
1 | <script> |
The object passed to dispatch()
will be available on the event
object as event.detail
.
tags: [“Svelte”, “DOM events”, “event listeners”, “createEventDispatcher”, “custom events”]