javascript / intermediate
Snippet
Reusable Element Behavior with Actions
Actions are functions called when an element is created. They allow you to add custom logic to DOM nodes, like detecting clicks outside an element. This is ideal for integrating third-party libraries or handling complex interactions without cluttering the component logic.
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.contains(event.target)) {node.dispatchEvent(new CustomEvent('outclick'));}};document.addEventListener('click', handleClick);return {destroy() {document.removeEventListener('click', handleClick);}};}
svelte
Breakdown
1
export function clickOutside(node) {
The function receives the DOM node instance as its first argument.
2
node.dispatchEvent(new CustomEvent('outclick'));
Fires a custom DOM event that can be caught in Svelte using on:outclick.
3
return { destroy() { ... } };
The returned object can include a destroy method for cleaning up listeners when the element is removed.