Skip to content

Svelte Actions Explained — Reusable DOM Behavior

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Svelte Actions Explained. We cover key concepts, practical examples, and best practices to help you master this topic.

Svelte actions are functions called when an element is created, providing direct DOM access for reusable behaviors like event listeners, third-party library integration, and DOM manipulation.

What You'll Learn

  • use: directive basics
  • Creating action functions
  • Action parameters and updates
  • Lifecycle hooks (mount, update, destroy)
  • Common action patterns

Why It Matters

Actions encapsulate DOM manipulation that would otherwise be scattered across lifecycle functions. They are the Svelte equivalent of Vue directives or React refs with useEffect.

<script>
  function clickOutside(node, callback) {
    function handleClick(event) {
      if (!node.contains(event.target)) {
        callback();
      }
    }
    document.addEventListener("click", handleClick, true);
    return {
      destroy() {
        document.removeEventListener("click", handleClick, true);
      }
    };
  }

  function tooltip(node, text) {
    const tip = document.createElement("div");
    tip.className = "tooltip";
    tip.textContent = text;
    document.body.appendChild(tip);

    function show() {
      const rect = node.getBoundingClientRect();
      tip.style.top = `${rect.top - tip.offsetHeight - 5}px`;
      tip.style.left = `${rect.left + rect.width / 2 - tip.offsetWidth / 2}px`;
      tip.style.display = "block";
    }

    function hide() { tip.style.display = "none"; }

    node.addEventListener("mouseenter", show);
    node.addEventListener("mouseleave", hide);

    return {
      update(newText) { tip.textContent = newText; },
      destroy() {
        node.removeEventListener("mouseenter", show);
        node.removeEventListener("mouseleave", hide);
        tip.remove();
      }
    };
  }

  let dropdownOpen = false;
</script>

<div use:clickOutside={() => dropdownOpen = false}>
  <button on:click={() => dropdownOpen = !dropdownOpen}>
    Toggle Dropdown
  </button>
  {#if dropdownOpen}
    <div class="dropdown">Dropdown content</div>
  {/if}
</div>

<button use:tooltip={"Save your changes"}>Save</button>

Expected output: Clicking outside the dropdown closes it. Hovering the Save button reveals a positioned tooltip.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro