Svelte logo

Svelte by Example: Actions

Actions are functions that bind to the lifecycle of a single element. They're especially useful to integrate Svelte with third-party libraries.

In this example, we'll focus an input when it's added to the page.

An action receives an HTML element when it's mounted in the browser.

Bind an action to an element with the use: directive.

AddTodo.svelte
<script>
  function focus(element) {
    element.focus();
  }
</script>

<label>
  New todo <input use:focus />
</label>

Attachments

Actions are still supported. For new code, Svelte recommends attachments, a more flexible way to work with an element's lifecycle. Attachments are available in Svelte 5.29 and newer.

An attachment also receives an element. It can return a cleanup function, which runs before the attachment reruns or the element is removed.

Attachments use {@attach}. Unlike actions, they rerun when reactive values read during setup change.

AddTodo.svelte
<script>
  function focus(element) {
    element.focus();
  }
</script>

<label>
  New todo <input {@attach focus} />
</label>