1

I have a for loop in which I'm using a local variable from the loop as a parameter for an onclick event callback. I'm doing it according to what I've read in these posts:

Passing parameter onclick, in a loop

Javascript - Dynamically assign onclick event in the loop

However the issue I'm seeing is that the onclick function is only calling once, immediately, and then never again. I found a potential solution in this post:

Javascript onclick function is called immediately (not when clicked)?

Except that example only seems to work if the onclick function takes no parameters.

SO. How do we both A) set onclick using a local variable in a loop, and B) have it call properly when clicked and not just once the first time?

Here is an example:

https://jsfiddle.net/jq7wbxaz/24/

function generateCard() {
  for(var n = 0; n < 5; n++) {
    for(var k = 0; k < 5; k++) {
      var cell = document.createElement("div");
      cell.setAttribute("class", "box");
      cell.setAttribute("id", "r"+n+"c"+k);
      var letter;
      switch(k) {
        case 0:
            letter = "B";
          break;
        case 1:
            letter = "I";
          break;
        case 2:
            letter = "N";
          break;
        case 3:
            letter = "G";
          break;
        case 4:
            letter = "O";
          break;

      }
      cell.innerHTML = letter + n;
      cell.onclick = (function(c) {changeCellColor(c);})(cell);

      document.getElementById("card").appendChild(cell);
    }
  }
} 

function changeCellColor(cell) {
    //var cell = getCell(n, k);
  console.log("Changing color for cell " + cell.id);
    cell.style.backgroundColor = '#'+Math.floor(Math.random()*16777215).toString(16);
}

generateCard();

In this fiddle, a bingo card is being generated. The desired behavior is for each box of the card to have an onclick function that changes that boxes color. Instead, they all are a random color at start and onclick doesn't work.

Any help would be appreciated!

SemperCallide
  • 1,950
  • 6
  • 26
  • 42

1 Answers1

1

You'll want to reference this in the function you call when the cell is clicked. It refers to the cell's element.

So, your onclick function will become this:

cell.onclick = function() { changeCellColor(this) };

More examples here

Joundill
  • 6,828
  • 12
  • 36
  • 50