Skip to content

Commit 8464089

Browse files
committed
New modal variant with close on outside click.
1 parent b0571c6 commit 8464089

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

src/components/Modal.astro

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
---
22
import Button from '@ui/Button.astro';
3-
const { id = 'modal', open = false } = Astro.props;
3+
const { id = 'modal', open = false, closeOnOutsideClick = false } = Astro.props;
44
---
5-
65
<div
76
id={id}
87
class={`fixed inset-0 z-50 flex items-center justify-center transition-opacity duration-300 ${
98
open ? 'opacity-100 visible bg-black/50' : 'opacity-0 invisible'
109
}`}
1110
data-modal-wrapper
11+
data-close-on-outside-click={closeOnOutsideClick.toString()}
1212
>
1313
<div
1414
class="relative bg-white dark:bg-gray-800 p-6 lg:rounded-2xl lg:shadow-xl lg:max-w-4xl lg:mx-4 h-full lg:h-[80vh] w-full lg:w-[70vw] max-h-full overflow-y-auto"
15+
data-modal-content
1516
>
1617
<Button
1718
id="search-close"
@@ -24,9 +25,9 @@ const { id = 'modal', open = false } = Astro.props;
2425
<slot />
2526
</div>
2627
</div>
27-
2828
<script is:inline>
2929
document.addEventListener('DOMContentLoaded', () => {
30+
// Open modal buttons
3031
document.querySelectorAll('[data-open-modal]').forEach(button => {
3132
button.addEventListener('click', () => {
3233
const modal = document.getElementById(button.dataset.openModal);
@@ -35,12 +36,28 @@ const { id = 'modal', open = false } = Astro.props;
3536
});
3637
});
3738

39+
// Close modal buttons
3840
document.querySelectorAll('[data-close-modal]').forEach(button => {
3941
button.addEventListener('click', () => {
4042
const modal = button.closest('[data-modal-wrapper]');
4143
modal?.classList.remove('opacity-100', 'visible');
4244
modal?.classList.add('opacity-0', 'invisible');
4345
});
4446
});
47+
48+
// Close when clicking outside the modal content - only if enabled
49+
document.querySelectorAll('[data-modal-wrapper]').forEach(modal => {
50+
const closeOnOutsideClick = modal.dataset.closeOnOutsideClick === 'true';
51+
52+
if (closeOnOutsideClick) {
53+
modal.addEventListener('click', (event) => {
54+
// Check if the click was on the wrapper but not on the content
55+
if (event.target === modal) {
56+
modal.classList.remove('opacity-100', 'visible');
57+
modal.classList.add('opacity-0', 'invisible');
58+
}
59+
});
60+
}
61+
});
4562
});
4663
</script>

src/components/Search.astro

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import Modal from "@components/Modal.astro";
66
---
77

88

9-
<Modal id="modal-search">
9+
<Modal id="modal-search" closeOnOutsideClick=true>
1010
<h2 class="text-xl font-bold mb-2 py-2">Search</h2>
1111
<SearchComponent
1212
id="search"

0 commit comments

Comments
 (0)