user4798789
user4798789

Reputation:

How to change a cell's background color javascript

The goal is to change the color of a cell when it is clicked. There is my js code below. As you can see I tried the style.backgroundColor, but only the right bottom cell changed it's color regardless the clicked cell.

var board = document.getElementById("tab"),
    lvl1 = {rows: 5, cols: 5};
for(var i=0; i<lvl1.rows; i++){
  var row=board.insertRow();
  for(var j=0; j<lvl1.cols; j++) {
    var cell = row.insertCell();
  }       
}
board.onclick = function(e) {
  var cellIndex = e.target.cellIndex;
  var rowIndexx = e.target.parentNode.rowIndex;
  console.log(cellIndex + ".." + rowIndexx);
  cell.style.backgroundColor = "red";
};
table { margin: 0 auto; }
td {
  height: 20px;
  width: 20px;
  border: 1px solid;
  cursor: pointer;
}
<table id="tab"></table>

Upvotes: 0

Views: 1765

Answers (1)

hbillings
hbillings

Reputation: 174

Replace:

cell.style.backgroundColor="red";

with

e.target.style.backgroundColor="red";

This will set the background for whatever is clicked on, which will be your elements. The alternative is to keep a two-deminsional array around of your cells ( cell[row][column] ) that you can get the proper cell from using your indexes.

Upvotes: 2

Related Questions