views:

32

answers:

1

Hi folks,

I need to synchronize functionality with various animations... unfortunately jQuery queues up ONLY animations of a certain object.

jQuery offers the possibility to add callbacks, but I cannot pass it any external variables.


Here is some code!!! =)

var unicorn_actions = [...];
for( var i=0; i<unicorn_actions.length; i++){
    var unicorn_action = unicorn_actions[i];
    if(unicorn_action['type'] == 'movement'){
         $('#unicorn').animate({...}, unicorn_action['time']);
    }
    else if(unicorn_action['type']=='action'){
         $('#unicorn').animate({}, 0, function(){
               // I NEED TO APPEND THE ACTION TO THE ANIMATION
               perform_action(unicorn_action);
         });
    }
}

1st problem

var unicorn_name = "George";
$(...).animate({'top':100,'left':100 }, 100, function(){
    alert(unicorn_name);
})

This returns unicorn_name undefined!


2nd problem

If i need to append a callback to an animation queue I'm thinking of doing the following

$(...).animate({'top':100,'left':100 }, 0, function(){
    // my actions
})

This messes up the animations...


Any ideas guys? =)

+1  A: 

Here's a version of your code that fixes all the issues you posted:

var actions = [
    {action:'movement', top:123, left:123, time:1000},
    {action:'alert', content:'test'},
];

$(function(){
    $.each(actions, function(i, action) {
        switch(action.action) {
           case 'movement':
                $('#unicorn').animate({top:action.top, left:action.left}, action.time);
                break;
            case 'alert':
                $('#unicorn').delay(50).queue(function(){ alert(action.content); });
                break;
        }
    });
});

You can test it here, there were several fixes in these changes:

  • You were accessing the variable from an array, i changes by the time you used it...you need to pass it into a closure, which $.each() creates.
  • Since you don't need to animate to the same spot again, to add a callback to the queue just use .delay() for the 50ms pause and .queue() to add your function (or remove the .delay() if you were just playing with it).
  • Other minor improvements:
    • Changed your if/else if structure to a switch, since it looks likely you'll add more cases.
    • Changed all of your ['prop'] to .prop...that's me just finding it easier to read :) ​
Nick Craver