HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

"Group" animation events in jQuery

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
eventsanimationjquerygroup

Problem

I have a number of jQuery animation effects applied to certain elements on the page:

jQuery("#bgd_balance").animate({
        backgroundPositionY: "0px",
        backgroundPositionX: "0px",
        'background-size':'100%'
},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")X.slideDown(600,"easeInCirc");
       delay(1000),                         
       jQuery(".balance_left_box").animate({
            height:"270px",
            top:"64px"  
        },100,"easeInCirc");
).run();


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, in my opinion.

Solution

The way I see it, you have 2 options; either use Deferreds, or store your delay in a variable:

var delay = 0,
    $left_box = $(".balance_left_box");

$("#bgd_balance").animate({
    backgroundPositionY: "0px",
    backgroundPositionX: "0px",
    'background-size':'100%'
}, 800, "swing");

$left_box.delay(delay += 2000).slideDown(200, "easeInCirc");

$left_box.find("p.first-line").delay(delay += 2400).slideDown(600, "easeInCirc");

$left_box.delay(delay += 1000).animate({
    height:"270px",
    top:"64px"  
}, 100, "easeInCirc");

Code Snippets

var delay = 0,
    $left_box = $(".balance_left_box");

$("#bgd_balance").animate({
    backgroundPositionY: "0px",
    backgroundPositionX: "0px",
    'background-size':'100%'
}, 800, "swing");

$left_box.delay(delay += 2000).slideDown(200, "easeInCirc");

$left_box.find("p.first-line").delay(delay += 2400).slideDown(600, "easeInCirc");

$left_box.delay(delay += 1000).animate({
    height:"270px",
    top:"64px"  
}, 100, "easeInCirc");

Context

StackExchange Code Review Q#13507, answer score: 4

Revisions (0)

No revisions yet.