0
0
SvelteConceptBeginner · 3 min read

What is Action in Svelte: Simple Explanation and Example

In Svelte, an action is a function that lets you add custom behavior directly to HTML elements when they are created. It is used to interact with the DOM, like adding event listeners or animations, by attaching the function to an element with the use: directive.
⚙️

How It Works

Think of an action in Svelte like giving a special instruction to an HTML element when it appears on the page. This instruction is a function that runs with the element as its input, allowing you to add extra behavior or effects.

For example, if you want to automatically focus an input box when it shows up, you can write an action that tells the input to focus itself. The action runs once when the element is created, and it can also clean up when the element is removed.

This is similar to giving a helper a note attached to a specific item, so the helper knows exactly what to do with that item without changing the rest of the page.

💻

Example

This example shows an action that automatically focuses an input box when it appears on the page.

svelte
<script>
  // Define the action function
  function autofocus(node) {
    node.focus();
    return {
      destroy() {
        // Cleanup if needed when element is removed
      }
    };
  }
</script>

<input use:autofocus placeholder="I am focused on load" />
Output
An input box with the placeholder text 'I am focused on load' is shown and automatically focused when the page loads.
🎯

When to Use

Use actions when you want to add custom behavior to elements that involves direct interaction with the DOM. This includes things like:

  • Setting focus on inputs
  • Adding event listeners that are not covered by Svelte's built-in events
  • Integrating third-party libraries that need DOM access
  • Adding animations or drag-and-drop functionality

Actions are perfect when you want reusable, clean ways to enhance elements without cluttering your component logic.

Key Points

  • An action is a function that runs when an element is created.
  • Attach actions using the use: directive on elements.
  • Actions can return an object with a destroy method to clean up.
  • They help keep DOM-related code organized and reusable.

Key Takeaways

An action is a function that adds custom behavior to an element when it is created.
Use the use: directive to attach an action to an HTML element in Svelte.
Actions can manage setup and cleanup of DOM interactions cleanly.
They are useful for focus control, event listeners, animations, and third-party integrations.
Actions keep your component code simple by isolating DOM logic.