How to Load In and Animate Content with jQuery
Tutorial Details
- Technology: jQuery
- Difficulty: Intermediate
- Completion Time: 1 hour
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.
XEROX CODEStep 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










jQuery Lightbox Evolution only $12.00
Events Calendar Pro - Wordpr ... only $30.00 
Hi!
Great script but I’m having a problem, I would know if it’s possible to move the effect from left to right?
Thanks a lot!
I’m also trying to get $_GET to work. I’m currently using the jquery.history plugin and it appears that it strips out the ‘?’ character so I don’t think using it is an option. If anyone who’s much better at javascript than me wants to try getting it to work then I think trying to use the jquery.address may be an option.
It can be found here: http://www.asual.com/jquery/address/
Here’s an example where $_GET has been used with it: http://web.elctech.com/2009/06/02/deep-linking-pagination-with-jquery-address/
Cheers guys
Is this possible as a wordpress plugin?
This was the first tutorial I read about jquery, and it was enough to allow me to start messing with UIs using jquery UI. The explanations are very clear, and the concepts of jquery are well explained!
Thanks a lot!
It is possible to put swf flash animation to this ?
It is a great script but i have a problem.
If i try to move ….. code inside to the ..the script doesnt work.
It would be good to make dinamic menu bar in relation to the page loaded in id=content
Isnt there a method to resolve it?
It is a great script but i have a problem.
If i try to move ul=”nav” code inside to the id=”content” .. the script doesnt work.
It would be good to make dinamic menu bar in relation to the page loaded in id=”content”
Isn’t there a method to resolve it?
This is a gear effect but it seems to jump slightly is the text is longer on one page than the next, any fix for this?
Is it possible to manipulate the loaded content before showing on the page.
Say changing h2 to h1 tag of page heading ?
The font seems to be slightly lighter when the content is loaded. Anyone has this problem as well? is there a way to solve this? thanks
Hey great tutorial, all is working…it’s just some of the content seems to be loading slow…and others fast?? Anything I can do to help this out? Because when the show function completes I still have the same content as the previous page still in the div…then boom it changes. It just defeats the show/hide effect all together.
Here is the link to my demo page, let me know what you think…
http://www.jpkbeats.com/loadContent/index.html
I’m having exactly the same problem as well…
It flickers the “old” page once really ugly. Please let me know if you have found a cure for this, thanks!
There seem to be some typo’s in the code that prevent the callback functions to fire.
Change this line “$(‘#content’).load(toLoad,”,showNewContent())” to ‘showNewContent’ without the brackets ( ), and do the same for ‘hideLoader’.
If you look closely this is correct in Step 4 but in Step 5 it suddenly changes …
Also, I don’t know why you have to append the loading image each time … maybe you could put this outside of the click handler and just fade it in and out.
Other than that, great tutorial, over 2 years old and still very useful
Gee, thanks Robin! I’m not so familiar with javascript – your advice did the trick thanks!
(For some reason I cannot reply to Robins entry…)
I appreciate the tutorial and script, and I’d love to learn how to set the CSS class of or to “active” — and to change the class of the formerly active or to “inactive” – when the associated content is being displayed. Jquery has a useful toggleClass() function, but I’m not sure how to single out the clicked link. (I imagine I could set all links in the #nav to “inactive” before setting the clicked link to “active”)
Any help would be appreciated!
Thanks,
Tim
Hi Tim!
Here’s a way to do it:
In the “$(‘nav li a’).click” function add this line:
$(“#nav li a”).addClass(“active”).not(this).removeClass(“active”);
This code adds the class “active” to the tab you click on and removes it from all other tabs.
Here’s the CSS you’ll need to style the active tabs:
#nav li a.active {
//Styles here
}
Also, add class=”active” to the welcome link in the homepage, to the about link in the about page, and so on. Otherwise visitors without javascript won’t be able to admire your active link styling.
Hope this is helpful.
Simon
Sorry to disturb you, I have not published the site cause it’s still work in progress. The script now works good on 4 of the 5 most popular browser, but it won’t work on Google Chrome 5 stable release.
When, from the index.html page I click on the nav to go in another page, like portfolio, it won’t load the content div. It works only when I load from the same page to the same page, like clicking when I’m on “Index.html” and I want to refresh the same page, clicking on Index.
Does anyone now how to solve this issue? Sorry but I’m a noob at html and Jquery, doesn’t know how to do it by myself
Sorry for the consecutive message but I can’t modify or delete the other one.
When I tried to put online my site on my web-host, it works also on Google Chrome.
Now it works perfectly on all the five major browser. Really thank you James, you’re just a genius…
Hi this is how i wrote my display function.
$(function(){
$(‘dynamic.content-loader’).wrapper();
});
function wrapper() {
$(‘#wrapper’).append(‘LOADING…’);
$(‘#load’).fadeIn(‘normal’);
}
Any comments.
I’m having trouble with this script. I have it working just fine, but it doesn’t seem to play nice with other jquery scripts. For example: if I use jquery UI tabs to display some content on the index.html, it works fine. If I then browse to another page and back it no longer works. I think it’s the URL change (history plugin?) that breaks it.
For example:
mysite/index.html = other scripts work fine.
mysite/index.html#index = other scripts do not seem to work.
Another example would be if I placed the tab script on the portfolio page, then navigate to it:
mysite/index.html#portfolio = it does not work.
mysite/portfolio.html = it works just fine. Although this page cannot be navigated to, it must be typed in the address bar manually.
This isn’t just with the tabs script, it seems to be for several scripts.
Any help with this?
I have this exact same problem I think.
I can’t use hyperlinks inside the content when I navigated to index.html#index. It only works when my navigation is on index.html.
When I click the hyperlink in the content when i’m in index.html#index i just go to the hyperlinks destination..
Any help?
Such a great tutorial! I too am having the same problem as these guys above though. Any chance of a little inside info on solving this problem?
@ Xarcell Did you every shed any light on this issue?
I tried taking out the internal javascript and making it external but still no fix.
It is breaking my category filter that I am using to organize my portfolio.
IF you would like to contact me we can try to work it out… really bumming me out. I have tried other methods of ajax content loader and they continue to give the same problem:
mysite/index.html = other scripts work fine.
mysite/index.html#index = other scripts do not seem to work.
I was having the same problem. What I was trying to do was when a new “page” is loaded to have various different jqueryUI / forms / etc displayed. But none of the javascript was working correctly.
This is because javascript will not work if you load it into a page (using .load() ).
To fix this you will need to incllude any javascript you will be using on any of the pages that are linked within your main page (index.html in the example). Then any javascript you want to use within any loaded pages you will need to use .delegate() .
For example If you add the following to about.html page:
Click
$(‘#myButton’).click(function(event) {
alert(‘doSomething’);
event.preventDefault();
});
this will not work. To get this example to work you will need to do the following:
on index.html add the following (to the header, anywhere other then #content).
$(“body”).delegate(“#myButton”, “click”, function(e){
alert(‘doSomething’);
e.preventDefault();
});
Then on about.html just include your button:
Click
When you click on the about link you will see the button, and it will function correctly too!
@ urbn
Like everyone else I can’t seem to get this guide to play well with other scripts. I tried to integrate your suggestion with no luck. I am not by any means great at javascript so chances are I didn’t do a good job. I was tring to use the prettyPhoto lightbox with this tut.
$(document).ready(function(){
$(“a[rel^='prettyPhoto']“).prettyPhoto();
});
@ urbn
Like everyone else I can’t seem to get this guide to play well with other scripts. I tried to integrate your suggestion with no luck. I am by no means great at javascript so chances are I didn’t do a good job. I was tring to use the prettyPhoto lightbox with this tut.
standard issued script placed before end body tag
$(document).ready(function(){
$(“a[rel^='prettyPhoto']“).prettyPhoto();
});
If you could take a look it would be greatly appreciated.
I’m having the same issue.
Anybody got any ideas?
Hi James,
First of all , thank you very much for this great tutorial.
I have a requirement like this.
Out of the external files(pages) where I load the contents from, can I keep one page loaded by default and highlight the relevant link. I am using the ‘active’ class to highlight the link and it is working perfectly when I click the links.
woooaaaawww
Yeah, I’m having the same problems as Xarcell, Wouter, and Chris Learey.
Anyone get a fix on this?
Thanks a lot for this how-to ! Works like a charm !
Is there a way to have this feature for another associated with another navigation menu in the same page without conflict ?
I dont get?!?, well yes i do. It worked perfectly in all browsers, then suddenly. It stopped, firefox just wouldnt show me the #content. Its so frustrating! It just will not show and google chrome does the same, execpt it shows the #content box but with nothing inside it!!!
What have i done wrong? Help? http://www.redjack.webege.com/homepage.php check the script and email me back please! big_ben_rocks@hotmail.co.uk
@ James Padolsey
when you load with this script you load the div #content of the other page in the div #content of the current page. It looks better if you load the content that is in the div #content of the page you’re loading from and put it in the div #content of the current page so you don’t end up with a div #content nested in another div #content
You understand what i mean?
nice….but, how to disable effect????i’m using just the loader
is here any body know farsi.i have great probmle.plz help me
Thanks for the easy to understand tute… I’m trying to get more into jquery – it’s really awesome.
The only problem I noticed with the above example is that the ‘#portfolio’ links won’t work if someone has javascript turned off ie. if they link to the page via that method -> http://nettuts.s3.amazonaws.com/011_jQuerySite/sample/index.html#portfolio they will just get the Welcome page.
Can this be done with an additional next and previous button to flick through the pages? the idea i have is for a portfolio where loading the entire portfolio at one woul dtake ages. something like this would work well with next and previous.
good tut though!
What If I had a link in the and it links to a page that I want to load into that div? I tried inserting a link in there and it just takes me a brand new page instead of loading into the div.
For example:
mysite/index.html = other scripts work fine.
mysite/index.html#index = other scripts do not seem to work.
Please HELP !!
I’m having the same exact problem!
Somebody help us!!!
I was running into a problem trying to use the JqueryUI API. The problem was when you try clicking on a link the new content would not be loaded into the page.
To solve this problem replace the following line in the .js file
$(‘#content’).show(‘normal’,hideLoadering());
$(‘#content’).show(hideLoadering());
Basicly remove ‘normal’, and the links/pages work correctly.
This is what I was looking for! Many many thanks.
Great work! Thanks for guys like you – this is very very nice to have everyging in one place!
Hello everyone, my problem is that putting a flash movie all’intenro the div does not work:
eg:
About —> about.html has a flash movie
portfolio —> portfolio.html is normal
if I click on ok portfolio.html
While portfolio.html about.html for the movie about not working, you can not see.
I think it’s due to # # and about portoflio .. boh .. I do not know ..
how to remove the symbol “# link.html link?
thanks!
Hi,
How To Hide before cilck link ? Example :
After Click To any Link about , … etc. Show and add icon for close or hide .
Thanks