xelab
xelab

Reputation: 5

Swap table cell color on click

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).

Upvotes: 0

Views: 4193

Answers (2)

Marcel Korpel
Marcel Korpel

Reputation: 21763

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";
}

Upvotes: 2

rosscj2533
rosscj2533

Reputation: 9323

You need double equals for comparison:

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

or triple equals if you prefer.

Upvotes: 3

Related Questions