Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make fade transition 'crossfade'?

Tags:

jquery

I'm trying to get this to crossfade, but I'm not entirely sure how.

How can I make this jQuery method crossfade the images?

$('a.thumb').click(function () {
    var src = $(this).attr('href');
    if (src != $('div#imageDisplay > img').attr('src')) {
        $('div#imageDisplay > img').stop().animate({ opacity: '0', duration: 500 }, function () {
            $(this).attr('src', src);
        }).load(function () {
            $(this).stop().animate({ opacity: '1', duration: 500 });
        });
    }
    return false;
});
like image 237
Chase Florell Avatar asked Mar 16 '12 23:03

Chase Florell


People also ask

How do you cross fade in Premiere?

While editing in Premiere Pro, go to the Effects tab and click Audio Transitions > Crossfade. You'll have the option to apply: Constant Gain (a quick fade out and in) Constant Power (an even dissolve between both tracks)


1 Answers

A cross fade between two images (where one fades out and the other fades in) requires two images, each with their own animation. You can't do it with just one image tag. You will need two images. There are ways to use a background image for one of the images, but frankly that's just more complicated than using two <img> tags.

Here's some jQuery that implements a cross fade using two image tags:

// precache all images so they will load on demand
var imgs = [];
$('a.thumb').each(function() {
    var img = new Image();
    img.src = this.href;
    imgs.push(img);
}).click(function () {
    var oldImg = $("#fadeContainer img");

    var img = new Image();
    img.src = this.href;
    var newImg = $(img).hide();
    $("#fadeContainer").append(img);

    oldImg.stop(true).fadeOut(500, function() {
        $(this).remove();
    });
    newImg.fadeIn(500);
    return false;
});​

You can see it work here: http://jsfiddle.net/jfriend00/frXyP/

This is basically how it works:

  1. Get the current image
  2. Create new image object
  3. Fetch URL from the clicked on link and assign to new image tag
  4. Hide the new image
  5. Insert the new image into the fadeContainer
  6. Initiate fadeOut of existing image and fadeIn or new image
  7. When fadeOut finishes, remove that image so it's ready for the next cycle
like image 53
jfriend00 Avatar answered Sep 20 '22 21:09

jfriend00