The following is based on a jQuery Mobile app I am working on. But, the code and details apply to jQuery, too.
The app I am working on makes frequent Ajax calls to back-end services, and so I want a busy indicator that shows the user that activity is occurring. This is actually really easy to do, once you have a few steps in place. So …
First you’ll need the indicator itself. The simplest way to do this is with an animated GIF (and, yes, that means that the indicator won’t reflect the relative wait time like a progress bar would). For great free animated GIF loading indicators, go to ajaxload.info. Once you have the image, embed it in your page using an tag:
I want the image centered on the page, accomplished using this CSS:
.ajaxLoader {
position: fixed;
top: 50%;
left: 50%;
margin-top: -24px;
margin-left: -24px;
z-index: 100;
display: none;
}
The GIF I used was 48px x 48px, so the margins are set to -half that size. That, combined with 50% for top and left ensures that the image is centered in the page. z-index is set to 100 to ensure that the image is in the foreground, and display:none prevents the image from being displayed.
Now there is an invisible animated GIF on the page. The next step is to show the image when an Ajax call starts and hide it when the call completes. jQuery makes this incredibly simple to do via the ajaxSetup() function. Here’s the code:
$.ajaxSetup({
beforeSend:function(){
$("#imgAjaxLoader").show();
},
complete:function(){
$("#imgAjaxLoader").hide();
}
});
When an Ajax call is initiated, beforeSend calls .show() to display the animated GIF, and when complete, .hide() hides the image. Simple.
My own jQuery Mobile app makes Ajax calls on multiple pages, and so I embedded the same animated GIF on each page, all using the same style. Rather than bothering to track which page is displayed to show / hide just that animated GIF, I use jQuery to show / hide all of them, like this:
$.ajaxSetup({
beforeSend:function(){
$(".ajaxLoader").show();
},
complete:function(){
$(".ajaxLoader").hide();
}
});
.ajaxLoader finds every tag styled as ajaxLoader, so $(“.ajaxLoader”).show() shows all of the loader GIFs and $(“.ajaxLoader”).hide() hides them all.
Nice and simple!
Leave a Reply