Showing Ajax activity with CSS

March 4, 2009 code 3 min read

You know when you have a form that submits with Ajax, and you want to show some type of activity on the form? There’s several ways to do this, like including a hidden image that you show and hide while there is activity, or inserting and removing an image with javascript. These all just feel too dirty to me. I don’t want to have to change the markup just because the form is submitting via Ajax.

As usual, there’s a cleaner way to do it with just CSS. I’ve used this simple but effective trick on a couple projects now, so I thought I would share.

First, here is a demo of what it looks like: (sorry, you’ll have to leave your feed reader.)

Click the save button.

or Cancel

This technique is very simple. It adds a class on the form with Javascript while it is loading, and then removes it once it’s done. The loading class hides the submit button and replaces it with a background image, usually an animated gif.

First, with Javascript, add a class to the form while the Ajax request is loading. It would look something like this in Prototype:

$('my_form').observe('submit', function(event) {
    evalScripts: true,
    onLoading:  function() { this.addClassName('loading'); }.bind(this),
    onComplete: function() { this.removeClassName('loading'); }.bind(this)

Next, wrap an element around your buttons or whatever you want to hide.

  <div class="buttons"></div>

Lastly, there’s just a little CSS to hide buttons and any elements inside them, and set the background image:

form .buttons { text-align: center; }
form.loading .buttons {
  text-indent: -2000px;
  overflow: hidden;
  background: url(../images/loading.gif) no-repeat center center;
form.loading .buttons * { visibility: hidden; }

There you have it. It’s really simple, but it’s worked well.

This content is open source. Suggest Improvements.


avatar of Brandon Keepers I am Brandon Keepers, and I work at GitHub on making Open Source more approachable, effective, and ubiquitous. I tend to think like an engineer, work like an artist, dream like an astronaut, love like a human, and sleep like a baby.