简体   繁体   中英

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 ie 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 id s once and on the next function callback, swaps them back again. What's the appropriate way to achieve this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM