AJAX snippet: Blank out a Div with a Spinner
on December 16, 2007While doing some quick prototyping for one of my projects I was building a week, month, year period selector. When loading stuff with AJAX it is important to indicate to your users that you are actually refreshing a piece of data on your page. There are many ways of indicating this load, but for now I just wanted something quick and useful (without requiring any strings that might have to be translated in the future):
example data:

when loading:

I meshed together a quick piece of Javascript and CSS since I couldn’t find anything out there. If you know something that does this, please let me know! (Since my code is obviously quick and dirty and only tested on Firefox).
Put this in one of your Javascript files (in case of rails: application.js):
1 2 3 4 5 |
function spin_div(div_id) { container = $(div_id); positioning = 'top: '+container.offsetTop+'px; width: '+container.offsetWidth+'px; height: '+container.offsetHeight+'px; '; container.innerHTML += '<div class="spin_div" style="position: absolute; ' + positioning + '"></div>'; } |
And here is some CSS which you can customize (spinner.gif is a generated spinner from ajaxload.info):
1 2 3 4 5 6 7 |
.spin_div {
background: #fff url('/images/spinner.gif') no-repeat center center;
opacity: 0.75;
filter:alpha(opacity: 75);
-moz-opacity: 0.75;
-khtml-opacity: 0.75;
}
|
Now when using Rail’s or prototype’s AJAX routines, just pass spin_div as a onLoad parameter:
1 |
link_to_remote('label', :url => takes_awhile_url, :loading => "spin_div('container_id');") |
The great thing about this method is that the spinner get’s automatically destroyed when the content of the container is refreshed.