0
0
Svelteframework~5 mins

Default actions in Svelte

Choose your learning style9 modes available
Introduction

Default actions let you add behavior to HTML elements easily in Svelte. They help you run code when elements are created or removed.

You want to focus an input automatically when it appears.
You need to add a tooltip or popup to an element.
You want to listen to events or modify elements without extra code in your component.
You want to clean up event listeners or timers when an element is removed.
Syntax
Svelte
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>
The node parameter is the HTML element the action is applied to.
The destroy function cleans up when the element is removed.
Examples
This action sets focus on an input when it appears.
Svelte
function focus(node) {
  node.focus();
  return {
    destroy() {
      // no cleanup needed here
    }
  };
}

<input use:focus>
This action logs a message when the button is clicked and cleans up the listener when removed.
Svelte
function logClick(node) {
  const handleClick = () => console.log('Clicked!');
  node.addEventListener('click', handleClick);
  return {
    destroy() {
      node.removeEventListener('click', handleClick);
    }
  };
}

<button use:logClick>Click me</button>
Sample Program

This example uses a default action to highlight a paragraph by changing its background color. When the paragraph is removed, the highlight is cleared.

Svelte
<script>
  function highlight(node) {
    node.style.backgroundColor = 'yellow';
    return {
      destroy() {
        node.style.backgroundColor = '';
      }
    };
  }
</script>

<p use:highlight>This text is highlighted when shown.</p>
OutputSuccess
Important Notes

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.

Summary

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.