Q:

javascript color change not working

<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript</h1>

<p id="demo">
JavaScript can change the style of an HTML element.
</p>

<script>
function myFunction()
{ 
  x=document.getElementById("demo") 
  if (x.style.color="#000000")
  {
    x.style.color="#FF0000"; 
    //alert(x.style.color);
  }
  else
  {
    x.style.color="#000000"; 
    //alert(x.style.color);
  }
}
</script>

<button type="button" onclick="myFunction()">Click Me!</button>

</body>
</html> 

above code not working second time Click 
i tried with many different colors 
x.style.color not accepting in else block
else block not working 
please help

A:

A) use == instead of = in the if condition statement 
B) check against rgb color notation and not hex
function myFunction() {

    x = document.getElementById("demo");
    if (x.style.color == "rgb(0, 0, 0)") {
        x.style.color = "#FF0000";
    } else {

        x.style.color = "#000000";
    }
}

http://jsfiddle.net/4QUWq/1/

A:

Different browsers might return different values for the same colors. You better use different logic to toggle the colors. What I suggest, using pure JavaScript, is this:
var demoColors = ["#000000", "#FF0000"];
var demoFlag = true;
function myFunction()
{ 
    var demo = document.getElementById("demo");
    demo.style.color = demoColors[+demoFlag]
    demoFlag = !demoFlag;
}

Live test case.

