Action parameters let you send extra information to a Svelte action. This helps customize how the action works on an element.
Action parameters in Svelte
use:actionName={parameter}The parameter can be any JavaScript value: string, number, object, etc.
Svelte calls the action's update function automatically when the parameter changes.
<div use:highlight={true}></div><button use:tooltip={{ text: 'Click me', position: 'top' }}></button><input use:focusOnMount={true}>This example shows an action called highlight that colors the background of an element. You pass a color as a parameter. When the color changes, the action updates the background color automatically.
Click the button to toggle the color between light blue and light green on the second paragraph.
<script> let color = 'lightblue'; // A simple action that changes background color based on parameter export function highlight(node, color) { node.style.backgroundColor = color || 'yellow'; return { update(newColor) { node.style.backgroundColor = newColor || 'yellow'; }, destroy() { node.style.backgroundColor = null; } }; } </script> <p use:highlight={'lightblue'}>This paragraph has a light blue background.</p> <button on:click={() => color = color === 'lightblue' ? 'lightgreen' : 'lightblue'}> Toggle Color </button> <p use:highlight={color}>This paragraph changes color when you click the button.</p>
Always return an update function from your action if you expect the parameter to change.
Remember to clean up in the destroy function to avoid side effects.
Action parameters let you customize Svelte actions with extra data.
Use use:action={parameter} syntax to pass parameters.
Actions can react to parameter changes with an update method.