Actions in Svelte let you add behavior to HTML elements easily. The update and destroy functions help manage changes and cleanup when the element or data changes.
Action update and destroy in Svelte
function myAction(node, parameters) { // setup code here return { update(newParameters) { // code to run when parameters change }, destroy() { // cleanup code here } }; }
The node is the HTML element the action is applied to.
The update function runs when the parameters passed to the action change.
function highlight(node, color) { node.style.backgroundColor = color; return { update(newColor) { node.style.backgroundColor = newColor; }, destroy() { node.style.backgroundColor = ''; } }; }
function logClicks(node) { function handleClick() { console.log('Element clicked!'); } node.addEventListener('click', handleClick); return { destroy() { node.removeEventListener('click', handleClick); } }; }
This Svelte component uses an action called colorAction to change the text color of a paragraph. When you click the button, the color toggles between blue and red. The update function changes the color when currentColor changes. The destroy function resets the color if the paragraph is removed.
<script> function colorAction(node, color) { node.style.color = color; return { update(newColor) { node.style.color = newColor; }, destroy() { node.style.color = ''; } }; } let currentColor = 'blue'; function changeColor() { currentColor = currentColor === 'blue' ? 'red' : 'blue'; } </script> <button on:click={changeColor}>Toggle Color</button> <p use:colorAction={currentColor}>This text changes color when you click the button.</p>
Always clean up in destroy to avoid memory leaks.
The update function is optional but useful when parameters change.
Actions can be reused on many elements with different parameters.
Actions add behavior to elements with setup, update, and cleanup.
update runs when parameters change.
destroy runs when the element is removed to clean up.