Skip to content

Instantly share code, notes, and snippets.

@seriousManual
Created July 14, 2022 12:05
Show Gist options
  • Save seriousManual/a28e24bc7ccdd228a723cf2586de465f to your computer and use it in GitHub Desktop.
Save seriousManual/a28e24bc7ccdd228a723cf2586de465f to your computer and use it in GitHub Desktop.
function clickOutside(node, handler) {
function handleClick(event) {
if (node && !node.contains(event.target) && !event.defaultPrevented) {
handler()
}
}
document.addEventListener('click', handleClick, true)
return {
destroy() {
document.removeEventListener('click', handleClick, true)
}
}
}
export default clickOutside
<script type="ts">
import onClickOutside from '../clickOutside'
</script>
<div use:onClickOutside={() => console.log('click')}>
modal
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment