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:

  1. Remove current page content.
  2. 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:

  1. The current content disappears with a cool effect
  2. 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

James Padolsey is JimmyP on Codecanyon
Add Comment

Discussion 568 Comments

Comment Page 9 of 10 1 ... 7 8 9 10
  1. -RMX- says:

    So cool !
    Great work, it’s perfect ! I love it !

  2. wolf says:

    The effect dosent work if you press the backarrow or the forward arrow for that matter.

  3. Dave says:

    Hi guys thx for that great work!

    How can I replace the hash sign “#” in the Adressbar.

    Any solutions?

    Thx 4 ur help.

  4. Romain says:

    Hi !

    Firstly, I need to say that you’ve done a really good job ! This mini-jquery web site is exactly what I was looking for !

    Can I take it (and modified it) for making my own web site ? (No commercial, just personnal)

    Thank you really much in advance and great tutorial !

    • Sean says:

      @Romain – This is a tuturial, of course you can use/modify etc.

      ** If anyone is having an issue with the new updated demo not working, and the back-button functionality within web browsers. I advise using jqueryBBQ. Much better script than the one used in this tutorial.

  5. Very nice, I’ve been looking for this, thanks man, you are rock!!

  6. florian says:

    Great tutorial.

    what is needed to make the back and forward buttons work? I already see the hash tag in the url, so not sure why the page doesnt switch back when using back button.

  7. Clarens says:

    Hey James, thank you very much!!.. this is an useful information, I only have a question, how can I do … to load javascript functions in let’s say.. about’s page? I am trying to do it, but it doesn’t work.. can anyone help me please?

  8. postgah says:

    perfect for portfolio, thanks for sharing

  9. florian says:

    would be great to get the working back button for this. I tried to add the jqueryBBQ but couldnt get it. anybody have this working ???

  10. Nice post. I learn one thing more challenging on different blogs everyday. It can always be stimulating to learn content material from different writers and observe a little bit one thing from their store. I’d want to use some with the content material on my weblog whether you don’t mind. Natually I’ll provide you with a hyperlink in your net blog. Thanks for sharing.

  11. Jonek says:

    Hay i add this code to my website and code run but i click on my menu this js no runing. Slider and file ttf in js have error and no run. why java no run?

  12. lawkout says:

    Great post! Thanks. I have been looking for something like this for some time now.

    However when I change the loaded content pages “about.html” to “about.php” the history gets broken… meaning when I click on the about link and its content is loaded… if the page gets refreshed it reverts back to the default welcome page.

    Can anyone assist with this modification? Thanks in advance.

    • lawkout says:

      I figured it out, sorry I am very new at this. I commented the lines that I modified in “js.js”

      $(document).ready(function() {

      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-4)){ // I modified this line to reflect the length -4
      var toLoad = hash+’.php #content’; // I modified this line to reflect “.php”
      $(‘#content’).load(toLoad)
      }
      });

      $(‘#nav li a’).click(function(){

      var toLoad = $(this).attr(‘href’)+’ #content’;
      $(‘#content’).hide(‘fast’,loadContent);
      $(‘#load’).remove();
      $(‘#wrapper’).append(‘LOADING…’);
      $(‘#load’).fadeIn(‘normal’);
      window.location.hash = $(this).attr(‘href’).substr(0,$(this).attr(‘href’).length-4); // I modified this line to reflect the length -4
      function loadContent() {
      $(‘#content’).load(toLoad,”,showNewContent())
      }
      function showNewContent() {
      $(‘#content’).show(‘normal’,hideLoader());
      }
      function hideLoader() {
      $(‘#load’).fadeOut(‘normal’);
      }
      return false;

      });

      });

  13. Neddy says:

    Nice work, James.

    But I’m wondering I would like to load the hidden contents inside index.html instead of specific pages. Is it possible? Thank you.

  14. Angela says:

    Great work!!! :D
    Can I have an animation from the top to the buttom?

  15. Angela says:

    Hi!
    Great work!!! But… how can I animate it with a moviment from the top to the buttom? :)

  16. Reiko says:

    Hi!
    Someone can help me? How can I replace the hash sign “#” in the adressbar?
    I’m using the “include”, but it doesn’t work whit che #!!!

  17. PhanHau says:

    Thank you for your tutorial, but I have a problem that I can not load a part in external page.

    Ex: I have an index.html and i want to load a session DIV with id “news” in “http://bbc.com” . but it’s not working!

    Can you resolved this problem!!!

    Thanks so much!

  18. christos says:

    hi

    great job indeed.

    I tried to extend the functionality by including also the content div, i.e I modified the code to read

    $(‘#nav li a, #content ul li a’).click(function(){
    ….

    my problem is that if I first click the link found in the #content ul li a tag it works perfectly. However, if a link in the nav li a tag is triggerd first then the link found in the #content ul li a tag opens in a new browser window.

    Any help pls?

    Thank you in advance

    Christos

  19. Gajanan says:

    Great work….I added to my site.But its not working on google chrome please help me…

  20. Lucas says:

    Hey! I’m trying to incorporate Cufón into this, but i only get the styled font on the main page, after loading another it loses the style, including on the frist page… Anyone has been successful into this integration? It would be incredible to have this effect using cufón or font-face… (better cufón).
    I believe this is possible as i have a Banner rotator with jQuery with a similar effect and i successfully integrated cufón into it…

    Thanks!

  21. 2tpower says:

    Hey!
    Pretty awesome tutorial, I don’t know if you’ve noticed but instead of replacing in the original “content” div, you are creating/importing the new div inside the old one.

    new info…

    Why does this happen and how can I solve it?
    Thanks.

  22. 2tpower says:

    Damn i cant post html code here :/ it’s replaced by “new info”…. Let’s try again now without the “”:

    div id=content
    div id=content>new info…/div
    /div

  23. Andrew says:

    Hi,

    I tried to use “FancyBox” and “tinyscrollbar” but it seams they dont work after changing pages, I was reading comments but I still I can not figure out how can I do this.
    is there anyone can help me out ?

    regards,

  24. Rodrigo says:

    Andrew, I’m facing the same problem, How to make some jquery script work into the loaded div after the user click…
    Anyone could help?

  25. Marco says:

    Andrew and Rodrigo, I have the same problem…
    Could anyone write a working script with livequery and fancybox, please?

  26. Rodrigo says:

    The includes are Always loaded by the “index.html” but if you write a javascript function there and try to call it on the rendered Div won’t work :/
    not even a javascript Alert work, anyone could help us to use the javascript inside the div?

  27. Hi all,

    I was searching for a solution for the fact that other js/ jquery stuff doesnt work when loaded in the div.
    My problem was with lightbox so here goes.

    added some // at the bit i changed have fin with it.

    $(document).ready(function() {

    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(‘LOADING…’);
    $(‘#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’).find(‘#gallery a’).lightBox({txtImage: ‘Lightbox’}).end().show(hideLoader); // here you call the lightbox script again because lightbox searches 4 links on page load, well you are not loading a new page so you got to tell to search again.!!!!!!!!!!!!!!!
    }
    function hideLoader() {
    $(‘#load’).fadeOut(‘normal’);
    }
    return false;

    });

    });

    • Rob says:

      hey Tycho

      i’m using shadowbox plugin and wordpress, how do i achieve what you did with lightbox?

      thanks

    • Marcel says:

      Hi Tycho,

      Thanks for your advice on getting other js scripts to work within the content changing js files.

      I have tried your code you submitted as I am also trying to use lightbox.js within one of the changing content pages but it doesn’t seem to work. (gallery)

      How did you seem to link the two as I get an error saying <Object doesn’t support property or method <lightBox>>and points to your updated line of code:

      function showNewContent() {
      $(‘#changercontent’).find(‘#gallery a’).lightBox({txtImage: ‘Lightbox’}).end().show(hideLoader);
      }

      I am running the latest lightbox.js

      Your help will be greatly appreicated!
      Marcel

  28. Mr Curious says:

    Great tutorial!

    Is there any way to modify the code to allow for the color of the ‘active’ link to change.

    Thanks

  29. Jon Roland says:

    I want something, such as a jquery script, that executes a python script that does nothing more than immediately display a line of HTML chosen based on the url of the calling HTML page, immediately upon page open or refresh, a different line for each URL. Initially, it can show just the URL, but the eventual solution is to use the URL as a dictionary key to select the line as a value of that dictionary.

  30. ngusum says:

    To make it better look like the demo, I substituted the .hide(‘fast’) method with .slideUp(‘fast’). You can also use slideUp(‘slow’) if you want a slower sliding effect. Similarly, replace .show(‘normal’) with slideDown(‘fast’) or slideDown(‘slow’). Pretty cool tutorial. Thanks.

  31. Sean says:

    How can i prevent users from mashing the links and keep loading the content. I basically want it to disable after it is clicked and enabled after the content has been fully loaded.

    Thanks in advanced!

  32. That is very attention-grabbing, You are an excessively professional blogger. I’ve joined your feed and look ahead to in the hunt for extra of your great post. Also, I have shared your site in my social networks!

  33. softpixel says:

    this script doesn’t work with jquery 1.6. Any solution to fix this problem?

  34. Great tutorial!

    Is there any way to modify the code to allow for the color of the ‘active’ link to change.

  35. whoah this blog is great i like studying your posts. Stay up the great work! You recognize, many individuals are hunting round for this info, you can help them greatly.

  36. Seasharp says:

    Hi everyone!

    Its a very good tutorial, and it works fine, but i have a problem.
    I loaded up the htmls to my website, and sometimes, when I click to a button, the text doesnt change.
    I clicked on the same button about 6 times, then i waited 20 seconds, and then the text changed, but I want it to change automatically.

    PLS give me a solution, pls I’m noob in building a website(that’s why I’m here xD).

  37. Romain says:

    Hello everybody,

    If you have a problem to use Fancybox or another library.

    Create New Function

    function display(who){
    $.fancybox({
    ‘href’: who,
    });

    return false;
    }

    On your link :

  38. Ram says:

    Hello,

    I want the slide effect Right to Left (NOT Bottom to top) will any buddy help me

    Thanks

  39. Is there any way to modify the code to allow for the color of the ‘active’ link to change.

    Thanks

  40. how can i modify this code is there a way?
    appreciate it

  41. hasan says:

    perfect for portfolio, thanks for sharing

  42. how can i modify this code is there a way?

  43. Richard says:

    Hello

    Your code has solved, I think, a problem I was having. However, the content from some pages does not load, while others load up fine.

    I can see no reason why on earth it is doing this. they are all being subject to the same code and the same conditions.

    what is strange is, if i put the with the id=”content” in the page template, then only some of the work. If I put exactly the same div around the content on each individual page in the content editing area for that page (which is in effect just doing exactly the same thing as putting it in the template) then they all work fine.

    ideally I want to be able to put it in the page template, as it may cause issues including it within the content code of each page individually.

    Has there been anything of a similar issue you have come across

    I can send you a mock up example of the problem if you need.

    Many thanks for any help

    Richard

  44. Is there any way to modify the code to allow for the color of the ‘active’ link to change.

  45. سئو says:

    Is there any way to modify the code to allow for the color of the ‘active’ link to change.

  46. Keoal says:

    This works fine on localhost but when it is uploaded to a live server there is a flicker during the content transition where the old content appears for a split second after the transition before the new content appears.

    Is there any way around this?

  47. H'ssaini says:

    this code dosen’t work in opera and Chrome. so if any one has a solution for that i’ll be grateful .

    • El garch says:

      To make it work on Chrome, copy your folder project to the server, if you’re using wamp, you should copy it to the WWW location.

      Best Regards

  48. Hannah Tsui says:

    Hello, Are you interested in the monetization of your RSS feed or online e-newsletter?

  49. George says:

    Hi I have tried it but it doesn’t work in my case. The .load doesn’t wait for the callback to finish it seems. So as soon as I click, I get the hide show of the same content, then the loading fades in and then the next content shows.
    Could it be that this happens due to the size of my div? I am loading a few images and text on each link

Comment Page 9 of 10 1 ... 7 8 9 10

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.