John
John

Reputation: 1797

jQuery hide and show divs with multiple set delays, code not working

I have some jQuery below which is not quite working correctly. When I click the button I need the following to happen:

However the loading gif div and the thank you div display at the same time and the hide/show page1 and 2 over rides the above.

Here is my code:

 $('a.myLink').click(function(e){ 
                // show loading gif for 5 seconds then fade out
                $(".myGif").show().delay(5000).fadeOut();

                //once loading gif has finished then show thank you message for 5 seconds then fade out
                $(".thanksAgain").show().delay(5000).fadeOut();

                // once thank you message has finished go back to main screen
                $('.page2').hide();
                $('.page1').show();
            });

How would I do this so it all works in correct sequence?

Upvotes: 0

Views: 679

Answers (2)

Ali Bassam
Ali Bassam

Reputation: 9959

$('a.myLink').click(function(e){ 
                // show loading gif for 5 seconds then fade out
                $(".myGif").show().delay(5000).fadeOut(400,function(){
                       $(".thanksAgain").show().delay(5000).fadeOut(400,function(){

                                $('.page2').hide();
                                $('.page1').show();
                       });

                });


});

Upvotes: 1

Axel
Axel

Reputation: 10772

You can use a callback function on the fadeout(); function, instead of trying to match up the timing. A callback occurs after the function is done running.

It would look something like this:

$(".myGif").show().delay(5000).fadeOut(400, function() {
    $(".thanksAgain").show().delay(5000).fadeOut();
});

This will allow the .thanksAgain div to display, only after the .myGif is done with it's fadeOut() function.

For the fadeout(); function, the callback is the second parameter. You can verify this by viewing the jQuery documentation: http://api.jquery.com/fadeOut/

Upvotes: 3

Related Questions