Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
Jquery - defer callback until multiple animations are complete

I need a callback to execute once after multiple elements have finished animating. My jquery selector is as follows:

$('.buttons').fadeIn('fast',function() {
   // my callback
});

The problem with this is that the buttons class matches a number of elements, all of which need to be faded in before the callback is executed. As it stands now, the callback is executed after each individual element has finished animating. This is NOT the desired function. I'm looking for an elegant solution such that my callback is only executed once after all the matched elements have finished animating. This question has popped up in a few places including SO, but there's never been an elegant answer (nor even a definitive answer for that matter - solutions that work for one person don't work at all for others).

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

jQuery introduced a promise in version 1.6 and is far more elegant than adding counters.

Example:

// Step 1: Make your animation
$(".buttons").each(function() {
    $(this).fadeIn("fast");
});

// Step 2: Attach a promise to be called once animation is complete
$(".buttons").promise().done(function() {
    // my callback
});
over 4 years ago · Santiago Trujillo Relatório

0

For collecting unrelated element animations into a single callback you can do this:

$.when(
    $someElement.animate(...).promise(),
    $someOtherElement.animate(...).promise()
).done(function() {
    console.log("Both animations complete");
});
over 4 years ago · Santiago Trujillo Relatório

0

An alternative to @Ross's answer that will always trigger the callback on the last button to fade in (which may or may not be the last button that was told to animate) could be:

var buttons = $(".buttons");
var numbuttons = buttons.length;
var i = 0;

buttons.fadeIn('fast', function() {
    i++;
    if(i == numbuttons) {
        //do your callback stuff
    }
});
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda