Skip to content

Instantly share code, notes, and snippets.

@Hugos68
Last active May 21, 2024 17:39
Show Gist options
  • Save Hugos68/27376946bfd21f431a0ee395f1e5ad71 to your computer and use it in GitHub Desktop.
Save Hugos68/27376946bfd21f431a0ee395f1e5ad71 to your computer and use it in GitHub Desktop.
`<dialog>` close on click outside Svelte action
<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