Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Setting and getting table cell background colors

Status
Not open for further replies.

shteev

Programmer
Jul 15, 2003
42
0
0
I'm writing a Jscript version of mastermind, code here:
http://mysite.wanadoo-members.co.uk/shteevshouse/games/MindMaster.html

I'm trying to fix it so that it works for Firefox as well as Opera and IE.

Each cell can be one of six colors. When I click on a colored cell, I want it's color to advance by 1 through the color sequence: red, green, blue, cyan, yellow, purple.

To do this I need to check the background color of the cell; but if I check <cell>.style.background different browsers return different values.

E.g. if i set a cell background color to 'red', and then check the value of <cell>.style.background,

IE will return 'red'
Opera will return '#ff0000'
Firefox will return 'rgb(255, 0, 0) none repeat scroll 0% 0%'

What functions can I use to ensure cross-browser functionality?
 
The proper DOM/style setting is "backgroundColor", not "background".

AFAIK Opera tends to convert color names into RGB... this works in O7.5/FF/IE6:
Code:
<table border="1" width="200">
<tr height="50">
	<td onclick="rotateColor(this)">&nbsp;</td>
	<td onclick="rotateColor(this)">&nbsp;</td>
	<td onclick="rotateColor(this)">&nbsp;</td>
	<td onclick="rotateColor(this)">&nbsp;</td>
</tr>
</table>	

<script language="javascript">
function rotateColor( oCell )
{	aColors = [ "#ff0000", "#00ff00", "#0000ff", "#00ffff", "#ffff00", "#ff00ff" ];
	sColor = oCell.style.backgroundColor;
	iPos = -1
	
	if (sColor)
		for( iPos++; iPos< aColors.length && aColors[iPos]!= sColor ; iPos++ );
		
	alert( sColor )	

	iPos = (iPos + 1) % aColors.length
	oCell.style.backgroundColor = aColors[iPos];	
}
</script>
 
I'm running that code in Firefox 1.0PR and it's not working properly; cell colors rotate as far as green, and then stop changing.

It returns a value in the style 'rgb(255, 0, 0)' which will not test positively against '#ff000'
 
Argh... It appears that IE returns value "as is", Opera converts to "#xxyyzz" and FF to "rgb(x, y, z)".
 
Indeed. I notice that you CAN set the background color with a cell with this command in all 3 browsers:

oCell.style.backgroundColor = 'rgb(255, 0, 0)'

but if you test it's value you still get 3 different return values:

IE returns 'rgb(255,0,0)' (no spaces)
Opera returns '#ff0000'
Firefox returns 'rgb(255, 0, 0)' (with spaces)

Surely there must be a function of some sort with which I can test the background color of a cell?

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top