How to create a Loading Animation / Spinner using jQuery

Many web applications have some kind of loading animation (aka spinner).

A loading animation is important to signal the user that the application is still doing something and the user should wait for an action to complete. This gets even more important when you use Ajax in your webapp.

Using the Ajax library jQuery it is very easy to create a loading animation that will be shown whenever an Ajax request is running.

First of all, you need an animated gif with a loading animation. You can pick a free gif and customize it at ajaxload.info.
Include a div containing the image in every page of your webapp. Typically, you will add this div to a layout file or header that you include in every page.

<div id="spinner" class="spinner" style="display:none;">
	<img id="img-spinner" src="spinner.gif" alt="Loading"/>
</div>

The attribute style=”display:none;” makes the div invisible when the page is loaded.
You can style the div whatever you like using the class “spinner”. I decided that I wanted the div to be centered in the middle of the screen on top of the rest of the page.

.spinner {
	position: fixed;
	top: 50%;
	left: 50%;
	margin-left: -50px; /* half width of the spinner gif */
	margin-top: -50px; /* half height of the spinner gif */
	text-align:center;
	z-index:1234;
	overflow: auto;
	width: 100px; /* width of the spinner gif */
	height: 102px; /*hight of the spinner gif +2px to fix IE8 issue */
}

To show the spinner automatically when an Ajax request is running, add the following jQuery javascript code to every page by including it to a layout file or header.

<script type="text/javascript">
$(document).ready(function(){
	$("#spinner").bind("ajaxSend", function() {
		$(this).show();
	}).bind("ajaxStop", function() {
		$(this).hide();
	}).bind("ajaxError", function() {
		$(this).hide();
	});

     });
</script>

This will show the loading animation when an Ajax requests starts and hide it automatically when the Ajax request is complete or when an error occurs.

Additionally, it is possible to use the spinner for normal, non-Ajax requests.
An example for this would be an ordinary file upload. If you use plain html, uploading a file does not trigger an Ajax request so your spinner wouldn’t be visible automatically.

In your file upload form, give the submit button an html ID, e.g. buttom-upload. Now include the following jQuery javascript code to show the spinner when the form is submitted:

<script type="text/javascript">
$(document).ready(function(){
	$('#button-upload').click(function() {
		$('#spinner').show();
	});
});
</script>

You do not have to hide the spinner, because when the request completes, a new page is rendered where the spinner is not visible.

Short URL for this post: http://blog.oio.de/yQwnB
This entry was posted in Java Web Frameworks and tagged , , . Bookmark the permalink.