Setting opacity of html elements in different browsers

merveotesi picture merveotesi · Dec 16, 2011 · Viewed 45.8k times · Source

I need to set an HTML <img src=""/> object's opacity in JavaScript in all the browsers.

In Firefox I do it with line:

imageobject.style.MozOpacity=opacity/100;

What is the proper javascript code to set the opacity of an element in different browsers?

Answer

Dennis picture Dennis · Dec 16, 2011
img.style.opacity = .5; //For real browsers;
img.style.filter = "alpha(opacity=50)"; //For IE;

You don't need to sniff the user agent, just set both values as browsers will ignore the irrelevant one.