Reputation: 91
I have a basic problem with showing modal. Everything is working ok, but only for second click. I am sure, I have some mistake in js code. Can you help me please?
HTML code:
<div class="flex flex-col lg:flex-row justify-center px-3 lg:px-0">
<div class="pb-3 lg:pb-0 lg:p-5 cursor-pointer">
<img onclick="showImage('planek1')" id="planek1" src="assets/imgs/planek1.jpg" alt="">
</div>
<div class="cursor-pointer lg:p-5">
<img onclick="showImage('planek2')" id="planek2" src="assets/imgs/planek2.jpg" alt="">
</div>
</div>
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>
Javascript code:
function showImage(id) {
const modal = document.getElementById("myModal");
const img = document.getElementById(id);
const modalImg = document.getElementById("img01");
img.onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
};
const span = document.getElementsByClassName("close")[0];
span.onclick = function () {
modal.style.display = "none";
};
}
Upvotes: 0
Views: 89
Reputation: 31835
Try removing onclick="showImage('planek2')"
, give a class="triggers-modal"
to your elements, and write this JavaScript:
const modalImg = document.getElementById("img01");
const span = document.getElementsByClassName("close")[0];
span.onclick = function () {
modal.style.display = "none";
};
Array.from(document.getElementsByClassName('triggers-modal')).forEach(element => {
element.onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
};
});
This code defines the modal behavior for every element that has the triggers-modal
class name instead of the onclick
event which is inappropriate.
Upvotes: 2