user1240679
user1240679

Reputation: 6979

Fire a callback only once on animating two objects

I was starting to make a quite complex animation with jQuery and I was looking for a certain way to animate elements together. I wrote the code somewhat as follows, which I could use to animate multiple elements together:

Here's the fiddle: http://jsfiddle.net/wkhrU/

$(document).ready(function(){
    $('#firstElement, #secondElement').animate(
        {left : '+=400px'}, 
        500,
        "linear",
        function(){
            alert("completed");
        });
});

However, the callback function fires twice i.e. each time for the element inside. What I was looking for is to be something like animating multiple elements simaltaneously for the same time duration and after the completion, fire a call inside which I wanted to swap the id attrib of the elements. I can't do the same here because on completion callback, it swaps the ids once and on the next function callback, swaps them back again. What's the appropriate way to achieve this?

Upvotes: 1

Views: 106

Answers (1)

krishwader
krishwader

Reputation: 11381

SOLUTION

You could maybe use a promise() to call the function to be executed instead of the inbuilt callback of animate. This ensures that the function in done is called only after animating both the elements. It's basically like you're asking #firstElement & #secondElement to promise JS that it'll inform when both of 'em are done so that you could attach a done handler to it.

$(document).ready(function () {
    $('#firstElement, #secondElement').animate({
        left: '+=400px'
    },
    500, "linear").promise().done(function () {
        alert("completed");
    });
});

DEMO

http://jsfiddle.net/hungerpain/wkhrU/1/

MORE INFO ON USED METHODS :

promise

  • Docs : http://api.jquery.com/promise/
  • What it does : Makes sure that all actions of a certain type bound to the collection, queued or not, have finished.

done

Upvotes: 1

Related Questions