Actions let you add extra behavior to HTML elements that you can use again and again. They keep your code clean and easy to manage.
0
0
Why actions add reusable element behavior in Svelte
Introduction
When you want to add the same interactive feature to many buttons or inputs.
When you need to handle events or animations on elements without repeating code.
When you want to keep your component code simple by moving element-specific logic outside.
When you want to share element behavior across different components.
When you want to clean up event listeners or effects automatically when elements are removed.
Syntax
Svelte
function myAction(node, parameters) { // setup code here return { update(newParameters) { // handle parameter changes }, destroy() { // cleanup code here } }; }
The node is the HTML element the action is applied to.
The function can return an object with update and destroy to handle changes and cleanup.
Examples
This action focuses the element when it is created.
Svelte
function focus(node) {
node.focus();
}This action changes the background color and updates it if the color changes.
Svelte
function highlight(node, color) { node.style.backgroundColor = color; return { update(newColor) { node.style.backgroundColor = newColor; }, destroy() { node.style.backgroundColor = ''; } }; }
Sample Program
This example shows a tooltip action that adds a small popup text when you hover over the button. The action handles showing and hiding the tooltip and cleans up event listeners when the button is removed.
Svelte
<script> function tooltip(node, text) { let tooltipDiv; function mouseOver() { tooltipDiv = document.createElement('div'); tooltipDiv.textContent = text; tooltipDiv.style.position = 'absolute'; tooltipDiv.style.background = 'black'; tooltipDiv.style.color = 'white'; tooltipDiv.style.padding = '0.25rem 0.5rem'; tooltipDiv.style.borderRadius = '0.25rem'; tooltipDiv.style.top = `${node.getBoundingClientRect().bottom + 5}px`; tooltipDiv.style.left = `${node.getBoundingClientRect().left}px`; document.body.appendChild(tooltipDiv); } function mouseOut() { if (tooltipDiv) { tooltipDiv.remove(); tooltipDiv = null; } } node.addEventListener('mouseover', mouseOver); node.addEventListener('mouseout', mouseOut); return { update(newText) { text = newText; }, destroy() { node.removeEventListener('mouseover', mouseOver); node.removeEventListener('mouseout', mouseOut); if (tooltipDiv) tooltipDiv.remove(); } }; } </script> <button use:tooltip="Click me!">Hover me</button>
OutputSuccess
Important Notes
Actions help keep your components simple by moving element-specific code outside.
Always clean up event listeners or timers in the destroy method to avoid memory leaks.
You can pass parameters to actions and update them dynamically.
Summary
Actions add reusable behavior directly to HTML elements.
They help share and organize code for element interactions.
Actions can set up, update, and clean up behavior easily.