Skip to main content
Actions are functions that are called when an element is created. They provide a way to add custom behavior to DOM elements, such as tooltips, click-outside detection, or custom event handlers.

Action Interface

Element
HTMLElement
default:"HTMLElement"
The type of element this action works on (e.g., HTMLDivElement, HTMLButtonElement)
Parameter
any
default:"undefined"
The type of parameter the action accepts. Use undefined if the action takes no parameters
Attributes
Record<string, any>
default:"Record<never, any>"
Additional attributes and events the action enables on the element (TypeScript only)

ActionReturn Interface

update
(parameter: Parameter) => void
Called whenever the action’s parameter changes, immediately after Svelte applies markup updates
destroy
() => void
Called when the element is unmounted from the DOM

Usage

Basic Action

Create a simple action that runs when an element is added to the DOM:

Action with Parameters

Pass parameters to customize the action’s behavior:

Action with Update

Handle parameter changes with the update method:

TypeScript Example

Type your actions for better IDE support:

Adding Type-Safe Attributes

Define custom attributes and events that the action enables:
Usage:

Common Patterns

Click Outside

Focus Trap

Notes

  • Actions are called when the element is created
  • The destroy method is called when the element is removed from the DOM
  • The update method is called whenever the parameter changes
  • Multiple actions can be used on the same element
  • Actions run after the element is added to the DOM
  • Actions are useful for integrating third-party libraries
  • The Attributes generic is TypeScript-only and has no runtime effect

See Also