-2

I very new to Javascript and I'm attempting to create multiple modal images within one page. I generate this coding below

// create references to the modal...
var modal = document.getElementById('myModal');
// to all images
 var images = document.getElementsByClassName('visual');
  // the image in the modal
 var modalImg = document.getElementById("img01");

 // Go through all of the images with our custom class
 for (var i = 0; i < images.length; i++) {
  var img = images[i];
  // and attach our click listener for this image.
  img.onclick = function (evt) {
console.log(evt);
modal.style.display = "block";
modalImg.src = this.src;
 }
}
 // When the user clicks anywhere outside of the modal, close it
 window.onclick = function(event) {
   if (event.target == modal) {
       modal.style.display = "none";
   }
}

It states that line 12 "Dont make functions within loops". Would appreciate help in solving this issue.

Matt.p
  • 1
  • 3
    Possible duplicate of [How to fix jslint error 'Don't make functions within a loop.'?](https://stackoverflow.com/questions/3037598/how-to-fix-jslint-error-dont-make-functions-within-a-loop) – Kevin Boucher Apr 26 '18 at 18:43

1 Answers1

0

You could define the img.onclick handler once, outside the loop, a named function:

...
img.onclick = handler
...

function handler(evt) {
  console.log(evt);
  modal.style.display = "block";
  modalImg.src = this.src;
}
DaveG
  • 445
  • 1
  • 3
  • 14