Introduction
Default actions let you add behavior to HTML elements easily in Svelte. They help you run code when elements are created or removed.
Default actions let you add behavior to HTML elements easily in Svelte. They help you run code when elements are created or removed.
function actionName(node) { // code to run when element is created return { destroy() { // code to run when element is removed } }; } <!-- Use in markup --> <div use:actionName></div>
node parameter is the HTML element the action is applied to.destroy function cleans up when the element is removed.function focus(node) { node.focus(); return { destroy() { // no cleanup needed here } }; } <input use:focus>
function logClick(node) { const handleClick = () => console.log('Clicked!'); node.addEventListener('click', handleClick); return { destroy() { node.removeEventListener('click', handleClick); } }; } <button use:logClick>Click me</button>
This example uses a default action to highlight a paragraph by changing its background color. When the paragraph is removed, the highlight is cleared.
<script> function highlight(node) { node.style.backgroundColor = 'yellow'; return { destroy() { node.style.backgroundColor = ''; } }; } </script> <p use:highlight>This text is highlighted when shown.</p>
Actions run when the element is added to the page.
Always clean up in destroy to avoid memory leaks.
You can pass parameters to actions for more control.
Default actions add behavior to elements easily.
They run code on element creation and cleanup on removal.
Use them to focus, add events, or modify elements simply.
focus to an input element in Svelte?use:actionName on elements.<input use:focus /> uses use:focus, which is the correct way to apply the action.use: prefix to apply default actions [OK]action: or on: instead of use:function highlight(node) {
node.style.backgroundColor = 'yellow';
return {
destroy() {
node.style.backgroundColor = '';
}
};
}
<div use:highlight>Hello</div>backgroundColor to 'yellow' on the node when applied.use:highlight, so its background color becomes yellow on render.function logClick(node) {
node.addEventListener('click', () => console.log('Clicked!'));
}destroy method to remove listeners and avoid memory leaks.autoFocus that focuses an input element when it appears and logs "Focused" once. Which code correctly implements this behavior?node.focus() and logging immediately runs once when the element appears.destroy method is valid and ensures cleanup structure.Pass the test and this pattern moves unknown