File size: 538 Bytes
53e0cfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import type { Action } from "svelte/action";

export const clickOutside: Action<HTMLElement, () => void> = (node, callback) => {
	let _callback = callback;

	function update(callback: () => void) {
		_callback = callback;
	}

	function handleClick(event: MouseEvent) {
		if (node && !node.contains(event.target as Node) && !event.defaultPrevented) {
			_callback();
		}
	}

	document.addEventListener("click", handleClick, true);

	return {
		update,
		destroy() {
			document.removeEventListener("click", handleClick, true);
		},
	};
};