Reputation: 1
i'enter code here novice in javascript i'm trying to make a popup but i have issue when opening these popups i don't find how to open these two divs with one javascript code it open one not the other i tried many solutions i find in this website but it still doesn't word
here are my html css and javascript code
var modal = document.querySelector(".aaa");
var trigger = document.querySelector(".trigger");
var 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);
.aaa {
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:relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 1rem 1.5rem;
width: 65%;
height: 80%;
border-radius: 0.5rem;
}
.close-button {
float: right ;
width: 1.5rem;
line-height: 1.5rem;
text-align: center;
cursor: pointer;
border-radius: 0.25rem;
background-color: lightgray;
}
.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;
}
<button class="trigger">Click here to trigger the modal!</button>
<div class="aaa">
<div class="modal-content">
<span class="close-button">×</span>
<div>
<h2>edddddddddddddd</h2>
<p>hhhhhhhhhdefrfrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrghjuyhgt</p>
</div>
</div>
</div>
<button class="trigger">Click here to trigger the modal!</button>
<div class="aaa">
<div class="modal-content">
<span class="close-button">×</span>
<div>
<h2>egtgttttttttgtg</h2>
<p>55555555555555555555555555</p>
</div>
</div>
</div>
Upvotes: 0
Views: 212
Reputation: 35
Writing an answer because I can't comment yet.
ortoDev is correct. To open different modals you need to use querySelectorAll on the modals as well.
Any time you query a css class you have to assume you will get an array because multiple components can have the same class.
document.querySelector(".aaa"); == document.querySelectorAll(".aaa")[0];
Upvotes: 0
Reputation: 36
It is because querySelector takes only the first .trigger
You should loop through all the elements using the ALL selector querySelectorAll() like :
var triggers = document.querySelectorAll(".trigger");
for( var i=0;i<triggers.length;i++){
triggers[i].addEventListener("click", toggleModal);
}
Upvotes: 1