Wednesday, July 23, 2014

jQuery's .show() doesn't always show





If you want to show or hide some DOM element, you probably use jQuery functions show() and hide().

Let's have this piece of code:

$.ajaxSetup({
    beforeSend: function (xhr) {
        ajaxCount++;
        $("#loading-indicator").show();
    },
    complete: function () {
        ajaxCount--;
        if (ajaxCount < 1) {
            $("#loading-indicator").hide();
        }
    }
});


which will show or hide an loading indicator.
The problem is that not always the indicator gets hidden though the counter reaches 0 and the condition is true in the complete callback.

The "secret" is that the jQuery show/hide functions have animation enabled by default with the duration set to 400 milliseconds.

In cases like this you should use:

$("#loading-indicator").show({ duration: 0 });

and

$("#loading-indicator").hide({ duration: 0 });

and everything should work fine.




No comments:

Post a Comment