Reputation: 6217
I wonder how can I code this:
//if there is any ajax request
$("#loader").css("display","block");
//on success:
$("#loader").css("display","none");
Note :
I am not going to code it again and again in my each ajax request function.
I want it generic so that my script knows if there is any ajax request do $("#loader").css("display","block");
and if there is any ajax success do $("#loader").css("display","none");
.
Upvotes: 7
Views: 708
Reputation: 13115
These other solutions are great but I am not sure they address your concern of calling your $("#loader")
CSS changes on start and success.
May be something like this:
$(document).ajaxStart(function() {
// do something on start
$("#loader").css("display","block");
}).ajaxError(function(e, xhr, settings) {
// do something on error
$("#loader").css("display","none");
}).ajaxSuccess(function() {
// do something on success
$("#loader").css("display","block");
});
Check out this properly working example: http://jsbin.com/ocovoq/3/edit#preview
Upvotes: 2
Reputation: 28711
Take a look at $.ajaxStart
and $.ajaxEnd
when you wire up your app in $.document(ready):
$.ajaxStart(function(){
$("#loader").css("display", "block");
})
.ajaxStop(function(){
$("#loader").css("display", "none");
});
UPDATE forgot about ajaxStop...@Cory's answer reminded me. Updated my answer.
Upvotes: 3
Reputation: 107626
The magical thing you are looking for is jQuery.ajaxStart() and jQuery.ajaxStop(). You might also find jQuery.ajaxComplete() useful.
Example:
$("#loader").ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).hide();
});
You should use the hide()
and show()
methods instead of changing the display
CSS attribute.
Upvotes: 8
Reputation: 4346
If you fire off two or three ajax calls, ajaxStop will only fire when the last one is done.
var isMakingAjaxCall;
$(document).ready(function () {
// Loading Screen for Ajax Calls
$("#loader").hide();
$("#loader").ajaxStart(function () {
isMakingAjaxCall = true;
RepositionLoading();
$("#loader").fadeIn();
});
$("#loader").ajaxStop(function () {
$("#loader").fadeOut();
isMakingAjaxCall = false;
});
});
function RepositionLoading() {
$("#loader").css('left', "20px");
$("#loader").css('top', "20px");
};
Upvotes: 1