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 biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating a simple toggle function

Status
Not open for further replies.

guttyguppy

Programmer
Feb 15, 2008
2
US
Hi, first post here!

I'm doing an art project and having trouble. I want a div's background color to turn black if it's white, and white if it's black. Here's my code:

Code:
function toggle(obj) {
	var el = document.getElementById(obj);
	el.style.backgroundColor = (el.style.backgroundColor != 'rgb(0,0,0)' ? 'rgb(0,0,0)' : 'rgb(255,255,255)' );
}

<div id="a8" onClick="toggle('a8');"></div>
The box turns black, but doesn't return to white when it's clicked again. What am I doing wrong? Thanks for any advice.
 
The rgb string returned in Firefox has spaces after the commas, but in IE it isn't. You're comparing exact strings, not numbers here, so will have to adjust your code appropriately to handle both formats.

This works for me:
Code:
function toggle(obj)
{
var el = document.getElementById(obj);
var bgcolor = el.style.backgroundColor.replace(/ /g, '');

if (bgcolor != 'rgb(0,0,0)')
  {

  el.style.backgroundColor = 'rgb(0, 0, 0)';
  }
else
  {
  el.style.backgroundColor = 'rgb(255, 255, 255)';
  }
}

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top