So I've just started learning JS and am stuck on this problem. I've created a table of buttons using JS which translates to this in HTML:
<table border="1" style="width: 100%; border: none;">
<tr>
<td class="emptyBorder">
<button class="gridButton" id="button0x0y"></button></td>
<td class="emptyBorder">
<button class="gridButton" id="button0x1y"></button></td>
</tr>
<tr>
<td class="emptyBorder">
<button class="gridButton" id="button1x0y"></button></td>
<td class="emptyBorder">
<button class="gridButton" id="button1x1y"></button></td>
</tr>
</table>
I'm trying to give each of them an onClick that cycles only their own color between 3 different colors. I tried assigning this onClick to each of them when I created them in my JS code, but was running into problems there so I separated that functionality into a new function, which is:
function addOnclickToTable(x, y){
for( var i = 0; i < x; i++ ) {
for ( var j = 0; j < y; j++ ) {
var thisId = buttonIDFromXY(i,j); // returns "button{i}x{j}y"
var button = document.getElementById(thisId);
button.onclick = function() {cycleBackgroundColor(thisID);}; // Changes background color of the element with the given ID
}
}
}
This assigns "onclick = cycleBackgroundColor('button1x1y')" to each of the buttons. It seems that the value of thisID is saved in the JS and referenced as its last known value when it is called later on. Is there a way to create a new instance of it in place? Is there a better solution?