I’m trying to adapt this solution to my needs: How can I create a "Please Wait, Loading…" animation using jQuery?
Basically a really awesome scheme is provided to wrap Ajax requests with a nice loading GUI. I’m trying to do the same for a function I have that does some calculations and then appends some graphics to the DOM.
So what I’ve tried is this:
$("body").addClass("loading");
long_time_taking_function(mainDiv);
$("body").removeClass("loading");
Unfortunately it appears as though the class is added and then removed instantly, either before or after the long_time_taking_function() executes. However I know that adding the class works, because commenting out the removeClass() call keeps the gif floating on the page.
Any ideas how I can make this work? I can provide more details about the intermediate function if needed.
Cheers
This is a common pitfall with AJAX: the first “A” stands for “asynchronous”. That means that the AJAX call returns immediately and runs more-or-less “in the background”.
long_time_taking_function()contains an AJAX call. You just need to move that$('body').removeClass('loading')into the callback of the AJAX call. If you’re using jQuery (assuming you are since you tagged jquery), it will look something like this:Edit: the jQuery Deferred object’s callback here should be
always(), as the loading class should be removed even if the ajax call failed.