Run a full function only once in jQuery animation?

I am trying to animate the font size of some text:

$("p").delay(500).animate({
    "font-size": "+=50"
}, 1000, function() {
    alert("Done");
})​;

Here is a demo.

I want to do something after the <p>s animation , which is in the example alert, but this amazingly launches it for everyone <p>, and this is not what I want. Is there a way for it to just start once or is this not possible?

+1
source share
5 answers
var $p = $("p");
var lastIndex = $p.length - 1;

$p.delay(500).animate({
    "font-size": "+=50"
}, 1000, function() {
    if ($p.index($(this)) == lastIndex) {
        alert("Done");
    }
})

Demo

+2
source

To notice, you can also use the promise object :

Returns a Promise object to observe when all actions of a certain type associated with the collection, in the queue or not, have finished.

First example ( demo ):

$("p").delay(500).animate({
    "font-size": "+=50"
}, 1000).promise().done(function(){
    alert("done");
});​

(demo):

$.when($("p").delay(500).animate({
    "font-size": "+=50"
}, 1000)).done(function(){
    alert("done");
});​
+10

You can just save the flag, as they should be animated at the same time:

var done = false;

$("p").delay(500).animate({
    "font-size": "+=50"
}, 1000, function() {
    if(!done) {
        done = true;
        alert("Done");
    }
})​;

Here is a demo.

+3
source

Give the P-tag a questionable ID and select that ID, not every P tag on the page. Like here: http://jsfiddle.net/LR8uP/1/

Or, if you want to animate each P-tag, but only run the function once, add a state variable, like here: http://jsfiddle.net/LR8uP/2/

0
source

This code can be used as a common countdown type.

// Function that returns a function,
// which when invoked 'count' number of times,
// will invoke the function 'fn'
function runOnZero (count, fn) {
    return function () {
        if (--count <= 0) {
            fn();
        }
    };
}

// Get all the <p>s
var ps = $("p");

// Do your thing after ps.length calls
var whenAllDone = runOnZero(ps.length, function () {
   alert("Done");
});

ps.delay(500).animate({
    "font-size": "+=50"
}, 1000, whenAllDone)​;
0
source

All Articles