-3

I'm having trouble looping the following function. It works when changing i='x' for each 1,2,3... However, when trying to loop for 'i', it becomes unresponsive. I feel there's something obvious I'm missing!

var i=1;
var modal = [];
var btn = [];
var span = [];
//for(i=1;i<5;i++)
//{
modal[i]= document.getElementById('challenge'+i+'Modal');
btn[i] =document.getElementById("challenge"+i);
span[i] = document.getElementById('challenge'+i+'Close');


btn[i].onclick = function() {
  modal[i].style.display = "block";
}

span[i].onclick = function() {
  modal[i].style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal[i]) {
    modal[i].style.display = "none";
  }
}
//}
Mikev
  • 2,012
  • 1
  • 15
  • 27

1 Answers1

0

Thanks @epascarello for the pointer, here is the solution:

var i;
var modal = [];
var btn = [];
var span = [];

function open(i) {
    return function() {
      modal[i].style.display = "block";
    }
}
function closex(i) {
    return function() {
      modal[i].style.display = "none";
    }
}
function close(i) {
    return function(event) {
      if (event.target == modal[i]) {
        modal[i].style.display = "none";
      }
    }
}

for(i=1;i<3;i++)
{
    modal[i]= document.getElementById('challenge'+i+'Modal');
    btn[i] =document.getElementById("challenge"+i);
    span[i] = document.getElementById('challenge'+i+'Close');

    // When the user clicks the button, open the modal 
    btn[i].onclick = open(i);

    // When the user clicks on <span> (x), close the modal
    span[i].onclick = closex(i);
    // When the user clicks anywhere outside of the modal, close it
    window.onclick = close(i);
}