0 day streak
javascript / intermediate
Snippet

Reusable DOM Logic with Svelte Actions

Actions are functions that are called when an element is created. They are perfect for integrating third-party libraries or handling global events like clicking outside a modal.

snippet.js
javascript
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('click_outside'));
}
};
document.addEventListener('click', handleClick, true);
return {
destroy() {
document.removeEventListener('click', handleClick, true);
}
};
}
svelte
Breakdown
1
export function clickOutside(node) { ... }
Define a function that receives the DOM node as its first argument.
2
return { destroy() { ... } };
Return an object with a 'destroy' method to clean up event listeners when the element is removed.