Named actions let you add reusable behavior to HTML elements in Svelte. They help keep your code clean and easy to understand.
Named actions in Svelte
function actionName(node, parameters) { // setup code here return { update(newParameters) { // handle parameter changes }, destroy() { // cleanup code here } }; } <!-- Use in markup --> <div use:actionName={parameters}></div>
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.
function focus(node) { node.focus(); return { destroy() { // no cleanup needed here } }; } <!-- Usage --> <input use:focus>
function highlight(node, color = 'yellow') { node.style.backgroundColor = color; return { update(newColor) { node.style.backgroundColor = newColor; }, destroy() { node.style.backgroundColor = ''; } }; } <!-- Usage --> <p use:highlight={'lightblue'}>Text with highlight</p>
This named action adds a tooltip that appears when you hover over the button. It cleans up the tooltip when the mouse leaves or the element is removed.
<script> function tooltip(node, text) { let div; function mouseOver() { div = document.createElement('div'); div.textContent = text; div.style.position = 'absolute'; div.style.background = 'black'; div.style.color = 'white'; div.style.padding = '0.25rem 0.5rem'; div.style.borderRadius = '0.25rem'; div.style.top = `${node.getBoundingClientRect().bottom + window.scrollY + 5}px`; div.style.left = `${node.getBoundingClientRect().left + window.scrollX}px`; document.body.appendChild(div); } function mouseOut() { if (div) { div.remove(); div = null; } } node.addEventListener('mouseover', mouseOver); node.addEventListener('mouseout', mouseOut); return { update(newText) { text = newText; }, destroy() { node.removeEventListener('mouseover', mouseOver); node.removeEventListener('mouseout', mouseOut); if (div) div.remove(); } }; } </script> <button use:tooltip={'Click me to do something'}>Hover me</button>
Always clean up event listeners or DOM changes in the destroy method to avoid memory leaks.
You can update the action's behavior by using the update method when parameters change.
Named actions help keep your components tidy by moving behavior outside the markup.
Named actions add reusable behavior to HTML elements in Svelte.
They receive the element and optional parameters, and can clean up after themselves.
Use them to keep your code organized and avoid repeating logic.