Modal Opened by Multiple Triggers
Allow multiple elements to trigger the opening of the same modal, using event delegation to minimize the number of event listeners.
<!-- HTML Structure -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<button class="modal-trigger">Open Modal</button>
<button class="modal-trigger">Open Modal Too</button>
This HTML structure includes a modal with a unique ID and two buttons with the same class. Both buttons are designed to trigger the opening of the modal.
/* CSS for the Modal */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
The CSS styles for the modal include hiding the modal by default and formatting for the modal content. The 'close' class styles the close button.
// JavaScript to open modal with multiple triggers
// Event delegation is used to minimize the number of event listeners
document.addEventListener('click', function(event) {
if (event.target.classList.contains('modal-trigger')) {
document.getElementById('myModal').style.display = 'block';
}
});
document.querySelector('.close').onclick = function() {
document.getElementById('myModal').style.display = 'none';
};
window.onclick = function(event) {
if (event.target == document.getElementById('myModal')) {
document.getElementById('myModal').style.display = 'none';
}
};
The JavaScript adds a single event listener to the document that listens for clicks on any element with the 'modal-trigger' class, then opens the modal. It also includes the script to close the modal when clicking the close button or outside the modal content.