Click here to Skip to main content
15,898,752 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
<!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
Posted
Updated 4-Mar-14 23:14pm
v2

This is solved here: http://jsbin.com/qusawaro/3/[^]

[Please accept/up-vote answers or solutions that work for you to encourage participation]
 
Share this answer
 
There are three issues with this code.

1) Your comparison in the if statement, if (x.style.color="#000000"), is not a comparison but an assignment, you're missing one = to make it a comparison. What basically happens is that the color property would get a value assigned, and then the result of that assignment (the value itself) is tested in the if statement, so it's always true.
2) After setting x.style.color to #000000, the color is not #000000 but rather rgb(0, 0, 0) (even the spaces are important here)
3) Initially the color is not set, so x.style.color doesn't return anything. It did turn red, because of the flawed if statement.

So to make the code work, you'll get something like this:
JavaScript
function myFunction()
{
    x=document.getElementById("demo") 
    if (!x.style.color || x.style.color=='rgb(0, 0, 0)')
    {
        x.style.color="#FF0000";
    }
    else
    {
        x.style.color="#000000";
    }
}
 
Share this answer
 
v2
Different browsers 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;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900