Last active
May 21, 2024 17:39
-
-
Save Hugos68/27376946bfd21f431a0ee395f1e5ad71 to your computer and use it in GitHub Desktop.
`<dialog>` close on click outside Svelte action
This file contains 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
<script lang="ts"> | |
const click_outside = (node: HTMLDialogElement) => { | |
const onclick = (event: MouseEvent) => { | |
if (event.target === null || !(event.target instanceof Element)) { | |
return; | |
} | |
if (event.target.tagName !== 'DIALOG') { | |
//This prevents issues with forms | |
return; | |
} | |
const rect = event.target.getBoundingClientRect(); | |
const clickedInDialog = | |
rect.top <= event.clientY && | |
event.clientY <= rect.top + rect.height && | |
rect.left <= event.clientX && | |
event.clientX <= rect.left + rect.width; | |
if (clickedInDialog === false) { | |
node.close(); | |
} | |
}; | |
document.addEventListener('click', onclick); | |
return { | |
destroy: () => { | |
document.removeEventListener('click', onclick); | |
}, | |
}; | |
}; | |
</script> | |
<dialog use:click_outside> | |
<!-- ... --> | |
</dialog> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment