Dev Dev - 2 months ago 16
CSS Question

Changing the color of the cells of a table on mouseclick using html

I designed a 2*4 table using html.I need to change the background color of a cell from white(default) to green on the odd mouse clicks and vice versa on the even clicks.Similarly any number of cells must be selected to green.I actually tried to replicate the seat selection design in redbus and bookmyshow websites' seat selection.But despite of clicking any cell only the first cell changes from white to green and vice versa.Kindly help me.Thank you.

<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<link rel="stylesheet" type="text/css" href="design.css">
<script type="text/javascript">
function change()
{
var s=document.getElementById('slot');
if(s.bgColor.match("white"))
{
s.bgColor="green";
}
else
{
s.bgColor="white";
}

}

</script>
</head>
<body>

<div class="leftcontent">
<TABLE BORDER="2" CELLPADDING="2" height="100px" WIDTH="300px">
<TR >
<TD id="slot" onclick="change()"></TD>
<TD id="slot" onclick="change()"></TD>
<TD id="slot" onclick="change()"></TD>
<TD id="slot" onclick="change()"></TD>
</TR>

<TR >
<TD id="slot" onclick="change()"></TD>
<TD id="slot" onclick="change()"></TD>
<TD id="slot" onclick="change()"></TD>
<TD id="slot" onclick="change()"></TD>
</TR>
</TABLE>

</div>
</body>
</html>

Answer Source

I answered a similar question here

Javascript .addEventListener "mouseenter" for a class

The difference is that this involves the click event and there is no css pseudo selector for this.

First query a list of all our td elements with querySelectorAll.

Next loop through and add the click event listener for each of them.

The class can be set multiple ways, but I recommend with the className method. To toggle between classes, the ternary operator is our best friend.

this.className = this.className == "white" ? "green": "white";

What this means is that it sets the class depending on its current value.

var cells = document.querySelectorAll("td");

for (var i = 0; i < cells.length; i++) {
    cells[i].addEventListener("click", function() {
       this.className= this.className == "white" ? "green" : "white";
    });
}
.green { background: green; color: white; }
.white { background: white; color: black; }

#sales-list { border: 1px solid black; }
td { padding: 10px; border: 1px solid black; }
<table id="sales-list">
  <tr>
    <td class="white">Row 1 Col 1</td>
    <td class="white">Row 1 Col 2</td>
    <td class="white">Row 1 Col 3</td>
    <td class="white">Row 1 Col 4</td>
  </tr>
  <tr>
     <td class="white">Row 2 Col 1</td>
     <td class="white">Row 2 Col 2</td>
     <td class="white">Row 2 Col 3</td>
     <td class="white">Row 2 Col 4</td>
  </tr>
</table>