Change Image Opacity Easily Using CSS or JS

by Hiroshi on January 23, 2009

in CSS, Javascript, Tricks

We can simply use CSS alone to reproduce opacity effect that have traditionally been done using scripting. The advantage of looking to CSS instead is obvious – much more lightweight and easier to implement. We can use this method where we need to use a dim or faint version of image, while when some one places mouse over it, then image comes sharp, clear and bright.

Use the following code in head section of web page.

<style type="text/css">
.opacityit img{
filter:progid:DXImageTransform.Microsoft.Alpha(opacity=40);
-moz-opacity: 0.4;
}
.opacityit:hover img{
filter:progid:DXImageTransform.Microsoft.Alpha(opacity=100);
-moz-opacity: 1;
}
</style>

Use the following code in body where the image is located.

<a href="#" class="opacityit"><img border="0" src="email.gif" /></a>

By this method image loads kind of blur in background and in light colors, but when some one places mouse over it. It becomes sharp.

Simple Opacity

We are using JavaScript to change the opacity of an image here. The technique works in both IE4+ and NS6+, and can be used to create some interesting “fading” effects. Here is the simple way to just place an image with opacity.

<img src="image.gif" style="filter:alpha(opacity=50); -moz-opacity:0.5">

In -moz-opacity:0.5 accepted range of values are 0 to 1, where 0 would make the image disappear and in alpha(opacity=50) range is between 1 to 100. We have combined the code both for IE and Mozilla for code compatibility.

We can also alter the opacity of image using javascript.

Head section code

<script>
function alteropacity(imageobject, opacity){
 if (navigator.appName.indexOf("Netscape")!=-1
  &&parseInt(navigator.appVersion)>=5)
    imageobject.style.MozOpacity=opacity/100
 else if (navigator.appName.indexOf("Microsoft")!= -1 
  &&parseInt(navigator.appVersion)>=4)
    imageobject.filters.alpha.opacity=opacity
}
</script>

Body Section Code

<img src="image.gif" style="filter:alpha(opacity=50); -moz-opacity:0.5" 
onMouseover="alteropacity(this, 100)" onMouseout="alteropacity(this, 30)">

Related Posts

Previous post:

Next post: