0

I want to be able to click a table cell, have it switch to color1, and then on the next click have it switch to color2, then back to color1... and so on.

function cSwap(cell){ 
 if (cell.style.backgroundColor = "#00000F")
 {
  cell.style.backgroundColor = "#F00000";
 }
 else if (cell.style.backgroundColor = "#F00000")
 {
  cell.style.backgroundColor = "#00000F";
 }
}

Right now, it only changes to the first color, and subsequent clicks do nothing.

The cells of the table each look like this:

<td classname='t' onclick='cSwap(this);' width='100' height='100' id='nw'><a href="" id="nw"></a></td>

...which'll be CSS once I get everything working (beside the point).

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
xelab
  • 5
  • 1
  • 2

2 Answers2

3

You need double equals for comparison:

  if (cell.style.backgroundColor == "#00000F")

or triple equals if you prefer.

Community
  • 1
  • 1
rosscj2533
  • 9,195
  • 7
  • 39
  • 56
2

Even with double equal signs it won't work. backgroundColor will change its string to an rgb value in Firefox when its value is retrieved (and other browsers may behave alike).

A solution is to put those colors in a class and switch the table cell's class on click. That's also more general, as you can easily change the colors.

CSS:

.t  { background: #00f }
.t2 { background: #f00 }

Also, the attribute is called class, not classname. And remember that you cannot have two elements with the same ID:

<td class='t' onclick='cSwap(this)' width='100' height='100'><a href=""></a></td>
<td class='t' onclick='cSwap(this)' width='100' height='100'><a href=""></a></td>

And the accompanying script:

function cSwap(cell){  
    if (cell.className == "t")
        cell.className = "t2";
    else if (cell.className == "t2")
        cell.className = "t";
}
Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80