How to wait for jQuery animation to complete before calling the following functions?

I had a problem completing my jquery function before calling the next function.

Essentially, I am trying to make my news articles fade and finish all fadeout animations until I get the next page of articles via ajax.

Here is what I have (Sampled to include only relevant functions).

The fade control function of each news article ...

function fadeArticlesOut() { var delay = 0; //set timeout for image to appear (set at 500ms) $('#news-articles article').each(function(index) { $(this).delay(delay).fadeTo(800, 0); delay += 400; }) }; 

A function that is triggered by clicking a pagination link. This fixes the download URL via ajax, but before he does, I want to run the fadeout function, i.e. FadeArticlesOut. I want the fade animation to complete before the loadProducts function starts.

 function doPager() { $('.pagination-controls a').click(function(e) { e.preventDefault(); fadeArticlesOut(); loadProducts($(this).attr('href')); history.pushState(null, null, $(this).attr('href')); historyedited = true; }); } function loadProducts(url) { $('#news-articles').empty().addClass('loading').load(url + ' #news-articles-inner', function() { $('#news-articles').removeClass('loading'); doPager(); fadeArticlesIn(); }); } 

Once completed, the product upload feature will then disappear in new news articles.

So far I have tried many methods, including using custom callbacks, deferred objects, and setting timeouts. The problem I have is that I can either get her to run fadeouts, but not continue loading ajax contents or not have fadeouts, but getting ajax contents.

+4
source share
1 answer

You can get the promise with .promise() , and then add the .done() handler.

 function fadeArticlesOut() { ... return $('#news-articles article').each(function(index) { ... }).promise(); }; 

 function doPager() { $('.pagination-controls a').click(function(e) { var $self = $(this); ... fadeArticlesOut().done(function(){ loadProducts($self.attr('href')); }); ... }); } 

The .done() handler will be called to complete all animations.

+7
source

All Articles