jQuery Image Fading Improved

After thinking about it a little more, I was able to shorten my code significantly and keep the same effect of a b+w image fading into a color image when rolled over. This has the added benefit of only placing one thumbnail in the HTML, so there aren’t two thumbnails of each image when styles are disabled.

Here’s the updated code:

HTML (in a PHP loop)


$html .= "<a class=\"zoom\" rel=\"{$category}\" href=\"photo/{$category}/i/{$name}.jpg\" style=\"background:url(photo/{$category}/t_on/{$name}.jpg);\" ><img class=\"off\" src=\"photo/{$category}/t_off/{$name}.jpg\" alt=\"$title\" /></a>";

CSS


.zoom {
display:inline-block;
width:213px;
height:142px;
margin-bottom:10px;
}
.zoom + .zoom {
margin-left:10px;
}

JavaScript


$(document).ready(function(){
var mySpeed=750; //miliseconds

$(".zoom img").hover(function(){
$(this).fadeTo(mySpeed, 0);
},function(){
$(this).fadeTo(mySpeed, 1.0);
});
});

Leave a Reply