Simple global Ajax activity indicator with jQuery

Posted by Felix Geisendörfer, on Jun 27, 2007 - in JavaScript & jQuery

Hey folks,

I'm currently doing something very cool which I intend to write about in great detail later on. I'm refactoring all JS for my current web app (the secret one that was supposed to launch like 3 month ago ^^) from an MVC-ish class approach to jQuery plugins. It's gorgeous!. My code is getting smaller, easier to read and more robust. I really can't await writing a more lengthy post about this topic and why I believe that JS is one of the hottest languages these days but requires a different mindset then what we are used to from PHP and other scripting languages.

Anyway, back to the topic. One of the things I just refactored was the code I use to display a little ajax activity indicator so Users know when the app is working on somethings for them. Since the result is a pretty generic little script I thought it might be interesting for others to look at:

javascript
  1. $(function() {
  2.     var $headline = $('h1:first');
  3.     $(document).ajaxSend(function() {
  4.         $headline
  5.             .removeClass('activity')
  6.             .addClass('activity');
  7.     });
  8.     $(document).ajaxStop(function() {
  9.         $headline.removeClass('activity')
  10.     });
  11. });

Notes: I don't use the $headline variable out of PHP habits but as a mean to indicate jQuery objects throughout my application. The 'removeClass' call in the ajaxSend closure is neccessary since otherwise you might add the 'activity' class twice to the $headline if two requests are going on at the same time which is something I usually try to avoid.

In the application you can then see a little ajax spinner show up whenever requests are taking place:

I hope some of you find this little snippet useful ; ).

Some unrelated news: I don't know how many unique downloads my svn screencast received but my stats say it swallowed around 250 GB in traffic which is sort of nuts. When I found out about it I was kind of scared for a second but then remembered that I recently upgraded my web hosting plan to one where I have unlimited traffic - which saved me 100 euros in bandwidth fees ; ).

So stay tuned for upcoming stuff like the finished Containable behavior, some other code and posts I got in my backlog as well as the launch of my little web application.

-- Felix Geisendörfer aka the_undefined