๐ญ 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:
- Svelte creates the
<div> - The
highlightfunction runs - 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:
- Text starts as red
- Click button โ parameter changes to โblueโ
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:
- Menu appears
- Action listens for ALL clicks
- Click outside? Callback fires! Menu closes.
- 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! ๐ชโจ
