In the site design that I am doing, several modals must be created on one page. I have created this mod. I want the modal to close whenever out of modal is clicked.
In the last part of the code window.onclick = function(event){...}
, this code is effective only on the last modal (modal number 3) and is completely ineffective on other modals (modal number 1 and 2).
I don't know where there is a problem in the code that doesn't work completely.
Thank you for guiding me.
const triggers = document.getElementsByClassName("trigger");
const triggerArray = Array.from(triggers).entries();
const modals = document.getElementsByClassName("modal");
const closeButtons = document.getElementsByClassName("btn-close");
for (let [index, trigger] of triggerArray) {
const toggleModal = () => {
modals[index].classList.toggle("show-modal");
};
trigger.addEventListener("click", toggleModal);
closeButtons[index].addEventListener("click", toggleModal);
// window.onclick = function(event) {
// const isClickInside = modals[index].contains(event.target);
// if (!isClickInside) {
// modals[index].classList.toggle("show-modal");
// }
// };
// window.onclick = function(event) {
// if (event.target === modals[index]) {
// modals[index].classList.toggle("show-modal");
// }
// };
//I found it=> this is work
window.addEventListener('click', function(event){
if(event.target === modals[index]){
modals[index].classList.remove("show-modal");
console.log(modals[index])
}
});
}
.modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
opacity: 0;
display: flex;
justify-content: center;
align-items: center;
visibility: hidden;
transform: scale(1.1);
transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}
.modal-content {
align-self: center;
background-color: white;
padding: 1rem 1.5rem;
width: 24rem;
border-radius: 0.5rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.btn-close {
float: right;
width: 1.5rem;
line-height: 1.5rem;
text-align: center;
cursor: pointer;
border-radius: 0.25rem;
background-color: lightgray;
}
.show-modal {
opacity: 1;
visibility: visible;
transform: scale(1);
transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}
<button class="trigger">Modal 1</button>
<button class="trigger">Modal 2</button>
<button class="trigger">Modal 3</button>
<div class="modal">
<div class="modal-content">
<span class="btn-close">×</span>
<h1>modal 1</h1>
</div>
</div>
<div class="modal">
<div class="modal-content">
<span class="btn-close">×</span>
<h1>modal 2</h1>
</div>
</div>
<div class="modal">
<div class="modal-content">
<span class="btn-close">×</span>
<h1>modal 3</h1>
</div>
</div>