Sorry if the title isn't exactly accurate, not sure how else to describe it. I have this bit of js I pieced together using various other tutorials. It's working, but I was hoping for a little more understanding on how/why it works.
The code is for a modal on a page full of images, where you click on any image and it launches a modal with that image in it. Here are the relevant parts of the code:
function modal(modalId, modalImg) {
var image = document.getElementsByClassName('modalImg');
var imageLength = image.length;
var myModal = document.getElementById(modalId);
var modalImg = document.getElementById(modalImg);
for (var i = 0; i < imageLength; i++) {
(function(index) {
image[i].onclick = function() {
myModal.style.display = "block";
modalImg.src = this.src;
imgIndex = index;
}
})(i);
}
}
You can see this code working (and in full context) here.
The part I'm trying to understand here involves the closure function and event listener. So the closure function is being called, and i
(the for-loop's counter) is passed as the index
argument. My question is, how the heck is i
being set to the index of the image that was clicked?