Changing Image Opacity on MouseOver using jQuery

Have you played the online memory game where an image appears when you hover over it and disappears on hover out. You have 20 images to view in 30 seconds and the one remembering the most wins. Well I wont be creating the game over here, but I will show you how to change the opacity of the image when the mouse if hovered over it.

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title></title>
<
style type="text/css">
img
{
opacity:0.0;
filter:alpha(opacity=0);
}
</style>
<
script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

<
script type="text/javascript">
$(document).ready(function() {
$('img').each(function() {
$(this).hover(function() {
$(this).stop().animate({ opacity: 1.0 }, 500);
},
function() {
$(this).stop().animate({ opacity: 0.0 }, 500);
});
});
});

</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
img alt="" src="images/emo.jpg" />
<
img alt="" src="images/icon068.gif" />
<
img alt="" src="images/icon260.jpg" />
</
div>
</
form>

</
body>
</
html>

Initially, all the images have an opacity of 0 – being completely transparent. When the mouse hovers over each one of them, the image is displayed, one at a time. The image disappears when the mouse hovers out. You can even use this technique to create a cool UI effect in your applications.

image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

Anonymous said...

Yes! Thanks, I was lookin for this.

Anonymous said...

thanks nice tip

Anonymous said...

Thanks! Just what I was looking for, but in reverse (i.e. alpha decreases on mouseover).