I am facing an issue with a modal box on my webpage. The first modal opens correctly when clicking a button, but after duplicating it for a second modal, the second one fails to open upon clicking the button.
Is there a way to trigger the second modal using the same classes and JavaScript function without adding additional code? Or can the second modal be activated with minimal code?
/* Modal Box Js */
const modal = document.querySelector(".modal");
const trigger = document.querySelector(".trigger");
const closeButton = document.querySelector(".close-button");
function toggleModal() {
modal.classList.toggle("show-modal");
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
}
trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
/**********
Modal Box Style
**********/
.trigger {cursor: pointer;}
.modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
opacity: 0;
visibility: hidden;
transform: scale(1.1);
transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 20px;
width: 40rem;
border-radius: 6px;
display: flex;
flex-direction: column;
}
.msg-title {
font-size: 18px;
font-weight: bold;
margin-bottom: 12px;
}
.msg-text {
font-size: 14px;
margin-bottom: 6px;
color: #5B616D;
}
.close-button {
float: right;
width: 1.5rem;
line-height: 1.5rem;
text-align: center;
cursor: pointer;
border-radius: 0.25rem;
background-color: lightgray;
align-self: end;
}
.close-button:hover {
background-color: darkgray;
}
.show-modal {
opacity: 1;
visibility: visible;
transform: scale(1.0);
transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}
<!-- Modal Box 1 -->
<div class="trigger">Modal Box 1</div>
<div class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<span class="msg-title">Title 1</span>
<span class="msg-text">
“If you are distressed by anything external, the pain is not due to the thing itself, but to your estimate of it; and this you have the power to revoke at any moment.”
― Marcus Aurelius.
</span>
</div>
</div>
<!-- Modal Box 2 -->
<div class="trigger">Modal Box 2</div>
<div class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<span class="msg-title">Title 2</span>
<span class="msg-text">
“If you are distressed by anything external, the pain is not due to the thing itself, but to your estimate of it; and this you have the power to revoke at any moment.”
― Marcus Aurelius.
</span>
</div>
</div>