javascript / expert
Snippet
Reusable Interaction Logic with Svelte Actions
Svelte actions are functions called when an element is created. They are perfect for interfacing with the DOM directly, such as handling clicks outside a modal. The return object's destroy method ensures proper cleanup when the element is removed.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export function clickOutside(node, handler) {const handleClick = (event) => {if (node && !node.contains(event.target) && !event.defaultPrevented) {handler();}};document.addEventListener('click', handleClick, true);return {destroy() {document.removeEventListener('click', handleClick, true);}};}// Usage: <div use:clickOutside={() => (show = false)}>
svelte
Breakdown
1
export function clickOutside(node, handler)
Defines the action taking the target element (node) and a callback function (handler).
2
if (node && !node.contains(event.target))
Checks if the clicked target is not the element itself or any of its children.
3
destroy() { ... }
Lifecycle cleanup that prevents memory leaks by removing the global event listener.