html element.style.color question
Solution 1
For a start this is wrong:
element.style.color == 'red'
should be "=" only. As you've written it this will be evaluated as an equality test, returning true or false.
Also, check what element.style.color
actually returns, it might not be "red" or "white" but an rgb
or hex
code and may be browser dependent.
Thirdly, your use of setInterval is wrong. See here for details on how to use this. You probably mean setTimeout:
setTimeout(function() { start_blink(elementId); }, 1000);
Solution 2
Your code is wrong in many ways... change the function to this instead:
function start_blink(elementId) {
//var red = "#ff0000";
//var white = "#000000";
var element = document.getElementById(elementId);
element.style.color = (element.style.color == 'red') ? 'white' : 'red';
//document.write(element.style.color);
blinkIntervalID = window.setTimeout(function() {
start_blink(elementId);
}, 1000);
}
And call it for the first time like this:
window.onload = function() {
start_blink('MySpan');
};
Solution 3
As has been pointed out already, you need to make sure that when you're setting a value that you use =
rather than ==
which is used for comparing values.
Secondly, checking the colour value is going to be rather inconsistent depending on how the browser decides to interpret the colour (rgb, hex etc).
What you can do is count the number of times the method is executed and decide based on that.
Here's an example: http://jsfiddle.net/nUvJV/
Here, instead of checking the colour we simply check the count:
item.style.color = (blinkCounter % 2)? '#000' : '#f00';
Michael
Updated on June 04, 2022Comments
-
Michael almost 2 years
I'm writing some javascript code to make some text blink but it wont work.
function start_blink(elementId) { //var red = "#ff0000"; //var white = "#000000"; var element = document.getElementById(elementId); element.style.color == 'red'; if(document.getElementById) { element.style.color = (element.style.color == 'red') ? 'white' : 'red'; //document.write(element.style.color); blinkIntervalID = setInterval(start_blink, 1000, elementId); } }
It only turns red, never white, meaning that
element.style.color == 'red'
always returns as false.
Why is this the case?