Show progress spinner on jQuery AJAX requests

Its right from UI design point of view to show user some kind of progress in case site or application is busy with some internal processing. Especially with AJAX requests, because they take time!

In jQuery its very easy to hook all AJAX requests into one start/stop functions, so there is no need to show and hide progress indicator on each $.ajax request.

I make usage of nice spin.js library, native JavaScript implementation of configurable spinner.

Code below is pretty self-explaning. It uses jQuery ajaxStart and ajaxStop hooks to show and hide spinner. Put this code into external file and just put a link on every page and thats it.

// Creating spinner see <a href="http://fgnass.github.com/spin.js/">http://fgnass.github.com/spin.js/</a> for configuration wizzard
var opts = {
   lines: 13, // The number of lines to draw
   length: 7, // The length of each line
   width: 4, // The line thickness
   radius: 10, // The radius of the inner circle
   rotate: 0, // The rotation offset
   color: '#efefef', // #rgb or #rrggbb
   speed: 0.75, // Rounds per second
   trail: 50, // Afterglow percentage
   shadow: true, // Whether to render a shadow
   hwaccel: false, // Whether to use hardware acceleration
   className: 'spinner', // The CSS class to assign to the spinner
   zIndex: 2e9, // The z-index (defaults to 2000000000)
   top: 'auto', // Top position relative to parent in px
   left: 'auto' // Left position relative to parent in px
};
var spinner = new Spinner(opts);
var ajax_cnt = 0; // Support for parallel AJAX requests
 
// Global functions to show/hide on ajax requests
$(document).ajaxStart(function() {
   $('&lt;div id ="spinner_center" style="position:fixed;top:70px;left:49%;"&gt;&amp;nbsp;&lt;/div&gt;').appendTo('body');
   spinner.spin($('#spinner_center')[0]);
   ajax_cnt++;
});
 
$(document).ajaxStop(function() {
   ajax_cnt--;
   if (ajax_cnt &lt;= 0) {
      spinner.stop();
      $('#spinner_center').remove();
      ajax_cnt = 0;
   }
});

I added ajax_cnt variable when I faced several AJAX requests being called at once, now it counts them and correctly hides the spinner!


Did you find this post useful? Support the the author ($10)
My Google Profile+

1 comment

  1. This is exactly what I was looking for!! The only thing I had to correct are those HTML encondings for gt and lt…
    Thanks a lot.

Leave a Reply

Your email address will not be published.