jQuery Loading Animation

April 3, 2013

After looking around online I was surprised how hard it was to find a full explanation on how to display a loading message/animation using jQuery, so I thought I’d put one together. If you want to jump straight to the source you can view a demo and extract what you need.

This solution degrades nicely when the user has JavaScript disabled, again something that seems to have been overlooked in several other examples that I’ve seen.

HTML

The HTML is as simple as can be. We have 2 div elements, a ‘loading’ div containing the message/animation to be shown while the page is loading, and a ‘container’ div that contains everything else.

<div id="container">
	<p>Lorem ipsum....</p>
</div>
<div id="loading">Loading</div>

CSS

Again the CSS is straight-forward. The only point to consider is that the ‘loading’ div should be set to hidden by default, this is key to the graceful degradation.

#container{
	width: 1000px;
	margin: 0 auto;
	margin-top: 60px;}
#loading{
	position: absolute;
	top: 0;
	left: 0;
	display: none;
	width: 100%;
	height: 60px;
	line-height: 60px;
	background: yellow;
	text-align: center;}

jQuery

The jQuery function relies on ‘ajaxStart’ (where the ‘loading’ div appears) and ajaxStop (when the page has loaded and the ‘container’ div is shown). There is a lot of documentation out there on these functions, but few resources inform you that need to call ‘$.ajax();’ in order for the script to work.

$(document).ready(function() {		
	//Required for loading
	$.ajax();							
});
		
// Loading	
$(document).ajaxStart(function(){
	$("#container").hide();
	$("#loading").show();
});
$(document).ajaxStop(function(){
	$("#container").delay(700).fadeIn(500);
	$("#loading").delay(200).fadeOut(500);
});

Conclusion

Yeah, it really is that simple.

I’ve added delays and fade effects in the jQuery code to avoid the loading message flashing too quickly when there isn’t much content on the page, so play around with these settings until you find a combination that you’re happy with.

Facebooktwittergoogle_pluslinkedinmail
Back to JournalMore Posts

Let's Talk

Let's work together and create something awesome.

If you want to know how it all works, if you've got a project idea, or if you have any questions or queries simply complete the form and I'll get right back to you.

Hi, my name is

I'm the

here at

You can email me via

or call me on