Search code examples
javascripthtml-tablecellbackground-color

Switching cell background color of a table created with javascript


I have a problem: I need a table 7x48 cells, those cells have a background color (grey) which have to be switchable when clicked (green) and then switchable again with another click. I created the table with the following js function:

function createGrid(){
// get the reference for the body
    var grid = document.getElementById("grid");
    var green="#33CC66";
    var grey="#DEDEDE";

    // creates a <table> element and a <tbody> element
    var tbl     = document.createElement("table");
    var tblBody = document.createElement("tbody");
    tbl.id="timegrid";
    tbl.style.backgroundColor=grey;
    // creating all cells
    for (var j = 0; j < 7; j++) {
        // creates a table row
        var row = document.createElement("tr");

        for (var i = 0; i < 48; i++) {
            // Create a <td> element and a text node, make the text
            // node the contents of the <td>, and put the <td> at
            // the end of the table row
            var cell = document.createElement("td");

            cell.onmousedown=function(){
                if(this.style.backgroundColor!=grey)
                this.style.backgroundColor=grey;
                else this.style.backgroundColor=green;                  

            };
            row.appendChild(cell);
        }

        // add the row to the end of the table body
        tblBody.appendChild(row);
    }

    // put the <tbody> in the <table>
    tbl.appendChild(tblBody);
    // appends <table> into <div id="grid">
    grid.appendChild(tbl);
    tbl.setAttribute("cellPadding", "7");
    tbl.setAttribute("cellSpacing", "0");
    tbl.setAttribute("border", "1");}

The problem is: it works the first time (from grey the cell switches to green) but I can't turn back to the original color the second time I click on the same cell. Any suggestion?


Solution

  • The problem is that the browser doesn't keep the same value that you set.

    For example, if you do

    document.body.style.backgroundColor = '#33cc66'
    console.log(document.body.style.backgroundColor);
    

    You get rgb(51, 204, 102) returned. (And let it be known that StackOverflow is hideous with a green background.)

    This value is the functional notation for colour.

    You probably need to store the value that you've set it to, because browsers are inconsistent in how they report the current colour value.

    cell.onmousedown=function(){
        if(background !== grey) {
            this.style.backgroundColor=grey;
            background = grey;
        } else {
            this.style.backgroundColor=green;      
            background = green;            
        }
    };