Skip to content

Instantly share code, notes, and snippets.

@SpenceDiNicolantonio
Created April 30, 2024 22:06
Show Gist options
  • Save SpenceDiNicolantonio/8ee4f3f9e6c784b5e65996c7e23cd6ac to your computer and use it in GitHub Desktop.
Save SpenceDiNicolantonio/8ee4f3f9e6c784b5e65996c7e23cd6ac to your computer and use it in GitHub Desktop.
Click Outside directive #svelte #typescript #directive
export default function clickOutside(node: HTMLElement) {
const handleClick = (event: MouseEvent) => {
if (!node.contains(event.target as Node)) {
node.dispatchEvent(new CustomEvent('outsideclick'));
}
};
// The node has been mounted to the DOM
window.addEventListener('click', handleClick);
return {
destroy() {
// The node has been removed from the DOM
window.removeEventListener('click', handleClick);
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment