Actions

Back

Loading concept...

๐ŸŽญ Svelte Actions: Teaching Your Elements New Tricks!

The Magic Wand Analogy ๐Ÿช„

Imagine you have a magic wand. When you wave it at a toy, the toy suddenly learns a new trick! It can glow, wiggle, or do something special whenever you touch it.

Svelte Actions are like magic wands for your HTML elements. You point an action at an element, and suddenly that element knows how to do something newโ€”like detecting clicks outside it, adding tooltips, or tracking when it appears on screen!


๐ŸŽฏ What Are Actions?

Actions are functions that run when an element is created. They can:

  • Set up event listeners
  • Modify the elementโ€™s behavior
  • Clean up when the element is removed

Think of it like giving a sticker to your element. The sticker tells it: โ€œHey, you can do THIS cool thing now!โ€


๐Ÿ“š Action Basics

The Simplest Action

An action is just a function that receives an element:

function myAction(node) {
  // node is the HTML element
  console.log("Element created!");

  return {
    destroy() {
      console.log("Element removed!");
    }
  };
}

Using It in Svelte

<script>
  function highlight(node) {
    node.style.background = 'yellow';
  }
</script>

<div use:highlight>
  I'm highlighted!
</div>

What happens:

  1. Svelte creates the <div>
  2. The highlight function runs
  3. The div gets a yellow background!
graph TD A["Element Created"] --> B["Action Runs"] B --> C["Element Gets Superpowers!"] C --> D["Element Removed?"] D --> E["Cleanup Runs"]

๐ŸŽ Action Parameters

Sometimes your magic wand needs instructions. โ€œMake it glowโ€ฆ but in BLUE!โ€

Passing Data to Actions

function colorize(node, color) {
  node.style.color = color;

  return {
    update(newColor) {
      node.style.color = newColor;
    }
  };
}

Using Parameters

<script>
  let myColor = 'red';

  function colorize(node, color) {
    node.style.color = color;
    return {
      update(newColor) {
        node.style.color = newColor;
      }
    };
  }
</script>

<p use:colorize={myColor}>
  I change colors!
</p>

<button on:click={() => myColor = 'blue'}>
  Make Blue
</button>

What happens:

  1. Text starts as red
  2. Click button โ†’ parameter changes to โ€˜blueโ€™
  3. update() runs โ†’ text turns blue!

Object Parameters

Need multiple settings? Pass an object:

function tooltip(node, { text, position }) {
  // text = "Hello!"
  // position = "top"
}
<button use:tooltip={{ text: "Click me!", position: "top" }}>
  Hover here
</button>

๐Ÿ”„ Action Lifecycle

Every action has a life story with three chapters:

1. ๐Ÿฃ Birth (Function Runs)

When the element appears, your action function runs ONCE.

function trackElement(node) {
  console.log("I'm born!");
  // Setup code here
}

2. ๐Ÿ”„ Update (Parameters Change)

When you pass new parameters, the update function runs.

function trackElement(node, params) {
  console.log("Born with:", params);

  return {
    update(newParams) {
      console.log("Updated to:", newParams);
    }
  };
}

3. ๐Ÿ’€ Destroy (Element Removed)

When the element disappears, destroy runs. Always clean up!

function trackClicks(node) {
  function handleClick() {
    console.log("Clicked!");
  }

  node.addEventListener('click', handleClick);

  return {
    destroy() {
      // IMPORTANT: Remove listener!
      node.removeEventListener('click', handleClick);
    }
  };
}
graph TD A["๐Ÿฃ Element Created"] --> B["Action Function Runs"] B --> C{Parameters Changed?} C -->|Yes| D["๐Ÿ”„ update Runs"] D --> C C -->|Element Removed| E["๐Ÿ’€ destroy Runs"] E --> F["Cleanup Complete!"]

๐ŸŽฎ The use: Directive

The use: directive is how you attach actions to elements.

Basic Syntax

<div use:actionName>

With Parameters

<div use:actionName={parameter}>

Multiple Actions

One element can have MANY magic wands!

<div
  use:tooltip="Click me"
  use:clickOutside={handleClose}
  use:animate
>
  I have 3 superpowers!
</div>

๐ŸŒŸ Real-World Example: Click Outside

A super common pattern! Close a menu when clicking outside it.

<script>
  let showMenu = false;

  function clickOutside(node, callback) {
    function handleClick(event) {
      if (!node.contains(event.target)) {
        callback();
      }
    }

    document.addEventListener('click', handleClick);

    return {
      destroy() {
        document.removeEventListener('click', handleClick);
      }
    };
  }
</script>

{#if showMenu}
  <div
    class="menu"
    use:clickOutside={() => showMenu = false}
  >
    <p>Menu Content</p>
  </div>
{/if}

<button on:click={() => showMenu = true}>
  Open Menu
</button>

The magic:

  1. Menu appears
  2. Action listens for ALL clicks
  3. Click outside? Callback fires! Menu closes.
  4. Menu removed? Listener cleaned up!

๐ŸŽจ Another Example: Auto-Focus

Make an input automatically focus when it appears:

<script>
  function autofocus(node) {
    node.focus();
  }
</script>

<input use:autofocus placeholder="I'm focused!" />

Thatโ€™s it! One line of action magic.


๐Ÿง  Key Takeaways

Concept What It Does
Action Function that adds behavior to elements
Parameters Data passed to customize the action
update() Runs when parameters change
destroy() Cleanup when element is removed
use: Directive to attach actions

๐Ÿš€ Quick Pattern Reference

function myAction(node, params) {
  // 1. SETUP: Runs once when element appears

  return {
    // 2. UPDATE: Runs when params change
    update(newParams) {
      // React to new parameters
    },

    // 3. DESTROY: Runs when element removed
    destroy() {
      // Clean up listeners, timers, etc.
    }
  };
}

๐ŸŽ‰ You Did It!

You now understand Svelte Actions! Theyโ€™re like giving superpowers to your HTML elements. Remember:

  • Actions = Functions that enhance elements
  • Parameters = Instructions for how to enhance
  • Lifecycle = Birth โ†’ Updates โ†’ Cleanup
  • use: = The magic word to attach actions

Now go teach your elements some new tricks! ๐Ÿช„โœจ

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.