Ryan
Ryan

Reputation: 787

Deferring action until .each() has completed

I have the following method:

function animatePortfolio(fadeElement) {
    fadeElement.children('article').each(function(index) {
        $(this).delay(1000*index).fadeIn(900);
    });
}

I'd like to defer an action until .each() has entirely completed. Assume this is some version of deferred/promise I need to employ, but not understanding how in this scenario it would work.

Upvotes: 1

Views: 77

Answers (3)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

Do not use done with animation promises, as if any are in the target state to begin with it will not fire. Use always() instead

function animatePortfolio(fadeElement) {
   fadeElement.children('article').each(function(index) {
      $(this).delay(1000*index).fadeIn(900);
  }).promise().always(function(){
     // do aditional animation here 
   });
 }

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can use the promise object returned by animation

function animatePortfolio(fadeElement) {
  fadeElement.children('article').each(function(index) {
    $(this).delay(1000 * index).fadeIn(900);
  }).promise().done(function() {
    fadeElement.css('color', 'red')
  });
}


animatePortfolio($('div'))
article {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <article>1</article>
  <article>2</article>
  <article>3</article>
  <article>4</article>
</div>

Upvotes: 2

Meenesh Jain
Meenesh Jain

Reputation: 2528

this can be done with done function

function animatePortfolio(fadeElement) {
   fadeElement.children('article').each(function(index) {
      $(this).delay(1000*index).fadeIn(900);
  }).promise().done(function(){
     // do aditional animation here 
   });
 }

OR

when function called do it there

    animatePortfolio(fadeElement).promise().done(function(){

     // do things here 
    });

Upvotes: 2

Related Questions