Hi there. I have a script that animates opacity but if the opacity has not been previously set then it just disappears. I just wondered if there was a way to check if the opacity has been set. Thanks in advance!
+1
A:
Generally, CSS properties that aren't set return an empty value in JavaScript.
Update: It appears that element.style
will only return values that were previously set via JavaScript or specified in the inline style. To get the true value of a CSS property, you need to use the so-called "computed style" of an element.
Here's a function (copied from quirksmode) that does this:
function getStyle(el,styleProp)
{
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
However, this will return 1.0
(the default value) if the opacity has not been set, so there's really no way to know if the opacity was actually defined in CSS or not.
casablanca
2010-10-27 20:45:12
I think you'd be better off with isNaN( element.style.opacity ).
Christopher W. Allen-Poole
2010-10-27 20:48:07
@Christopher W. Allen-Poole: What if it's 0.0?
Robusto
2010-10-27 20:50:08
Nope, checking if it is an empty string and running it through the isNaN function still return 0.
Wolfy87
2010-10-27 20:51:11
@Christopher W. Allen-Poole: I don't think it's any different, considering the value can only be empty or a number. @Robusto: 0.0 is still considered a number.
casablanca
2010-10-27 20:52:12
Does anyone know what a not set opacity will return? Or a method of determining what it returns?
Wolfy87
2010-10-27 20:57:17
@Wolfy87: I was wrong, see my updated answer.
casablanca
2010-10-27 21:10:44
@casablanca You're right, it doesn't practically matter here. @Wolfy87 Also correct, that should have been isNaN( parseInt( element.style.opacity ) ); @robusto 0.0, "0.0" and 0/10 are all Numbers. (Though if you call Object.prototype.toString.apply( "0.0" ) it will display [Object String]").
Christopher W. Allen-Poole
2010-10-27 21:12:40
Well casablanca's function did not work for me, it seems a bit browser specific too. And using isNaN(parseInt(element.style.opacity)) did not do the trick either.
Wolfy87
2010-10-27 21:27:45
@Wolfy87: What problem are you having? It seems to work fine for me. It assumes that `el` is the ID of an element, so you would call it as `getStyle('some_id', 'opacity')`.
casablanca
2010-10-27 21:31:28
Okay, it *was* not working, but after playing about with my code quite a bit I have managed to get it working, thank you very much for that. All sorted!
Wolfy87
2010-10-27 21:47:15
One thing: In newer versions of Firefox, `getComputedStyle` gets the unclicked version of a link if there's an `a` and an `a:visited`.
Hello71
2010-10-27 22:37:23