javascript / intermediate
Snippet
Element-Level Logic with Svelte Actions
Svelte Actions are functions that allow you to attach custom logic to a DOM element's lifecycle. They are ideal for reusable behaviors like detecting clicks outside an element for modals or dropdowns.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export function clickOutside(node) {const handleClick = (event) => {if (node && !node.contains(event.target) && !event.defaultPrevented) {node.dispatchEvent(new CustomEvent('outclick'));}};document.addEventListener('click', handleClick, true);return {destroy() {document.removeEventListener('click', handleClick, true);}};}
svelte
Breakdown
1
export function clickOutside(node) {
The function receives the actual DOM node when the element is created.
2
node.dispatchEvent(new CustomEvent('outclick'));
Creates and dispatches a custom event that can be listened to using on:outclick.
3
destroy() { ... }
Svelte calls this cleanup function automatically when the element is removed from the DOM.