I checked, and though I found a similar answer from 3 years ago (button turns background green), the answer was not quite satisfactory, as the top respondent basically said, "Works fine for me".
My Document: I have a table of four white boxes. When a box is clicked, the box's background turns blue. If the background is already blue, it turns white.
My Problem: The top-left box in the table requires only 1 click to change color, but the other 3 blocks require double-clicks. The only difference between the single-click block and the double-click blocks is that the background-color is explicitly stated inline for the first block, while the double-click boxes have their background-color stated in the head of the document.
My Question: Why is this happening? It is almost as though for the 3 blocks requiring double-click, their background color is not "white" to begin with, which would lead my JavaScript to color them white on the first click before coloring them blue on the second click. That is my best guess. Your thoughts?
<!DOCTYPE html>
<html>
<head>
<title>Check Answers Test</title>
<style> table, th, td {border: 2px solid black; text-align: center; background-color: white;} </style>
<script>
function myScript(element){
if (element.style.backgroundColor != "white"){
element.style.backgroundColor = "white";
}else{
element.style.backgroundColor = "#99ccff";
}
}
</script>
</head>
<body>
<table>
<thead>
<tr>
<td onclick="myScript(this)" style="background-color:white;">1</td>
<td onclick="myScript(this)">2</td>
</tr>
</thead>
<tbody>
<tr>
<td onclick="myScript(this)">象</td>
<td onclick="myScript(this)">象</td>
</tr>
</tbody>
</table>
</body>
</html>
EDIT: Someone suggested below I reverse the logic for the color change (change blue if not blue). However, I did it this way my first time coding the document, and I cannot get the boxes to return to "white" after turning blue. Observe:
<!DOCTYPE html>
<html>
<head>
<title>Check Answers Test</title>
<style> td {border: 2px solid black; text-align: center; background-color: white;} </style>
<script>
function myScript(element){
if (element.style.backgroundColor != "#99ccff"){
element.style.backgroundColor = "#99ccff";
}else{
element.style.backgroundColor = "white";
}
}
</script>
</head>
<body>
<table>
<thead>
<tr>
<td onclick="myScript(this)" style="background-color:white;">1</td>
<td onclick="myScript(this)" >2</td>
</tr>
</thead>
<tbody>
<tr>
<td onclick="myScript(this)" >象</td>
<td onclick="myScript(this)" >象</td>
</tr>
</tbody>
</table>
</body>
</html>