tags:

views:

179

answers:

3

I have a page that has a tab set. Each of the tabs is loaded by the jQuery .load() function.

I want to display a loading animation that disappears when all of the ajax requests are finished. However, document.ready() has only provided me with limited success.

How can I ensure that all ajax requests are completed before executing the code to hide the loading animation?

Thanks!

+1  A: 

ajaxComplete

Per the documentation:

$('.log').ajaxComplete(function() {
    $(this).text('Triggered ajaxComplete handler.');
});
Jason
Well, this will fire on completion of each AJAX request. I read the question as "How to detect when they are all finished?"
Matt
+2  A: 

Use the callback argument to .load(), setting a flag or increasing a counter in the callback function. Once all flags are set or the counter reaches the number of tabs, you know all tabs have been loaded, and you can remove the animation.

In pseudocode that might or might not be valid JavaScript:

loadedTabs = 0;

function onLoad() {
    for (int i = 0; i < numTabs; ++i) {
        tabs[i].load(tabUrl(i), tabLoaded);
    }
}

function tabLoaded() {
    ++loadedTabs;
    if (loadedTabs == numTabs)
        loadingAnimation.display = 'none';
}
Thomas
Good approach, but how would I know when the right number has been reached? Writing a `while` loop which waits for the right number to be set seems like a bad idea for some reason...
Mike
Like I said, use a global counter. I'll update my answer.
Thomas
Ah! I see what you're saying... I'll give this a try to tomorrow and see how it works! Thanks so much!
Mike
+2  A: 

This?

http://api.jquery.com/ajaxStop/

JC
this is the correct answer.
Jason