James Lawson
James Lawson

Reputation: 419

Firing more than one jQuery animation at once

I'm finding that my animations are taking to long to perform (into each other) - is it actually possible to set more than one off at a time?

Published copy http://colourednoise.co.uk/closing/

What's currently happening: Fade In > Expand > Fade Out - however the first two steps seem to stall a little.. can I merge them? I.e get it to fade slightly whilst it's starting to expand to give an overall smoother experience.

jQuery(document).ready(function() {
    positionElements();

    var fontSize = 60,
        goodbyeFadeIn = 1000,
        goodbyeAnimation = 1500,
        goodbyeFadeOut = 1000;

    jQuery('#goodbye').fadeIn(goodbyeFadeIn, function() {
        jQuery(this).animate({
            fontSize: fontSize
        }, goodbyeAnimation, function() {
            jQuery(this).fadeOut(goodbyeFadeOut, function() {

                jQuery('#content').fadeIn();
            });
        });
    });
});

jQuery(window).resize(positionElements);

function positionElements() {
    var documentWidth = jQuery(document).width(),
        documentHeight = jQuery(document).height(),
        goodbyeWidth = jQuery('#goodbye').width(),
        goodbyeHeight = jQuery('#goodbye').height(),
        contentWidth = jQuery('#content').width(),
        contentHeight = jQuery('#content').height();

    jQuery('#goodbye').css({
        left: (documentWidth / 2) - (goodbyeWidth / 2),
        top: (documentHeight / 2) - (goodbyeHeight / 2)
    });

    jQuery('#content').css({
        left: (documentWidth / 2) - (contentWidth / 2),
        top: (documentHeight / 2) - (contentHeight / 2)
    });
}

The other reason for me wanting to get the fade in animation to mix with the expand is because I'm finding the expand animation to be very .. jittery?

Upvotes: 0

Views: 198

Answers (1)

James Montagne
James Montagne

Reputation: 78750

Animations in jquery have an option of queue which defaults to true. If false, the animations will run immediately and not wait for the previous to finish. You can do something like this:

$('#goodbye').fadeIn({duration: goodbyeFadeIn, queue: false}) // run outside of the queue
             .animate({  // animate queued, but runs immediately as queue is currently empty
                 fontSize: fontSize
             }, goodbyeAnimation)
             .fadeOut(goodbyeFadeOut, function() {  // fadeOut is queued and will run when animate finishes
                 jQuery('#content').fadeIn();
             });

http://jsfiddle.net/wyEwB/

Note that due to this queueing behavior, you did not need to nest all of those animations one within the other. They could have simply been chained and the same effect would have been achieved.

Upvotes: 3

Related Questions