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 >Open Modal</button>
<div id="myModal" >
<div >
<span >×</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" >
<div >
<span >×</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
CodePudding user response:
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 >Open Modal 1</button>
<div >
<div >
<span >×</span>
<p>
Hello 1
</p>
</div>
</div>
<hr>
<button >Open Modal 2</button>
<div >
<div >
<span >×</span>
<p>
Hello 2
</p>
</div>
</div>
<hr>
<button >Open Modal 3</button>
<div >
<div >
<span >×</span>
<p>
Hello 3
</p>
</div>
</div>
CodePudding user response:
Just a small mistake in your code. You are selecting class myBtn using getElementById.
Old code:
var btn = document.getElementById(".myBtn");
New code:
var btn = document.getElementByClassName("myBtn"); //Don't use . (dot)
Or:
var btn = document.querySelector(".myBtn"); //Use . (dot)
