How to Load In and Animate Content with jQuery

May 25th in Javascript & AJAX by James Padolsey

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.

Author: James Padolsey

I'm a freelance web developer based in Hampton, UK. I write about and enjoy front-end web development. Most of what I write focuses on my favorite topic, JavaScript! To read my blog or find out more about me please visit my site!


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


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

User Comments

( ADD YOURS )
  1. Mark Provan May 25th

    Nice. Could really use this on my new project. Thanks alot.
    Mark


  2. Tuna May 25th

    Awesome. Keep it coming, I love it.


  3. Ben Griffiths May 25th

    The final effect looks great, especially with such a small amount of code, thanks :)


  4. Razvan May 25th

    Excellent, thanks for the tut! :)


  5. Fanou May 25th

    Really nice effect ! Thx for the Tutorial !

    But do you know how to do that with Mootools ?


  6. Claudiu May 25th

    great work! I love it!


  7. Omkar May 25th

    Wow thats brilliant!


  8. ijajaja May 25th

    Awesome!! Thanks for sharing !!!


  9. Alvito Falcon May 25th

    Nice. I can really use this on the next app i make …. will feature a link on my blog as well.


  10. Robin May 25th

    James,
    Thanks much for the tutorial. Good example of the power of Jquery!

    On another note… has anyone built something like this and ran it through Google Analytics to see if it tracks the clicks to the individual page sections? If it doesn’t work, could be a big issue with clients.


  11. Robin May 25th

    Sorry to double post,

    @James

    Is there a way to make this step back through the section transitions when hitting the browser’s back button?


  12. Dmitri May 25th

    Great, however browser’s back button functionality gets broken when you use such trick. I guess it would be very nice to provide the fix in following tutorials.


  13. D. Carreira May 25th

    Thanks! I was looking for something like this a month ago…

    Great tutorial!

    David Carreira


  14. makalu May 25th

    it’s amazing! really cool


  15. Shaein May 25th

    Great work! Looks very nice!

    There’s just this little thing..

    When switching to another page the content doesn’t seem to change. And I’m using Opera 9.50 beta. That could be the reason :P.
    Version:
    9.50 beta
    Build
    9945

    It did work on Fx beta 3 and IE7 though.


  16. James May 25th

    Thank you for all the kind comments!

    @Robin -

    Very important issue raised. If this functionality was ever integrated into a real-life project you’d have to seriously consider the usability of the website. The tutorial allows bookmarking (with the hash vaues) but doesn’t cater for the BACK button.

    There are various solutions available on the web although I didn’t think of it as necessary to include them in this tutorial seeing as it was more of an introduction…

    If you’re interested then have a look here:
    - http://dev2dev.bea.com/pub/a/2006/01/ajax-back-button.html
    - http://www.isolani.co.uk/blog/javascript/FixingTheBackButtonThatAjaxBroke

    As far as I can see, it seems to be about manipulating the browser history object.

    And that’s a good question about Google Analytics, if they don’t yet offer it maybe it would be something for them to consider for the future.

    @Fanou -

    I’m sure it could be achieved with mooTools, - Have a look at the ajax class - http://docs.mootools.net/Remote/Ajax.js#Ajax


  17. Medium May 25th

    I once asked something like this to be made as a tutorial so thank you net tuts for this :)

    @James
    When i go and type #about or #portfolio it does not work. I tried in firefox 3 & IE 6.
    It changes URL and content when i click on the nav buttons, but it does not load different content when i type the URL manualy. And this is a very big thing.


  18. Peter Butler May 25th

    Excellent tutorial and loads of help, thank you


  19. Tony Mathew May 25th

    Amazing effect, thanks for teaching us!
    It will sure come useful when i finally decide to make a portfolio


  20. Zé Miguel May 25th

    Cool Tutorial! Tanx!
    Can you tell me the font you used in the banner though? thanx


  21. Patrick May 25th

    The problem with this technique is that when you click on the back button of your Browser, nothing happens. Even though the effect looks great and is pretty cool, I do not see why one would implement this effect on a Website. But I have to admit, it looks cool.


  22. Chris Coyier May 25th

    Extremely nice, great work!

    I did a site like this one, and it was suggested to me to use the jQuery History plugin, which restores the functionality of the “back” button in the browser which would be great for this tutorial.


  23. mike May 25th

    Interesting tutorial and a pretty cool effect but not very practical.
    Using this you lose all your page titles, the ability to highlight the current page in the navigation menu, and, as Robin already pointed out, you may as well cancel your subscription to google analytics.
    Having said that, it does give food for thought and with a lot of work suggests some interesting possibilities.


  24. Peter May 25th

    Overall a very nice effect, but I do perceive one flaw in this tutorial: the content should not “reappear” until the content of the new page is loaded. What happens when you click the link is that the previous page’s info reappears and then changes to the new content a second or so later. Is there a way to delay the content reappearing until it actually loads?


  25. Shane May 25th

    Interesting effect, but as a few people have pointed out, from a usability point of view, I don’t feel it’s best to theme an entire site around the effect.

    That said, your tutorial is well written and is yet another example of jQuery in action. I’ve done similar stuff in the past, but have concentrated on smaller areas of content.

    thanks :)


  26. James May 25th

    @Medium - That is because the page does not reload when you type a hash value in and the hash values are only checked upon page load. The hash values take effect when the page loads… So if you were to click this link it would take you to the #about page –> http://nettuts.s3.amazonaws.com/011_jQuerySite/sample/index.html#about

    If you want to automatically and continually check the hash value you could add a timeout function to do that. (e.g. maybe check every 500 milisecs) - I have not tried this so I don’t know if it would work… Typing the hash value in seems to work in Safari3 - I havn’t tried any other browsers.

    With little support available for Ajax apps across browsers you might feel uncomfortable using this solution for an entire site but it is still very useful for smaller widgets and inner content.

    @mike - Changing the page title is possible and having active link styles on the nav menu is also possible. - I have not included them in this tutorial though because I didn’t want it to get too crowded ;) … The google analytics thing would be quite an issue and there are various other usability issues, but it still (like u said) is food for thought and hopefully this is a taster (no pun intended) of things to come in the future of the web.

    @Shane - I think you’re right about it not being a perfect solution for an entire site. Like you pointed out, this effect is more suited to smaller areas of content. :)


  27. Jaswinder Virdee May 25th

    Cool, nice and simple site, if i were to use this i would have my different social profiles embedded in them or for simple data maybe to show off an app


  28. Danny May 25th

    This is really cool


  29. Bruce Alrighty May 25th

    Great tutorial.

    I think the effect would better suited in a sidebar though, instead of the whole website.


  30. shofr May 25th

    I wonder how this would effect SEO. A spider would see each separate HTML file, which might not be ideal depending on the content.


  31. Tony Mathew May 25th

    When I add this script to a page as well as the ligthbox script they conflict and whichever script is first always seems to win.
    Is there any way for this script to work in harmony with the lightbox script on the same page?


  32. Louie May 25th

    Wow I like this tutorial. Many thanks :)


  33. Joefrey Mahusay May 25th

    Great tut. Two thumbs up!


  34. Snorri3D May 25th

    nice tutorial :)
    more AJAX related would be great :D


  35. Andrew May 25th

    Your tutorials on this and PSD Tuts are consistently awesome. Thanks!


  36. x May 25th

    Just pointing out some errors in the tutorial:
    - The link is missing in Step 4 ( “It should work perfectly now. You can see an example of it here: [LINK]“)
    - Code is not indented properly - the wrapper div in the first block, the big code blocks in step 4 and 5
    - You should extract the file-name using regexp (or indexOf etc.) instead of just removing the last 5 chars:
    href.replace(/(\..+?)?$/,”)
    or
    href.slice(0,href.indexOf(’.'))
    .. What will happen if the href contains full path or links to a different domain (e.g. http://www.google.com/ )?


  37. Adam May 25th

    One of the BEST on this site so far! Great Stuff!


  38. Eric Orr May 25th

    Very cool effect.


  39. Marko Novak May 26th

    I don’t know if anyone mentioned this already, but with this method you disable browser back button. Which is in my opinion bad option. Other than that, it’s a very nice tutorial.


  40. sinan May 26th

    thank you.goog tutarial.


  41. eod May 26th

    cool, perfect for portfolio, thanks for sharing


  42. James May 26th

    THANKS FOR ALL THE COMMENTS!!! :)

    I have had a go and using the jQuery history plugin (Thanks for the tip Chris Coyier!) I have made it possible to use the back button.

    The new script (js.js) is actually shorter now, and you can get it here: http://www.qd-creative.co.uk/uploads/projects/ajaxtut/js.js

    You need to download the history plugin for this to work: - http://www.mikage.to/jquery/jquery.history.js

    So you should be linking to three scripts at the top of your document now:

    I’ve tried this out on Firefox and Safari (seems to work very nicely) …

    I haven’t updated the original tut files or the tutorial because it might just end up confusing people.


  43. James May 26th

    @Tony - Lightbox uses the prototype library which uses the same ($) function caller and so there is a “conflict” between jQuery and Prototype.

    I’m sure there are other solutions available but this ( http://codingforums.com/showthread.php?t=120309 ) thread seems to offer some help. (POST#4 is probably what ur after)


  44. Ahmad Alfy May 26th

    It looks cool!

    but I’m worried about accessibility and seo stuff

    I suggest it should be used within web apps … where users have to login to acess data


  45. James May 26th

    Just a note, I have created a fix to the various usability issues (like using the back button) - I have detailed the fix in a comment, but it is awaiting moderation… (because it has links in it I think)


  46. Martin Sarsini May 26th

    wow what a tutorial, very simple and effective to understand, I wish many people could explain things like you
    and of course great effect, I like it also because it’s fully accessible. of course it’s a great thing for some kind of websites, or some areas of websites, very usable but it needs to be used in the right way and not just because it looks “cool”


  47. linzprod May 26th

    Hats off to you!

    Nice tut. thanx a lot.


  48. jd May 26th

    Very nice tutorials! Many thanks!


  49. BroOf May 26th

    I love you :D And i love JQuery :D! Thank you for posting this!


  50. Miguel Pereira May 26th

    This site is very good.

    I have helped many times :)

    MIGUEL PEREIRA


  51. Tom May 26th

    Great example, I’m glad to see that it works even with javascript disabled. Well done!


  52. David May 26th

    Nice, but two comments:

    $(document).ready(function() { is not so clever to use unless you wrap it as a private function. Many other frameworks uses the $ sign and there will be conflicts. It’s much better and recommended to use jQuery(function($) {.

    Also, you break the important history features in the browser (back/forward buttons) by not bothering to take control of the browser history. It would be much cooler if you included history support (also good for bookmarking).


  53. Evan May 26th

    This is a very well done example. Things get far more complex when you content is more complex or could contain new content that needs javascript functionality but it is a good start.

    The most recent beta versions of google analytics have added event tracking. I find they have come in very handy with pages of this style.

    For example when a user clicks the about in the navigation element at the top you send an event out to google analytics to track that click on the about section. It tracks both unique and total events.You can do this around the same time you make the request for the new content. You still loose a bit of google analytics functionality but at least they now provide a better way to track this type of interaction.


  54. Qw3rTy May 26th

    I have a problem with this…
    When I try to add other JS libraries they don’t work -.-’

    sry for my english :X


  55. JC May 26th

    Very cool look, thanks


  56. Nico May 27th

    Slick! Thanks


  57. Dennis Gaasbeek May 27th

    Well written article, thanks James! Wow this site has learned me a lot, I visit it daily now eagerly awaiting new tutorials :)

    I applied your fixes and now the back button works fine (verified in Firefox, IE6 and IE7). Only (minor) issue I have found is that when I download the example site I cannot link directly to the HTML files in my browser (e.g. portfolio.html) because it will just load the index.html file. Strange thing is, on the live example on this website it does work so I will look into it some more to see if you have applied some other fixes as well ;)


  58. JamesS May 27th

    Building a whole site like this is not a good idea, but the technique certainly has its uses.

    Putting the SEO, usability and accessibility drawbacks aside, you can get around the Google Analytics problem mentioned in a previous post by using separate virtual funnel paths for each link - just add something like this as an unobtrusive onclick event (the same as you would do for non-html documents/multimedia files):

    var pageTracker = _gat._getTracker(”UA-12345-1″);
    pageTracker._initData();
    pageTracker._trackPageview(”/my/virtual/url”);


  59. Christian Mejia May 27th

    Yes! Real slick!


  60. Lamin Barrow May 27th

    Waaw.. that’s pretty cool. Thx for all your time and effort. :)


  61. Zé Miguel May 27th

    Just Noticed the WebSite doesn’t work in Opera =(


  62. James May 27th

    Thanks for the nice comments!! :)

    @Ze Miguel - I think the script posted in comment-1498 works in opera. Let me know. :)
    Link to comment: http://nettuts.com/javascript-ajax/how-to-load-in-and-animate-content-with-jquery/#comment-1498


  63. James May 28th

    @JamesS - Thanks for the Google-Analaytics fix!!! :D

    I don’t see this solution as an SEO issue like some of you have mentioned though - For example when Google crawls the site it will see each individual page (.e.g, about.html, index.html etc.). You could stick a Javascript redirect on all pages which redirect the user to the index page (if they have JS enabled) with the associated hash. So if they were on the about.html page they would be redirected to index.html#about …

    The usability issue has been fixed with the history plugin for jQuery - see comment 1498 ….

    With a bit of work I do think this could be an awesome solution for a small site! It’s better than using Flash in my opinion plus you get to use tonnes of animations…


  64. aldomatic May 29th

    Great stuff! - I will defenitley find use for this on future projects.


  65. Robonoob May 29th

    Neat!

    However, it is not working on Opera. Same page always shows for all the button I clicked.

    As for IE, the old content rolls down first and then the new content flashes out.

    Anyway. This is a great tutorial.


  66. Jason May 30th

    James,

    I have a quick question for you regarding your jquery syntax. I’m a real n00b so please don’t take offense. Why is it that for the .hide call (in the callback function) you don’t need the empty brackets? But for the .load call you need the empty brackets when calling the showNewContent callback function?

    I can’t figure it out, thanks!


  67. glo yniestra May 31st

    It looks just great, soberb and elegant…..Thanks


  68. Qbrushes May 31st

    i need to try this out!


  69. Jacob Gube June 1st

    Anyone interested in using this but hate how asynchronous content-loading breaks the back button (since you’re really not navigating away from the URL when you load the content), check out this article that discusses this issue in brief and provides a solution:

    A Better Ajax Back Button Solution

    Basically, checking the url for the #hashValue at set intervals and load the appropriate content based on the URL value (if the content is not already loaded). It’s a psuedo-fix for the back button.

    I’m not sure about how it’ll affect performance if you’re running this function every 0.5 seconds — I leave it up to you to check your web page performance with your favorite tool or method (I’d personally use Firebug to profile client-side processing times with and without the script).

    Live demo can be found here.


  70. Jacob Gube June 1st

    @Qw3rTy - Might be a conflict with $() shorthand notation. What other JS libraries are you using? Other libraries like Prototype JS uses $().

    Try doing something like:
    var $j = jQuery.noConflict()

    then replacing all $()’s with $j()’s.

    OR…

    Just use the full name instead of the $() shortcut - i.e. jQuery(selector).


  71. Will June 1st

    This tut confuses me. I mean did you write that “js.js” script or did you find it on jQuery’s site? You never told us. I’m not a coder , but I’m trying to learn and “tutorials” like this don’t make it easy. Can any of you guys suggest some websites for someone who isn’t a coder to help them learn this stuff? It seems that a lot of the tuts here are assuming the everyone here knows how to code. hello? give us “lesser beginnings” some help please.


  72. BrianH June 2nd

    Is there anyway to get Flash to work with this? I tried to add a Flash content window to the main body of a test site using this technique, and when it gets linked to from one tab/button to another the Flash is treated as not even existing. ie the load effect doesn’t even drop down to accommodate for where Flash is.


  73. jay June 3rd

    How would I get this to work to open a php file? It’s fine using html documents but as soon as I try and load a php file, it doesn’t work…


  74. Sean Vosler June 3rd

    Help! Help!

    Alrighty… so i think i’ve done everything correct! I may have the location of the #wrapper and the #content wrong, but It seems to make since to me where I have them… if anyone could help me I’d greatly appriciate it!

    Its live at http://www.vezign.com/ {still under construction btw}

    first one to solve gets a cookie!! :D

    ps. the css file has the #load {
    display: none;
    position: absolute;
    rightright: 10px;
    top: 10px;
    background: url(images/ajax-loader.gif);
    width: 43px;
    height: 11px;
    text-indent: -9999em;
    }


  75. C June 3rd

    Nice tutorial!
    I have one question though. When I try this in Internet Explorer, when the animation loads a new page, the font changes to a weaker and less slick looking one…Does any one else have this problem? I’ve tried on multiple computers with multiple versions of IE, with no success. It works fine in Firefox though.

    Thanks


  76. John June 3rd

    How can i make the nav bar extend to touch the content border? Thanks.


  77. James June 3rd

    @Sean Vosler - It seems you’re using them in the right place. I would suggest changing your script to the new (improved) one: http://www.qd-creative.co.uk/uploads/projects/ajaxtut/js.js - For this new script to work you’ll need to download the jQuery history plugin - available here: http://www.mikage.to/jquery/jquery.history.js and link to it in the HEAD of ur document…

    @John - You’ll need to adjust the padding on “#wrapper”…

    @Jay - Change this line:


    window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);

    to THIS:


    window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-4);

    Jay, I would suggest changing to the new script which solves various other issues.

    @Jacob Gube - That setInterval solution won’t work… I originally tried something like that but for some reason it didn’t recognize that “window.hash” was changing. The best solution, I think, is to use one of the history scripts available. The jQuery history plugin seems sufficient: http://www.mikage.to/jquery/jquery_history.html

    @Will - Check out Tizag.com … or Lynda.com …. or w3schools.com


  78. Jan June 4th

    It works fine for me, except in the Konqueror browser. The first page works, but then links look like this in Konqueror:

    index.html##about

    Notice the two “##”, there is one too much, and although the effects are working, the content will not be refreshed…

    Maybe someone has a solution for this??

    Thanks

    Jan


  79. John June 4th

    Okay I made the nav bar extend to touch the content border. My new question is, How would you go about loading a php into this page?


  80. Jan June 5th

    Forget my last comment, it is a bug in konqueror :)

    And i finally learned something: Ajax not for me :D

    (Too unclean, too hackish imho, especially when using frameworks like jQuery… It is nice to play with, but not something i consider for a production site…)


  81. Chad S June 5th

    Hi all. I decided to experiment with using this technique for my personal homepage.

    It looks like the #content div is preventing another jquery function from working properly: in my case, the fancybox lightbox.

    Basically, if I put in a fancybox link outside of the #content div, the fancybox function works fine, but if I use it inside the #content div, it doesn’t work.

    Any thoughts on how I can work around this?

    To see what I mean, you can see it on my homepage, chadswaney.com

    Any help would be appreciated@


  82. Ben Tomas June 6th

    I have the same problem as C…When I implemented this tutorial in Internet Explorer, when Ajax loaded the page, the text changed fonts to a weaker unspecified one. Even the demo here looks like that in Internet Explorer. Is there some solution to this? After all, these effects should be cross browser.

    Thanks


  83. James Baldwin June 7th

    Excellent tutorial, and as said, impressive for the small amount of code.

    Not sure how SEO friendly a system like this would be for a whole site, but I will definitely find a use for it on a smaller scale

    Thanks again


  84. brian June 8th

    I’m modifying this template to fit my site; however, the fadeIn animation looks best against a dark background in IE6. Is this an IE6 specific bug, or is there a way to make it blend in with white backgrounds more smoothly? The loading animation also doesn’t play nice with IE6, so maybe it’s just specific to IE?


  85. brian June 8th

    Regarding the Cleartype bug in IE6, I was able to get around it by setting a background color for the and elements. :-)

    New request, however, is how to make hyperlinks within #content behave links links in the navbar. Thanks in advance!


  86. Jason June 9th

    James,

    Just wanted to ask something that some of the other comments have touched upon and that is how to make content that has javascipt inside it load properly? In one of my ‘contents’ I want to have a Javascript gallery plugin. It works when I put it outside of the ‘content’ div but breaks when it goes inside it (where it’s supposed to be if I want the animation to work upon load).

    I think the problem lies in the fact that the gallery app needs to called in the document ready part of jquery… any suggestions?

    Thanks


  87. Brian June 10th

    Love the script and tutorial James! Quick question, is it possible to make the transition a fade and y-axis scale only? Wanted to eliminate the x-axis scaling, just find what is controlling it.

    Best and fantastic work!


  88. James June 11th

    The clearType problem in IE6 is apparently fixable by specfying a background color (I haven’t checked this though).

    @Brian - The X-Axis animation is achieved by the “show()” function. You can create custom animations in jQuery using the “animate()” method. For example:
    $('#content').animate({left:'+=200px'}); - You can find more info on this here: docs.jquery.com/Effects


  89. Chris Coggan June 11th

    Although i haven’t implemented it yet, this is looking very promising, even from an seo perspective. Will let you know how it pans out. Thanks for the fresh approach!


  90. Brian June 11th

    Awesome, thanks for the quick response and great work James!


  91. Harry June 11th

    Hey James- Appreciate the work you’ve put into this and answering the commenters. I have one snag. On my site here, http://stacytroke.com , I get a 400 bad request error when I click on the blog link in the navigation menu in my Firefox browser. all other links work fine except for the blog button. it’s supposed to take you to http://stacytroke.com/blog . Not to mention that it seems that the content starts to float further and further downwards as I continue to click on the nav menus. thouhts?


  92. Brian June 12th

    With Jason on this question… is it possible to call and run JS Lightbox or tooltips from the AJAX’d info loaded in the “content” div? I have the scripts for JS tooltips working on their individual pages, but as soon as they are loaded in the content div, it breaks. Thoughts anyone?


  93. Kenny June 12th

    I really like this idea and I’ve been trying to get it to work with an embedded flash movie, but it doesn’t take that from the source html page and put it in the main one. Should it work? Is there the capability for this to work and if so any hints (or better still solutions)

    Kenny


  94. David June 13th

    Kenny,

    I’m having the same problem. I can’t get it to load flash content correctly.

    If anyone knows how to do this, I would appreciate the help as well.

    Thanks!
    David


  95. Rohil June 15th

    James…there is a big problem. There are is an extra div created each time a link is being created. I used this onone of my websites, and each time I load the same page, an extra div is created and since the div already has some padding, it is shifting more to the left since new padding is being applied. Use the Web Developer plugin to see the div order after every click and you will know.

    This seems to be due to the .append staement used.

    Please help.
    Rohil


  96. Rohil June 15th

    Anyways, never mind. I bypassed the problem by removing the padding from #content and wrapping it in an external and div and then applying the appropriate styling. Thanks for the tut !!


  97. zohaib June 15th

    superb, fantastic


  98. Patrick June 16th

    [EDITOR'S NOTE: I have not checked Patrick's ZIP files, listed below. So publishing this comment is not an endorsement of these files. Use at your own risk.]

    Drawing from suggestions in these comments, a friend of mine Andre and I repackaged a version of the final product of this tutorial to have the back button fixed, lightbox already included and working, and compatibility for php and wordpress. It can be downloaded at http://www.tigerofdoom.com/ajaxContent/ajaxContent.zip and http://andrebluehs.net/ajaxContent/ajaxContent.zip

    It’s also live at both http://andrebluehs.net/ajaxContent/ and http://www.tigerofdoom.com/ajaxContent

    Also, we had no trouble loading flash in the content div, though that’s not shown in our repack.


  99. Rohil June 16th

    I second Peter.

    “Overall a very nice effect, but I do perceive one flaw in this tutorial: the content should not “reappear” until the content of the new page is loaded. What happens when you click the link is that the previous page’s info reappears and then changes to the new content a second or so later. Is there a way to delay the content reappearing until it actually loads?”

    I have tried to remove this problem but not successful yet. Instead of hiding and showing contents, i am using fadeTo effect. But same problem.

    Rohil


  100. James June 16th


  101. Rohil June 18th

    hey James,

    Although I had customized the script a lot, your ne