Discover how a tiny reusable trick can save you hours of repetitive coding!
Why Default actions in Svelte? - Purpose & Use Cases
Imagine you want to add the same behavior to many buttons on your webpage, like focusing an input when a button is clicked. You write the same event code over and over for each button.
Writing repetitive event handlers for each element is tiring and easy to forget. It clutters your code and makes updates slow because you must change every handler separately.
Svelte's default actions let you write reusable behaviors once and apply them easily to any element. This keeps your code clean and consistent without repeating yourself.
button.addEventListener('click', () => { input.focus(); });<button use:focusOnClick>Click me</button>
<script>
function focusOnClick(node) {
node.addEventListener('click', () => {
document.querySelector('input').focus();
});
return {
destroy() {
node.removeEventListener('click', () => {
document.querySelector('input').focus();
});
}
};
}
</script>It enables you to create simple, reusable behaviors that automatically attach to elements, making your app easier to build and maintain.
Think of a form where clicking any label focuses its input. Instead of coding each label separately, a default action can handle all labels uniformly.
Manual event handling is repetitive and error-prone.
Default actions let you write reusable behaviors once.
They keep your code clean and easy to update.