Skip to content

Instantly share code, notes, and snippets.

@elzodxon
Created November 26, 2023 18:02
Show Gist options
  • Save elzodxon/77187677b4826f044bd9e9fd21232d1f to your computer and use it in GitHub Desktop.
Save elzodxon/77187677b4826f044bd9e9fd21232d1f to your computer and use it in GitHub Desktop.
Modal
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiple Modals Toggle Example</title>
<style>
.modal {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background-color: #fff;
border: 1px solid #ccc;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
z-index: 1000;
}
.overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
z-index: 999;
}
</style>
</head>
<body>
<!-- Trigger buttons for multiple modals -->
<button class="modalToggleBtn" data-modal="modal1">Open Modal 1</button>
<button class="modalToggleBtn" data-modal="modal2">Open Modal 2</button>
<!-- Modals -->
<div id="modal1" class="modal">
<p>This is Modal 1!</p>
<button class="closeModalBtn">Close Modal</button>
</div>
<div id="modal2" class="modal">
<p>This is Modal 2!</p>
<button class="closeModalBtn">Close Modal</button>
</div>
<!-- Overlay -->
<div class="overlay"></div>
<!-- JavaScript -->
<script>
// Get all modal toggle buttons
var modalToggleButtons = document.querySelectorAll('.modalToggleBtn');
// Get all close modal buttons
var closeModalButtons = document.querySelectorAll('.closeModalBtn');
// Get all modals
var modals = document.querySelectorAll('.modal');
// Get all overlays
var overlays = document.querySelectorAll('.overlay');
// Function to open a specific modal
function openModal(modalId) {
var modal = document.getElementById(modalId);
var overlay = document.querySelector('.overlay');
modal.style.display = 'block';
overlay.style.display = 'block';
}
// Function to close a specific modal
function closeModal(modalId) {
var modal = document.getElementById(modalId);
var overlay = document.querySelector('.overlay');
modal.style.display = 'none';
overlay.style.display = 'none';
}
// Event listeners for modal toggle buttons
modalToggleButtons.forEach(function(button) {
button.addEventListener('click', function() {
var modalId = button.getAttribute('data-modal');
openModal(modalId);
});
});
// Event listeners for close modal buttons
closeModalButtons.forEach(function(button) {
button.addEventListener('click', function() {
var modalId = button.parentElement.id;
closeModal(modalId);
});
});
// Event listener to close modal when clicking outside the modal
overlays.forEach(function(overlay) {
overlay.addEventListener('click', function() {
var modalId = overlay.nextElementSibling.id;
closeModal(modalId);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment