Created
April 30, 2024 22:06
-
-
Save SpenceDiNicolantonio/8ee4f3f9e6c784b5e65996c7e23cd6ac to your computer and use it in GitHub Desktop.
Click Outside directive #svelte #typescript #directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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