How to Load In and Animate Content with jQuery
In this tutorial we will be taking your average everyday website and enhancing it with jQuery. We will be adding ajax functionality so that the content loads into the relevant container instead of the user having to navigate to another page. We will also be integrating some awesome animation effects.
So first of all, I have put together a very simple layout for this example. Here’s a screenshot and the HTML code we’ll use.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>mmm... Ajax!</title>
<script type="text/javascript" src="jquery.js"></script>
<style type="text/css">
@import url(css.css);
</style>
<script type="text/javascript" src="js.js"></script>
</head>
<body>
<div id="wrapper">
<h1>ajax ... nettuts</h1>
<ul id="nav">
<li><a href="index.html">welcome</a></li>
<li><a href="about.html">about</a></li>
<li><a href="portfolio.html">portfolio</a></li>
<li><a href="contact.html">contact</a></li>
<li><a href="terms.html">terms</a></li>
</ul>
<div id="content">
<h2>Welcome!</h2>
<p>Text</p>
</div>
<div id="foot">Tutorial by James for NETTUTS</div>
</div>
</body>
</html>
Step 1
First thing’s first, go and download the latest stable release of jQuery and link to it in your document:
<script type="text/javascript" src="jQuery.js"></script>
One of the best things, in my opinion, about jQuery is it’s simplicity. We can achieve the functionality described above coupled with stunning effects in only a few lines of code.
First let’s load the jQuery library and initiate a function when the document is ready (when the DOM is loaded).
$(document).ready(function() {
// Stuff here
});
Step 2
So what we want to do is make it so that when a user clicks on a link within the navigation menu on our page the browser does not navigate to the corresponding page, but instead loads the content of that page within the current page.
We want to target the links within the navigation menu and run a function when they are clicked:
$('#nav li a').click(function(){
// function here
});
Let’s summarize what we want this function to do in event order:
- Remove current page content.
- Get new page content and append to content DIV.
We need to define what page to get the data from when a link is clicked on. All we have to do here is obtain the ‘href’ attribute of the clicked link and define that as the page to call the data from, plus we need to define whereabouts on the requested page to pull the data from – i.e. We don’t want to pull ALL the data, just the data within the ‘content’ div, so:
var toLoad = $(this).attr('href')+' #content';
To illustrate what the above code does let’s imagine the user clicks on the ‘about’ link which links to ‘about.html’ – in this situation this variable would be: ‘about.html #content’ – this is the variable which we’ll request in the ajax call. First though, we need to create a nice effect for the current page content. Instead of making it just disappear we’re going to use jQuery’s ‘hide’ function like this:
$('#content').hide('fast',loadContent);
The above function ‘hides’ the #content div at a fast rate, and once that effect finished it then initiates the “loadContent” function (load the new content [via ajax]) – a function which we will define later (in step 4).
Step 3
Once the old content disappears with an awesome effect, we don’t want to just leave the user wondering before the new content arrives (especially if they have a slow internet connection) so we’ll create a little “loading” graphic so they know something is happening in the background:
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
Here is the CSS applied to the newly created #load div:
#load {
display: none;
position: absolute;
right: 10px;
top: 10px;
background: url(images/ajax-loader.gif);
width: 43px;
height: 11px;
text-indent: -9999em;
}
So, by default this ‘load’ span is set to display:none, but when the fadeIn function is initiated (in the code above) it will fade in to the top right hand corner of the site and show our animated GIF until it is faded out again.
Step 4
So far, when a user clicks on one of the links the following will happen:
- The current content disappears with a cool effect
- A loading message appears
Now, let’s write that loadContent function which we called earlier:
function loadContent() {
$('#content').load(toLoad,'',showNewContent)
}
The loadContent function calls the requested page, then, once that is done, calls the ’showNewContent’ function:
function showNewContent() {
$('#content').show('normal',hideLoader);
}
This showNewContent function uses jQuery’s show function (which is actually a very boring name for a very cool effect) to make the new (requested) content appear within the ‘#content’ div. Once it has called the content it initiates the ‘hideLoader’ function:
function hideLoader() {
$('#load').fadeOut('normal');
}
We have to remember to “return false” at the end of our click function – this is so the browser does not navigate to the page
It should work perfectly now. You can see an example of it here: [LINK]
Here is the code so far:
$(document).ready(function() {
$('#nav li a').click(function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').hide('fast',loadContent);
$('#load').remove();
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
function loadContent() {
$('#content').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#content').show('normal',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
});
Step 5
You could stop there but if you’re concerned about usability (which you should be) it’s important to do a little more work. The problem with our current solution is that it neglects the URL. What if a user wanted to link to one of the ‘pages’? – There is no way for them to do it because the URL is always the same.
So, a better way to do this would be to use the ‘hash’ value in the URL to indicate what the user is viewing. So if the user is viewing the ‘about’ content then the URL could be: ‘www.website.com/#about’. We only need to add one line of code to the ‘click’ function for the hash to be added to the URL whenever the user clicks on a navigation link:
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
The code above basically changes the URL hash value to the value of the clicked link’s ‘href’ attribute (minus the ‘.html’ extension. So when a user clicks on the ‘home’ link (href=index.html) then the hash value will read ‘#index’.
Also, we want to make it possible for the user to type in the URL and get served the correct page. To do this we check the hash value when the page loads and change the content accordingly:
var hash = window.location.hash.substr(1);
var href = $('#nav li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-5)){
var toLoad = hash+'.html #content';
$('#content').load(toLoad)
}
});
With this included here is all the javascript code required: (plus the jQuery library)
$(document).ready(function() {
// Check for hash value in URL
var hash = window.location.hash.substr(1);
var href = $('#nav li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-5)){
var toLoad = hash+'.html #content';
$('#content').load(toLoad)
}
});
$('#nav li a').click(function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').hide('fast',loadContent);
$('#load').remove();
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#content').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#content').show('normal',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
});
Finished…
The great thing about this method is that’s it’s adaptable and can be applied to a site within minutes. It’s fully unobtrusive and the website will work normally if the user has JS disabled.
View the Final Working Example
Download the HTML, JS, CSS & Images









I added the jQuery lightbox into one of the page and the lightbox didn’t work….
Any help?
Read comments, I saw the same problem and solution for that
it’d be nice if someone could write a version of this that doesn’t rely on specific HTML markup, I tried enhancing some already written traditional HTML pages with it and couldn’t get it working…
How can I get this to work with ASP pages ? For example, if I want to go to a contactpage, I usually send out index.asp?page=contact. How can I do this in this ajax script?
tnx for this.
very interesting tut, thanks for sharing James
This is exactly what I was looking for for a project I’m about to start. Thanks for the tut!
Great work – This just put the finishing touches to a project of mine!
Really Cool!
really awesome tut from you
truly taught me a lot as m new to ajax
but just
ONE SPECIAL REQUEST
working of $_GET and $_POST commands so that we can get the usernames
PS. I have reworked js as guided to get it load all php files just need this little bit now
Hello there,
I’m making this tutorial, step by step because i love javascript with ajax…
Well, it’s new for me one thing,
Line 4 in CSS:
rightright: 10px;
I don’t remember ever seen this is CSS.
Is it a new propriety?
how can i get a link from within the content div to open new content within itself ?
Hi,
I have noticed that when there’s include(“somefile.php”) and there’s tag in this include, efect is no longer working.
Example index.php:
Content in ’somefile.php’ (only one line):
Title
and click function in your js.js:
$(‘#content a.test’).click(function(){
Is there a solution to this problem.
PS: Thank you for this code
sorry code was cleard
index.php:
div content
include ’somefile.php’ file
div
somefile.php:
a href = “link” class = “test”
Simple Question.
I have an empty div
And then I have an external PHP file that runs a MySQL query that retrieves some data.
I just want to fadeIn this data. Without fadeOut anything else… fadeIn outof nothing… is this possible?
Looking for other ajax navigation, i found this page:
http://snipplr.com/view/6455/jquery-ajax-navigation/
familiar?
Looks like the one you linked to was posted hours after this one came out. Interesting. No credit given, either.
Hi!
Great tutorial for an easy but very powerfull jquery option! Thanks a lot!
I have a question. I’m using cycle plugin in on of the pages. Cycle plugin works perfectly on the page alone, but it doesn’t when it’s loaded into the #continer div. I’ve tried everything (I think): call cycle as a callback function in your code, call cycle in the same page where the slideshow is…
Do you know the reason of it?
Anyway, again, thanks a lot for this tutorial.
Hi, is there any way to check if the file to be loaded exists before attempting the load? and if it doesnt change the load to go to a custom error page or something like that?
Cheers
I’m trying to use the script multiple times in one page.
One for the tabs menu on the left, and one for the content field on the right.
http://www.popfabryk.nl/projecten.html
The tabs above the menu work fine, and if the content in the menu doens’t reload by the script/ajax, then that works fine to.
The problem only exists after the content in the menu gets loaded by ajax, I think the script has to be reloaded to to make the new links in the menu work.
Could someone please give me some hint or a solution?
Thanx in advance!
I almost forgot to tell how mucht I love this script!
The link to the updated version doesn’t seem to work for me, can someone please post it somewhere else.
Thank you!
I have question. how to make a php request like index.php?page=anythink
and work ajax.
Very good tutorial, I must say. I will be Using this on my new page. but I have a problem. I want to open url link from an imagemap (hotspot), but I can not url Andress to open. it is only white in the div Tag. What should I do to get it to work?
I solved my previous problems. Now is my problem that I can not use any new javascript on the page I open to this effect. How do I make a javascript to work on the new page?
I have a problem, I followed this tut step by step, but don’t get it to work, the script doesnt load anything. I just modified the script a tiny little bit as I am using .php files and net .html
Any ideas ?
the page I am using it on is http://www.mactabilis.net/index.php
nevermind, used a different approach for my content
Hi James!
I sent you a little e-mail concerning an ambiguous issue with IE8 hope you manage to read it…! Would be more than grateful
Best Paul
I am fairly new to jquery so please bear with me. I am trying to make the browsers BACK and FORWARD buttons
work with Jquery.
To illustrate I have created a simple test website with the following:
My Jquery code looks like the following
$(function() {
$(‘#header’).load(‘header.php’);
$(‘#splash’).load(’splash.php’);
$(‘#horizontal_nav’).load(‘horizontal_nav.php’);
$(‘#middle’).load(‘home.php’);
$(‘#footer’).load(‘footer.php’);
});
The horizontal_nav contains three items : HOME GALLERY SLIDESHOW
and I have set up my jquery so that when one of the items is clicked a module is executed
to populate the
$(‘home’).click(function()
{
$(‘#middle’).load(‘home.php’);
});
$(‘home’).click(function()
{
$(‘#middle’).load(‘gallery.php’);
});
$(‘home’).click(function()
{
$(‘#middle’).load(’slideshow.php’);
});
All this works splendidly – with the exception that I cannot get the browsers back and forward buttons to work. I have tried using various
Jquery history plugis but I must be missing something because I cannot get it to work.
Can anyone offer any advice ??
Great tutorial! thanks. How can I add sub menus?
James forgot a ” in the latest version js.js
$(document).ready(function() {
var contentWrapID = ‘content_wrapper’;
$(‘#content’).wrap(‘<div id=" ' + contentWrapID + ' "<’);
now works in IE and Chrome for me …
$(‘#content’).wrap(”);
sorry
lol what happen with code?
so its 5 line in js.js
i’ve implemented this in my website, but now if a load content and then switch back to say portfolio, the jquery imageviewer i have there, doesnt work… any way to still run jquery after loading different content?
Wonder if anyone could help me out…
I’ve tried implementing the technique used here but with one small twist – clicking the main nav links causes new content from the page to load, same as this script. But, the content displays in a small-ish box with a “Read More” link at the bottom. Clicking “Read More” is supposed to cause the content to scroll up, revealing the next section of that page. You can see an example here: http://joelstranscription.com/misc/card_portfolio/index.html
The “Read More” buttons work perfectly when the page is first loaded, but if I try to switch to any of the other pages, or switch back to the first page, using the nav links it screws up and the Read More button doesn’t work anymore. I set Console.log() to check to see if the script is even running when I click on the Read More, and it doesn’t seem to be running at all. Does anyone know why this could be? Much obliged for any help.
I solved my own problem, which it seems is shared by several other people on here (such as Jakob), so I’ll try to explain what I did.
As others have stated, the problem is that content loaded with the .load() function doesn’t get event handlers, like onclick. So you need to rebind the event handler for all the links you want to have do something. The important thing which I didn’t realize is that you need to rebind the events AFTER the content gets loaded, using a callback. I was trying to do it in the next line after the .load line, which doesn’t work because the content hasn’t actually loaded yet.
This page sums it all up very well: http://docs.jquery.com/Tutorials:AJAX_and_Events.
Avesome Thanks..
Tnx,Thanks.
Great tutorial. Thanks very much.
thanks
i want to use other jquery in content of page but not worked
how to do ?
Very Nice Thank you!
Anyone have any ideas on how I could add a link into one of the pages content (div id content) that would function like the regular menu items so it could toggle into another page?
Also can anyone help get the hash BBQ integrated into this? If you use the back button nothing happens on this demo..