Gordonmac Dot Com

Mostly a web development blog

Adding a page “loading” box with jQuery

Posted: June 4th, 2012 | Tags: | Posted in: CSS, jQuery, Tutorials
Note: This tutorial was originally published in 2012. The tips and techniques explained may be outdated.

This is one of the fastest little tutorials I have probably ever written, and that’s because creating a “page loading” box in jQuery is so damn simple it’s silly. You can view the example just to see what it does.

The Javascript

You need to grab hold of the jQuery library first by adding the following line inside the <head> section of your page.

<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js?ver=1.7.0'></script>

The next part you need to add to the <head> is just a couple of lines.

<script>
jQuery(window).load(function(){
jQuery('#loading').fadeOut(3000);
});
</script>

This simple tells jQuery to fade out the element (in our case it will be a <div> with the ID #loading) after the the entire page has loaded. And that the fading effect should last 3000 milliseconds.

The HTML

This is the simplest HTML you’ll ever write! It’s just an empty div with the ID “loading”. It only serves as a container for displaying our loading animation:

<div id="loading"></div>

Place this after the opening body tag (<body>).

The CSS

Some simple CSS is used to centre the loading message in the middle of the page… here goes…

#loading {
background:#000 url(images/ajax-loader.gif) no-repeat center center;
height: 50px;
width: 50px;
position: fixed;
left: 50%;
top: 50%;
margin: -25px 0 0 -25px;
z-index: 1000;
}

This simply creates a small back background box (with an animated loading gif background), measuring 50px by 50px, and centres it in the middle of the page by fixed positioning it 50% form the top and 50% from the left, then dragging it back to the left and top by half its overall width.

You can generate your own loading gifs via Ajaxload, it’s a really nifty little online tool!

The z-index value is there just as a fail-safe, it will ensure that the loading box will appear above all other positioned elements on the page.

That’s all there is to it! Have a look at the finished example.