I wish to use the below modal in multiple area on the same page but because it has id element it works only once, can someone help me here to make it work as many times on a same page?
i tried the following but when click the button nothing opens.
js coxe
var modal = document.getElementById("myModal");
var btn = document.getElementById(".myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
here is the html
<button class="myBtn">Open Modal</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p><?php echo $row['domainid'];?></p>
</div>
</div>
and here is the complete working html + js code
<button id="myBtn">Open Modal</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p><?php echo $row['domainid'];?></p>
</div>
</div>
<script>
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
please someone help me out here. thanks alot in advance
>Solution :
getElementsByClassName returns a collection of elements. So to add an event listener to each of them, you need to loop that collection.
Then, if the modal is always the nextElementSibling of the button, it is easy to target it.
Another useful targeting method is closest() which I used to target a parent of the event.target (the modal).
var btns = Array.from(document.getElementsByClassName("myBtn"));
var spans = Array.from(document.getElementsByClassName("close"));
btns.forEach(function(btn) {
btn.addEventListener("click", function() {
this.nextElementSibling.style.display = "block";
})
})
spans.forEach(function(span) {
span.addEventListener("click", function() {
this.closest(".modal").style.display = "none";
})
})
window.onclick = function(event) {
let modal = event.target.closest(".modal");
if (modal) {
modal.style.display = "none";
}
}
.modal {
display: none;
}
<button class="myBtn">Open Modal 1</button>
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>
Hello 1
</p>
</div>
</div>
<hr>
<button class="myBtn">Open Modal 2</button>
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>
Hello 2
</p>
</div>
</div>
<hr>
<button class="myBtn">Open Modal 3</button>
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>
Hello 3
</p>
</div>
</div>