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 it transparent and play with transparency with mouse gestures. So in this post, I will show you how 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.

//Code Starts
$("#imgDemo").css("opacity", 0.5);
//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 "hover" here.

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.

//Code Starts
$("#imgDemo").hover(function() {
        $(this).animate({opacity: 1.0}, 500);
    }, function() {
        $(this).animate({opacity: 0.5}, 500);
    });
//Code Ends

So, the complete code looks like,

//Code Starts
$(document).ready(function() {
    $("#imgDemo").css("opacity", 0.5);
    $("#imgDemo").hover(function() {
        $(this).animate({opacity: 1.0}, 500);
    }, function() {
        $(this).animate({opacity: 0.5}, 500);
    });
});?
//Code Ends

See result below.

See Complete Code

Feel free to contact me for any help related to jQuery, I will gladly help you.