picknick
picknick

Reputation: 4007

Why doesn't jQuery seem to wait for animation to finish?

What i'm trying to do is:

  1. Fade in a progress bar.
  2. When the fade finishes, animate the progressbar to 100%.
  3. When the progressbar is at 100%, fade out the preogress bar.
  4. when the fade out is completed, reset progress bar.

I thought this code would provide the solution:

    $('#savebar').fadeIn('fast', function () {
        $('#savebar .bar').animate({width: '100%'}, "slow", function () {
            $('#savebar').fadeOut('fast', function () { 
                $('#savebar .bar').css({'width':'0%'});
            });
        });
    });

The problem seem to be that the animate complete function executes to early. Is this because the browser doesn't render the progress bar fast enough or am I missing something here?

Here's a jsfiddle that's illustrating the problem: http://jsfiddle.net/dub6P/

Upvotes: 2

Views: 989

Answers (3)

Jai
Jai

Reputation: 74738

I think making animate faster and fadeout slower will solve:

$('#btn').click(function () {
  $('#savebar').fadeIn('fast', function () {
     $('#savebar .bar').animate({width: '100%'}, 500, function () {// 500 ms used
         $('#savebar').fadeOut(1500, function () {                // 1500 ms used
             $('#savebar .bar').css({'width':'0%'});
         });
     });
  });    
});

fiddle: http://jsfiddle.net/dub6P/10/

Upvotes: 0

tom
tom

Reputation: 19153

Seems like the fadeOut happens too soon. Try adding a delay before the fadeOut. The animation looks pretty good that way IMO: http://jsfiddle.net/dub6P/7/

$('#btn').click(function () {
    $('#savebar').fadeIn('fast', function () {
    $('#savebar .bar').animate({width: '100%'}, "slow", function () {
             $('#savebar').delay(1000).fadeOut('fast', function () { 
                 $('#savebar .bar').css({'width':'0%'});
             });
         });
     });    
 });

Upvotes: 5

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

Slow down the fadeout function and it seems to work fine.

$('#btn').click(function () {
    $('#savebar').fadeIn('fast', function () {
        $('#savebar .bar').animate({width: '100%'}, "slow", function () {
            $('#savebar').fadeOut(1500, function () {
                $('#savebar .bar').css({'width':'0%'});
            });
        });
    });    
});

Example: http://jsfiddle.net/dub6P/5/

Upvotes: 3

Related Questions