Dominiek.com
Dominiek ter Heide
11 months ago
Tweet this Bookmark and Share

AJAX snippet: Blank out a Div with a Spinner

While 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.

blog comments powered by Disqus

About

I'm a 22 year old Web Developer who is currently engaged in RubyOnRails consulting. Apart from obsessing about many technology related topics, I enjoy traveling and international life. In the coming months I intend to boost up my entrepreneurial activities, so stay tuned!

Creative Commons License

All content on this blog is available under the Creative Commons Attribution 3.0 License. Dominiek.com is running Kakuteru a new Semantic-Web enabled lifestreamer. Design and interaction inspired by Yonfook's Sweetcron. Most icons used are by Joseph North.