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