MadEste MadEste - 1 month ago 13
Javascript Question

HTML Button created in object constructors onclick event not working

So whatever is causing the error must actually be in this loop:
Creating a box by calling the gridBox constructor on its own works. But those created by the buildField function do not return an on click event.

var grid = [];
function buildField(size){
//loops through each row
for(var y=0; y<size;y++){
//loops through each column
grid[y]=[];
for(var x=0; x<size; x++){
//create new object for grid
grid[y][x] = new gridBox(x,y);
}
document.getElementById("board").innerHTML += "<br>";
}
}

function gridBox(x,y){
this.x=x;
this.y=y;
var me = this;
//function to create and add button.
function makeBtn(){
var btn = document.createElement("BUTTON");
btn.type = "BUTTON";
btn.className = "gridButton";
btn.value = "BUTTON";
btn.name = me;
btn.onclick = function(){
console.log("click");
};
document.getElementById("board").appendChild(btn);
console.log("madeButton");
}
makeBtn();
}

Answer
document.getElementById("board").innerHTML += "<br>";

This will:

  1. Convert the DOM to HTML
  2. Add <br> to that HTML
  3. Convert that HTML to DOM
  4. Overwrite the existing DOM with that

… the onclick event handlers will not be part of the serialised HTML, so they will be lost when step 4 happens.

Use createElement and appendChild again. Don't use innerHTML.