avs099
avs099

Reputation: 11227

how to group function calls for consecutive execution in jQuery?

I have a number of jQuery animation effects applied to certain elements on the page. Right now my code looks like this:

jQuery("#bgd_balance").animate({backgroundPositionY: "0px",},800,"swing");
jQuery(".balance_left_box").delay(2000).slideDown(200,"easeInCirc");
jQuery(".balance_left_box p.first-line").delay(2400).slideDown(600,"easeInCirc");
jQuery(".balance_left_box").delay(1000).animate({height:"270px",top:"64px",100,"easeInCirc");

the problem I'm facing is that when I'm tweaking delay of a certain element, i have to go through everything and adjust all other delays accordingly.

Is it possible to have something like this instead (pseudocode):

queue.add(
       delay(2000),
       jQuery(".balance_left_box").slideDown(200,"easeInCirc"),
       delay(2000),
       jQuery(".balance_left_box p.first-line").slideDown(600,"easeInCirc");
       delay(1000),                         
       jQuery(".balance_left_box").animate({height:"270px", top:"64px"},100,"easeInCirc");
).run();

I hope the code speaks for itself.

I know I can achieve this "queuing" by adding callback function to animate() call but then resulting code will be really bulky and hard to read IMO.

Upvotes: 1

Views: 880

Answers (1)

gnarf
gnarf

Reputation: 106332

You might want to look at my answer on Can somebody explain jQuery.queue to me as well, but here is a quick example of how to use a queue on an empty object to make a pretty straightforward queue:

var tempQueue = jQuery({});

tempQueue.delay( 2000 );
tempQueue.queue( function( next ) {
    // note using the callback on the animation to call the "next" function in the queue
    jQuery( ".balance_left_box" ).slideDown( 200, "easeInCirc", next );
});

tempQueue.delay( 2000 );
tempQueue.queue( function( next ) {
    jQuery( ".balance_left_box p.first-line" ).slideDown( 600, "easeInCirc", next );
});
tempQueue.delay( 1000 );
tempQueue.queue( function( next ) {
    jQuery( ".balance_left_box" ).animate({
        height: "270px",
        top: "64px"
    }, 100, "easeInCirc", next );
});

Upvotes: 3

Related Questions