btrballin btrballin -5 years ago 116
HTML Question

onclick() not working on first click for HTML table

So I made a 5x5 grid using HTML's

element. I want each cell to turn red when it is clicked and revert back to white when it isn't. It looks like it won't detect the first ever click on each cell. Once the first click has been triggered, it alternates from red and white normally under 1 click, but when you click it for the very first time for that instance, it does not respond. Why is it that a cell responds on the first click after it has been clicked on twice, but doesn't respond on the first click if it has never been touched before?

HTML snippet:

<table type="board">
<td id="r1-c1" onclick="changeColor('r1-c1')"></td>
<td id="r1-c2" onclick="changeColor('r1-c2')"></td>
<td id="r1-c3" onclick="changeColor('r1-c3')"></td>
<td id="r1-c4" onclick="changeColor('r1-c4')"></td>
<td id="r1-c5" onclick="changeColor('r1-c5')"></td>

The snippet is nested inside body and 2 div tags respectively.
JS code:

function changeColor(id)
if(document.getElementById(id).style.backgroundColor == "white"){
document.getElementById(id).style.backgroundColor = "red";
document.getElementById(id).style.backgroundColor = "white";

Answer Source

Use the following code. It will work.

function changeColor(id){
    if( (document.getElementById(id).style.backgroundColor == "white") || (document.getElementById(id).style.backgroundColor == "")){
        document.getElementById(id).style.backgroundColor = "red";  
        document.getElementById(id).style.backgroundColor = "white";

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download