I am trying to display a modal with the name and the description of an image that was clicked by the user. Currently I only get the last image's name and no description (bad loop).
Please have a look at my code and please let me know how I can fix this issue. I am looking at this loop and I feel that it's not right, but I just can't figure it out how to fix it. Been trying for a while... Many thanks, guys.
Found an issue - myName[i].innerHTML, I cant reach variable i, I get error (Cannot read property 'innerHTML' of undefined), if I enter number manually then it prints name correctly.
// Get modal
let modal = document.getElementById("myModal");
let i;
// Get image
let img = document.getElementsByClassName("myImg");
let myName = document.getElementsByClassName("myName");
let myDesc = document.getElementsByClassName("myDesc");
let modalImg = document.getElementById("showImg");
let modalName = document.getElementById("imgName");
let modalDesc = document.getElementById("imgDesc");
// Loop through images
for (i = 0; i < img.length; i++) {
img[i].onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
modalName.innerHTML = myName[i].innerHTML;
modalDesc.innerHTML = myDesc[i].innerHTML;
}
}
// Images
<div>
<img class="myImg" src="images/1.png" alt="">
<h5 class="myName">Image name1</h5>
<p class="myDesc">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis, quaerat, aut.</p>
</div>
<div>
<img class="myImg" src="images/2.png" alt="">
<h5 class="myName">Image name2</h5>
<p class="myDesc">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis, quaerat, aut.</p>
</div>
<div>
<img class="myImg" src="images/3.png" alt="">
<h5 class="myName">Image name3</h5>
<p class="myDesc">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium, debitis, provident.</p>
</div>
// Modal
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="showImg">
<div id="imgName"></div>
<div id="imgDesc"></div>
</div>