Manipulating image opacity in browsers
Note: Tutorial last updated May 12th, 2015
All modern browsers support the manipulation of elements' opacity, either using CSS or JavaScript. And to borrow from the vocabulary of a surfer dude, it's totally rad!
FYI, "opacity" refers to transparency; the lesser the opacity of an element, the more transparent it is.
Using CSS to define
opacity
We use CSS to define the initial degree of the opacity of an element:
<IMG style="opacity:0.5" src="test.gif">
Valid range of values for opacity
is from 0 to 1,
where lesser equates to more transparency. See for yourself the
difference:
|
|
Changing
opacity on the fly
Interesting effects arise when we have dynamic access to the opacity property, which luckily is the case here. The syntax is:
object.style.opacity=number (valid range: 0 to 1)
How about a quick opacity change onMouseover?
<IMG style="opacity:0.6" src="alta.gif" onMouseover="this.style.opacity=1" onMouseout="this.style.opacity=0.6">
For simple event driven changes to an element's opacity
(or any other style for that matter), such as when moving the mouse over
an image, can be accomplished using CSS only, by using CSS's pseudo
classes such as ":hover
". The following sets all images on
the page to an initial opacity of 0.5, and onMouseover, back to full
opaqueness of 1:
<style> img{ opacity: 0.5; } img:hover{ opacity: 1; } </style>
-Example: Fading pumpkin
To round off our tutorial, the below image continuously fades incrementally between 0.3 (30%) and 0.6 (60%) opacity:
<img id="test" src="pump.gif" width=116 height=123 style="-moz-opacity:0.3" /> <script type="text/javascript"> opacity=0 //opacity of image var increase=1 //increase opacity indicator var decrease=0 //decrease opacity indicator function fade(){ if (opacity<0.6&&increase) opacity+=0.05 else{ increase=0 decrease=1 } if (opacity>0.3&&decrease) opacity-=0.05 else{ increase=1 decrease=0 } document.getElementById("test").style.opacity=opacity } setInterval("fade()",100) </script>
Spookay!