jQuery Image Fading Improved

by Sarah Milcetic on January 14th, 2010 in Website TipsNo Comments

Empire State Building, New YorkPortrait of JohannaPlaya Jaco, Costa Rica

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 improvement has the added benefit of only placing one image thumbnail in the HTML so there aren’t two thumbnails of each image when styles are disabled (and it just seems more syntactically correct, doesn’t it?).

Here’s the updated code:

HTML

<a class="zoom" href="large-image.jpg" style="background:url(color-thumb.jpg)">
<img class="off" src="bw-thumb.jpg" alt="Alt. Text" /></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);
});
});

Tags:

Leave a Reply