HYUTS HYUTS - 5 months ago 17
HTML Question

Add onclick event to individual divs within loop

I am making a tic-tac-toe game.
I would like to add individual onclick event to each div so I can add either an "X" or an "O" depending on the div I click. "O" will be added later.

JavaScript:

function createDivs() {
for (i=0; i<9; i++) {
var d = document.createElement("DIV");
document.body.appendChild(d);

//Stuck here -borrowed some of this from a similar topic-
d.onclick = function() {
return function() {
var p = document.createElement("P");
var x = document.createTextNode("X");
p.appendChild(x);
d.appendChild(p);
}
}(i);
//-------------------------------------------------

var ii = document.createAttribute("id");
ii.value = "D" + i;
d.setAttributeNode(ii);
var z = "D" + i;
if (i == 3 || i == 6) {
document.getElementById(z).style.clear = "left";
}
}
}


html:
<body onload="createDivs()">

Answer

Pass d as argument and accept it as argument so that closure will remember it when click handler-function will be executed.

d is nothing but the element you are creating(var d = document.createElement("DIV");)

function createDivs() {
  for (i = 0; i < 9; i++) {
    var d = document.createElement("DIV");
    d.style.float = 'left';
    document.body.appendChild(d);
    d.onclick = function(d) {
      //----------------^^^ Accept d here
      return function() {
        var p = document.createElement("P");
        var x = document.createTextNode("X");
        p.appendChild(x);
        d.appendChild(p);
      }
    }(d);
    //^^ Pass d here
    var ii = document.createAttribute("id");
    ii.value = "D" + i;
    d.setAttributeNode(ii);
    var z = "D" + i;
    if (i == 3 || i == 6) {
      document.getElementById(z).style.clear = "left";
    }
  }
}
div {
  width: 30px;
  height: 30px;
  border: 1px solid black;
}
<body onload="createDivs()">