0

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?

Ben
  • 19
  • 4

1 Answers1

0

You could do it like this way.

var table = document.querySelector('table');
var buttons = [].slice.call(table.querySelectorAll('.gridButton'));
table.addEventListener('click', function(e) {
  var target = e.target;
  if(buttons.indexOf(target) > -1) {
    var id = target.id;

    console.log(id, target);
    // target is your button and id its id
    // do your color circle thing here
    // you could bind the button as `this` to your circle function
    // circleBackgroundColor().bind(target);
    // inside of circleBackgroundColor this.id will give you the button id and this will give you the button.
  }
});
<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>
cyr_x
  • 13,987
  • 2
  • 32
  • 46