0

I have the following HTML, CSS and Javascript:

HTML

<p id="loading">Loading...</p>
<div id="my-box"></div>
<input type="button" id="my-button" value="Click" />

CSS

#loading {
    display: none;
}

Javascript

$("#my-button").click( function() {

    $.ajax({
        type: 'POST',
        url: '/echo/html/',
        data: {html: "<p>Text echoed back to request</p>"},
        delay: 0,

        beforeSend: function(xhr) {

            $('#loading').fadeIn('fast', function() {
                $('#my-box').fadeOut();
            });

        },

        success: function(html){

            $('#my-box').stop(true, true).html(html).fadeIn('slow', function(){
                $("#loading").fadeOut("fast");
            });
        }
    });
});

There is a JSFiddle here here.

The problem is if the ajax call takes less than 200ms to execute, fadeOut() overwrites fadeIn() and #my-box become invisible instead of visible.

I am not seeing what can cause this. Any help will be very welcome.

Marcio Mazzucato
  • 8,841
  • 9
  • 64
  • 79
  • [fast](http://api.jquery.com/animate/) has a duration of 200 MS. If the AJAX call finishes before that, then the Success function will fire before the callback function of `$('#loading').fadeIn` – Stryner Aug 22 '14 at 13:27

1 Answers1

1

You should use the same sequence in success for fadeOut() and fadeIn()

success: function (html) {
    $('#loading').fadeOut('fast', function () {
        $('#my-box').html(html).fadeIn();
    });
}

DEMO

Satpal
  • 132,252
  • 13
  • 159
  • 168
  • I am trying to solve this since yesterday, you save my life! Thanks! One last question, do you know exactly why it happens if we use a different sequence for `fadeIn()` and `fadeOut()`? – Marcio Mazzucato Aug 22 '14 at 13:31
  • @MarcioSimao, Its nothing to do with ajax, fadeIn() and fadeIn() are added to queue, so which ever is added first executed first. – Satpal Aug 22 '14 at 13:42