A Simple JQuery AJAX Loader

  • posted by mark
  • on Sept. 7, 2012
Every modern web application gets busy from time to time, whether it be with background AJAX calls or simply just generating an unusually complex page, and you need to let your users know that it's doing something. A good way of doing this is to display an animated loader with a faded background to disable the busy area. Depending on what's loading you might want to do this over your entire page, or you might just want to fade out a single component or small area. There's a few plugins out there to do this for you automatically, but if you're using JQuery on your site (and if you're not, why not?), here's a few snippets to help you to roll your own in a matter of minutes.

Step 1 - The Loader Image

Firstly you need to obtain an animated loader image to use. Fortunately there's a bunch of websites out there that will generate one for you. Here's two I use: www.preloaders.net www.ajaxload.info Generate an image (ideally an animated gif) and save it somewhere.

Step 2 - The Stylesheet

Add the following elements to your site's stylesheet:
#ajax-loader { position: absolute; z-index: 1000; background: #fff url('ajax-loader.gif') no-repeat center; opacity: 0.75; display: none;}
Make sure to replace ajax-loader.gif with the filename and location of your loader image. And add the following to your site's main template (or on each page you want to use the loader)
<div id='ajax-loader'></div>

Step 3 - The Javascript

Add this function somewhere in your site's Javascript:
$.fn.showLoader = function() { pos = $(this).offset(); $loader = $('#ajax-loader'); if(pos !== undefined) { $loader.css('position','absolute'); $loader.css('top',''); $loader.offset(pos); } else { $loader.css('position','fixed'); $loader.css('top','0'); } $loader.width($(this).width()); $loader.height($(this).height()); $loader.fadeIn(); } $.hideLoader = function() { $loader = $('#ajax-loader'); $loader.fadeOut(); }
You can now show and hide the loader using the .showLoader() and .hideLoader() functions respectively. For instance, you can show the loader over the entire page using:
$(window).showLoader();
Or over a single element:
$('#element').showLoader();
You can hide the loader with just:
$.hideLoader();
And there you have it, it's probably not the most elegant solution and at the time of writing this has only been tested on Firefox and Chrome so I make no guarantees it's completely bug free. Feel free to use this snippet on any of your sites, and all suggestions, feedback and improvements are welcome.