Reputation: 99
Why does the following code not toggle the element color when the button is clicked? My assumption is that the style.color
is returning an object of sorts and not a string. What would be the best way to correct this issue?
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
asd=document.getElementById("demo")
if (asd.style.color!="rgb(255,0,0)")
asd.style.color="rgb(255,0,0)";
else
asd.style.color="rgb(0,0,0)";
}
</script>
</head>
<body>
<h1>My First JavaScript</h1>
<p id="demo">
JavaScript can change the style of an HTML element.
</p>
<button type="button" onclick="myFunction()">Click Me!</button>
</body>
</html>
Upvotes: 1
Views: 2167
Reputation: 94
if(document.getElementById("color1").style.color!="#FF0000")
{
document.getElementById("color1").style.color="#FF0000";
}
else
{
document.getElementById("color1").style.color="#FFFFFF";
}
Try this hope will work.
Upvotes: 0
Reputation: 43823
Browser vendors return various versions of the style.color
value.
From a quick test on this very page (which by pasting the code into the JavaScript console you can see for yourself):
"#888"
for document.querySelectorAll('div[class="user-details"]')[0].currentStyle.color
"rgb(136, 136, 136)"
for document.defaultView.getComputedStyle(document.getElementsByClassName('user-details')[0], null)['color']
I'm fairly sure I've seen a previous version of one browser return "rgb(136,136,136)"
(without spaces) before.
One way to work around this inconsistency is to define the colors in CSS classes instead and toggle between the class names.
A very simple demonstration of this would be the following code. However this is very simple as it would only work if the element has a single CSS class. You would need to write a utility function to check if an element has a class applied and functions to add and remove a single class from a list if your design needed multiple classes. These have been written many times before so there are plenty of examples (search for javascript hasclass addclass removeclass
) or use an existing utility library.
CSS
.on {
color:#f00;
}
.off {
color:#000;
}
JavaScript
function myFunction() {
var e = document.getElementById("demo");
e.className = e.className === 'on' ? e.className = 'off' : e.className = 'on';
}
HTML
<h1>My First JavaScript</h1>
<p id="demo" class="off">
JavaScript can change the style of an HTML element.
</p>
<button type="button" onclick="myFunction()">Click Me!</button>
Upvotes: 3
Reputation: 21
The browser sets an inline rgb color with spaces after the commas, so your if statement has to match the string exactly. Adding spaces after your commas in your rgb value will make this work.
if (asd.style.color!="rgb(255, 0, 0)")
Upvotes: 0