0 day streak
javascript / expert
Snippet

Custom DOM Interactions via Svelte Actions

Actions are elemental-level lifecycle functions. They are perfect for integrating third-party libraries or handling complex DOM events like detecting clicks outside an element for modals or dropdowns.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
export function clickOutside(node, onEvent) {
const handleClick = (e) => {
if (node && !node.contains(e.target)) onEvent();
};
document.addEventListener('click', handleClick);
return { destroy: () => document.removeEventListener('click', handleClick) };
}
<div use:clickOutside={() => console.log('Closed')}>Content</div>
svelte
Breakdown
1
export function clickOutside(node, onEvent)
A standard JS function receiving the DOM node and a custom handler.
2
return { destroy: ... }
Ensures proper cleanup to prevent memory leaks when the element is removed from the DOM.
3
use:clickOutside={...}
The directive that attaches the logic to a specific HTML element.