Tuesday, June 29, 2010

jQuery crossfade

I spent a significant chunk of my time today looking for a simple way to crossfade one element into another on hover. Nothing I found was a great fit, and the one I eventually decided to try degraded until I realized I wasn't actually using any of the code I'd picked up. Here's what I ended up with:

$(document).ready(function() { $('.crossfade').css('position', 'relative'); $('.crossfade').children().css({position: 'absolute', top:0, left:0}).each(function(i) { $(this).css('z-index', i); }); $('.crossfade img:last-child').hide(); $('.crossfade').hover(function() {$(this).children('img:first-child').fadeOut(500); $(this).children('img:last-child').fadeIn(250);}, function() {$(this).children('img:first-child').fadeIn(250); $(this).children('img:last-child').fadeOut(500);}); });
The HTML is extra-simple:
<div class="crossfade"> <img src="image1.png" /> <!-- this is the regular image --> <img src="image2.png" /> <!-- this image shows up on hover --> </div>

That's it -- the only other thing you need to do is make sure your div is the right size. Very easy to plug into your page. Note that the fadeIn is faster than the fadeOut; this makes the transition smoother.

This script can easily be adapted to use other triggers or to work with non-image elements.

And an example – hover to try it out:

No comments:

Post a Comment