In Prototype I can show a "loading..." image with this code:
var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars,
onLoading: showLoad, onComplete: showResponse} );
function showLoad () {
...
}
In jQuery, I can load a server page into an element with this:
$('#message').load('index.php?pg=ajaxFlashcard');
but how do I attach a loading spinner to this command as I did in Prototype?
There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.
$('#loadingDiv')
.hide() // Hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
The ajaxStart/Stop functions will fire whenever you do any Ajax calls.
Update: As of jQuery 1.8, the documentation states that .ajaxStart/Stop
should only be attached to document
. This would transform the above snippet to:
var $loading = $('#loadingDiv').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});