My last little jQuery tutorial was an alternative to using CSS to create an image change on a mouseover. Now I want to take that one step further and add a fade effect. For my example, I am going to make a black and white image fade into a color image. To achieve this effect I am going to introduce the animate function. There are tons of possibilities in regards to jQuery’s animate function, but for this tutorial, I’m going to keep it simple by just using it to do one thing.

First things first, download jQuery. Grab the Production minified version off of their site. Next, get two images. I used the following.

cbavota-bwcbavota


Add the jQuery script between your head tags.

<script type='text/javascript' src='http://yoursite.com/jquery.js'></script>

Here is the function.

<script type='text/javascript'>
$(document).ready(function(){
$("img.a").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
});

});
</script>

Here is the CSS.

<style>

div.fadehover {
	position: relative;
	}

img.a {
	position: absolute;
	left: 0;
	top: 0;
	z-index: 10;
        }
	
img.b {
	position: absolute;
	left: 0;
	top: 0;
	}

</style>

And here is the body code.

<div class="fadehover">
<img src="cbavota-bw.jpg" alt="" class="a" />
<img src="cbavota.jpg" alt="" class="b" />
</div>

All together you got something that looks like this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery Hover Effect</title>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function(){

$("img.a").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
});

});
</script>
<style>
div.fadehover {
	position: relative;
	}

img.a {
	position: absolute;
	left: 0;
	top: 0;
        z-index: 10;
	}
	
img.b {
	position: absolute;
	left: 0;
	top: 0;
	}
</style>
</head>

<body>
<div class="fadehover">
<img src="cbavota-bw.jpg" alt="" class="a" />
<img src="cbavota.jpg" alt="" class="b" />
</div>
</body>
</html>

Test it out below:

NOTE: If you are using jQuery with WordPress, you need to replace all the dollar signs ($) with the word jQuery due to other Javascript libraries that use the dollar sign.