How to change image opacity on mouseover using jQuery

Images are undoubtedly the most attractive element of the page. And images with some cool effects make them more powerful and attractive. One of the effect on the image, is to make ittransparent and play with transparency with mouse gestures. So in this post, I will show youhow to change image opacity on mouseover and reset it on mouseout using jQuery.


First when image gets load on the page, set its opacity to 0.5 so that it looks transparent on load.
1//Code Starts
2$("#imgDemo").css("opacity", 0.5);
3//Code Ends
Now using "hover" event, just change the opacity of image to 1.0 on mouseover and 0.5 on mouseout. Read more about "hoverhere.

You can set the opacity property directly, but I have use animate method. The jQuery animate method allows create animation effects on any numeric CSS property. It also takes duration (in millisecond) as parameter. Thus the below jQuery code will apply opacity property in 5 milliseconds.
1//Code Starts
2$("#imgDemo").hover(function() {
3        $(this).animate({opacity: 1.0}, 500);
4    }, function() {
5        $(this).animate({opacity: 0.5}, 500);
6    });
7//Code Ends
So, the complete code looks like,
01//Code Starts
02$(document).ready(function() {
03    $("#imgDemo").css("opacity", 0.5);
04    $("#imgDemo").hover(function() {
05        $(this).animate({opacity: 1.0}, 500);
06    }, function() {
07        $(this).animate({opacity: 0.5}, 500);
08    });
09});​
10//Code Ends
See result below. 

0 comments:

Post a Comment

Don't Forget to comment