View Single Post
Old 11-07-2012, 12:09 AM   PM User | #2
sunfighter
Senior Coder

 
Join Date: Jan 2011
Location: Missouri
Posts: 2,391
Thanks: 18
Thanked 351 Times in 350 Posts
sunfighter is on a distinguished road
Here's a little help on trouble shooting:
Your code snippet:
Code:
function toggle() {
var x=document.getElementById("box").style;
if(x.color=="blue") {
x.color="#808080";
}

Read more at http://www.codingforums.com/showthread.php?p=1289328#PgYovAJysFTqm7fQ.99
Right after the first line
Code:
var x=document.getElementById("box").style;
Put
Code:
alert(x);die;
you will get exactly what you x is = [object CSSStyleDeclaration]

Not what you wanted. So you look things up and use
Code:
var x = document.getElementById("box").style.backgroundColor;
This time the alert says blue. Hurray!!

Here's the replacement for this section:
Code:
var x = document.getElementById("box").style.backgroundColor;
if(x == "blue")
document.getElementById("box").style.backgroundColor = "#808080";
}
If you use the alert trick again you will find that #808080 will give you an alert of rgb(128, 128, 128). Not what you wanted, AGAIN. So I found this function here http://haacked.com/archive/2009/12/2...gb-to-hex.aspx and added it.

Now I run it and again have a problem. it wont go to blue from green. So I change the order of the statements. Here is the final results with two functions.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
function colorToHex(color) {
    if (color.substr(0, 1) === '#') {
        return color;
    }
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);

    var red = parseInt(digits[2]);
    var green = parseInt(digits[3]);
    var blue = parseInt(digits[4]);

    var rgb = blue | (green << 8) | (red << 16);
    return digits[1] + '#' + rgb.toString(16);
};
function toggle()
{
	var x = document.getElementById("box").style.backgroundColor;
	if(x == "green")
	{
		document.getElementById("box").style.backgroundColor = "blue";
	}
	if(x == "blue")
	{
		document.getElementById("box").style.backgroundColor = "#808080";
	}
	if(colorToHex(x) == "#808080")
	{
		document.getElementById("box").style.backgroundColor = "green";
	}

}
</script>
</head>
<body>
<div id="box" style="background-color:blue;height:100px;width:300px;"></div>
<button onclick="toggle()">PUSH</button>
</body>
</html>

Last edited by sunfighter; 11-07-2012 at 12:46 AM..
sunfighter is offline   Reply With Quote
Users who have thanked sunfighter for this post:
Md8^h2nx (11-08-2012)