Is it possible to set transparency of any image in javascript? And how can I do that?
+5
A:
If using plain javascript this should work:
function SetOpacity( imageid, opacity ) {
var s= document.getElementById(imageid).style;
s.opacity = ( opacity / 100 );
s.MozOpacity = ( opacity / 100 );
s.KhtmlOpacity = ( opacity / 100 );
s.filter = 'alpha(opacity=' + opacity + ')';
}
Call by: SetOpacity('myImg', 50); //Half transparent
Nick Craver
2010-03-07 13:18:42
Would be more efficient to use a variable for opacity / 100: var decentBrowserOpacityValue = opacity / 100, OR let opacity be a value between 0-1, and use s.filter = 'alpha(opacity=' + (opacity*100) + ')';
KooiInc
2010-03-07 13:58:03
@Kooilnc - Possibly, is 1 variable assignment and 1 division cheaper than 3 divisions? I'm not sure, but I bet it's a infinitesimally small difference either way. In this case the vast majority of your work is the browser's rendering engine making the image transparent...the difference in variable assignment here is a micro-optimization that arguably makes the code less readable, so I tend to stay away in these simple cases.
Nick Craver
2010-03-07 14:06:07
@Nick Craver - it's micro indeed, but you know how it is: many micros tend to make a big one. Another point may be the 'microsoft orientedness' of the function, which I adressed in the OR clause. Well, it's a matter of taste I suppose.
KooiInc
2010-03-07 14:11:43
Is `MozOpacity` necessary? I use `opacity` and not `-moz-opacity` in my CSS all the time for Firefox and it works just fine.
fudgey
2010-03-07 14:24:17
@Kooilnc - If I wanted optimization and true cross-browser support, I'd use jQuery...which I do :) Normally I agree with optimizations pay off in the big picture, but not in this case, test for yourself: http://pastie.org/858174 Running this 500,000 times with 1.5 million divisons saves a whole 2 hundredths of a second :) In this case it's very micro, and not likely to add up to any appreciable benefit...and results in much less readable code. The 2 seconds it'll save someone trying to figure out what's going on is probably more than the function will ever save in it's lifetime :)
Nick Craver
2010-03-07 14:28:45
@fudgey - Just in case you want to support something as old as possible, for practical purposes, yes it could probably be omitted.
Nick Craver
2010-03-07 14:29:45