JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
HTML
<!-- Trigger Button -->
<button id="openModal">Open Modal</button>
<!-- Modal Structure -->
<div id="modalBackdrop" class="modal-backdrop hidden">
<div id="modalContent" class="modal-content">
<p>This is a modal. Click outside to close.</p>
</div>
</div>
CSS
.modal-backdrop {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
background: white;
padding: 20px;
border-radius: 5px;
}
.hidden {
display: none;
}
JavaScript
document.addEventListener('DOMContentLoaded', function() {
const modalBackdrop = document.getElementById('modalBackdrop');
const openModalBtn = document.getElementById('openModal');
const modalContent = document.getElementById('modalContent');
// Open modal
openModalBtn.addEventListener('click', function() {
modalBackdrop.classList.remove('hidden');
});
// Close modal on clicking the negative space
modalBackdrop.addEventListener('click', function(event) {
// If the clicked element is not the modal content, close the modal
if (event.target === modalBackdrop) {
modalBackdrop.classList.add('hidden');
}
});
// Prevent modal content click from closing the modal
modalContent.addEventListener('click', function(event) {
event.stopPropagation();
});
});