Image Cross Fade Transition with jQuery
Join the DZone community and get the full member experience.
Join For Freea frequent query and request i receive, and have had as a developer myself is:
“how can i fade one image into another?”.
in particular, nathan wrigley of pictureandword.com , needed a method which would fade one image into another on a mouse roll over event, and then slowly fade back once the mouse has moved of the image.
image rollovers were the staple javascript nugget of the 90s, and for a lot of javascript developers i know, one of the starting points that led to their passion for the javascript language. today, rollovers are a no-brainer, whether with css or the simplest of javascript:
$(function () { $('img.swap').hover(function () { this.src="images/sad.jpg"; }, function () { this.src="images/happy.jpg"; });});
today’s challenge is the rollover transition!
watch the complete screencast ( alternative flash version )
(quicktime version is approx. 20mb, flash version is streaming)
how to approach the problem
there are a few different ways in which this problem can be solved (and i’d love to hear alternative methods via the ).
here are the different approaches i’m going to go through:
- two image
- single image
- pure css
the key to all of these techniques is how the rendered markup (i.e. what the browser finally sees) is arranged: all of which are very similar. essentially, the end image for the transition must sit absolute
ly in the same position as the starting image. it’s also worth keeping in mind that the images we fade between should be the same size (height & width-wise).
note: all three of these techniques have a caveat: styling the start or end image may cause the effect to break. i would recommend wrapping the image in a div
or span
and styling that element, as it will require less changes to the javascript. either way: it is always best to test in the targeted browsers.
two image technique
i should start by crediting karl swedberg who runs learning jquery . he solved nathan’s transition problem using the following technique. karl’s method starts with the two images in the markup: both the start and end images. they are contained in a div
and the end image is contained in a further div
with absolute
positioning.
it is important to note that this technique works best for absolutely position images. changing the div.fade
to position: relative
means the div
element remains as a block
element, and div
will stretch the width of it’s container element (defaulting to 100%).
view the working example and the source
html
<div class="fade"> <a href="/info.html"><img src="start.jpg" /></a> <div> <a href="/info.html"><img src="end.jpg" /></a> </div> </div>
css
obviously if i had more than one fading image, i would use an id or alternative class to position the top
and left
css properties.
.fade { position: absolute; top: 100px left: 100px } .fade div { position: absolute; top: 0; left: 0; display: none; }
jquery
// when the dom is ready: $(document).ready(function () { // find the div.fade elements and hook the hover event $('div.fade').hover(function() { // on hovering over, find the element we want to fade *up* var fade = $('> div', this); // if the element is currently being animated (to a fadeout)... if (fade.is(':animated')) { // ...take it's current opacity back up to 1 fade.stop().fadeto(250, 1); } else { // fade in quickly fade.fadein(250); } }, function () { // on hovering out, fade the element out var fade = $('> div', this); if (fade.is(':animated')) { fade.stop().fadeto(3000, 0); } else { // fade away slowly fade.fadeout(3000); } }); });
single image technique
this takes the two image technique further. i like the idea that we should let javascript add the sugar to the markup - in that we should really only want an image tag, and using some method, know which image we want to fade to.
this technique allows us to insert the image in the markup as we would if there were no transition effect, and the image can be inline, rather being positioned absolutely. we are going to use the background-image
css property to specify the target image to fade to.
view the working example and the source
html
<img class="fade" src="images/who.jpg" style="background: url(images/who_ro.jpg);" />
css
other than the inline background image - none is required. you can also apply the background-image
using classes if you like. if we wanted to absolutely position the image, or float: right
for instance, the best way to do this (if we want to keep the transition), would be to wrap it in a div
and style that element.
jquery
using jquery, we execute the following tasks:
- wrap the image in a
span
- insert a new image, whose source is the
background-image
of our start image - position the new image so that sits directly behind the starting image
- bind the hover event to start the effect
// create our transition as a plugin $.fn.crossfade = function () { return this.each(function () { // cache the copy of jquery(this) - the start image var $$ = $(this); // get the target from the backgroundimage + regexp var target = $$.css('backgroundimage').replace(/^url|[\(\)]/g, '')); // nice long chain: wrap img element in span $$.wrap('<span style="position: relative;"></span>') // change selector to parent - i.e. newly created span .parent() // prepend a new image inside the span .prepend('<img>') // change the selector to the newly created image .find(':first-child') // set the image to the target .attr('src', target); // position the original image $$.css({ 'position' : 'absolute', 'left' : 0, // this.offsettop aligns the image correctly inside the span 'top' : this.offsettop }); // note: the above css change requires different handling for opera and safari, // see the full plugin for this. // similar effect as single image technique, except using .animate // which will handle the fading up from the right opacity for us $$.hover(function () { $$.stop().animate({ opacity: 0 }, 250); }, function () { $$.stop().animate({ opacity: 1 }, 3000); }); }); }; // not only when the dom is ready, but when the images have finished loading, // important, but subtle difference to $(document).ready(); $(window).bind('load', function () { // run the cross fade plugin against selector $('img.fade').crossfade(); });
pure css technique
if i’m honest, this final technique is a bit cheeky - but still valid. it uses css animations currently only available in safari 3 (and webkit). however, this is a great example of how to the leverage css using an iphone, in place javascript. the html is the same rendered html from the single image technique - but it requires zero javascript.
html
<span style="position: relative;"> <img src="images/who_ro.jpg" /> <img style="position: absolute; left: 0px;" src="images/who.jpg" class="fade" /> </span>
css
although this is only supported in safari 3, the roll over still works in firefox (and could work in ie7 - though not ie6 because :hover
only works on anchors) - because it’s changing the image’s opacity on :hover
.
img.fade { opacity: 1; -webkit-transition: opacity 1s linear; } img.fade:hover { opacity: 0; }
taking it further
i’ve taken the single image technique further in to a complete plugin. it’s designed to allows us to pass options to control the type of bind, delays, callbacks and tests before running the animation.
you can see the plugin in action in this simple memory game i put together quickly. it pulls the latest photos from flickr , shuffles them, and then sets your memory skills to work. it’s obviously just a quick prototype - and i’m not sure what happens when you go beyond level 5! enjoy.
Published at DZone with permission of $$anonymous$$, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments