Grow your CSS skills. Land your dream job.

Dynamic Page / Replacing Content

Published by Chris Coyier

This article is an update to this old article, which had an ugly demo and a variety of techniques in it no longer probably considered good practices. This new demo is much cleaner, up to date, and fuller featured. Because the old article was a bit of a different scope, I'll leave it alone, just refer to this one.
Update January 2013: There are better practices now, detailed here.

Let's say you wanted to make a website where clicking buttons in the nav would dynamically load some content. Kind of like the organic tabs thing, only the content is loaded dynamically. Say something like this:

View Demo   Download Files

The HTML: It all works without JavaScript

There is no excuse for the navigation of a website to be completely broken without JavaScript enabled. So the best approach here is just to create these pages and the navigation as plain ol' semantic HTML. You know, like it's 2001.

The navigation links to the files that contain that content, and are fully formed functional pages on their own.

<nav>
    <ul>
        <li><a href="index.php">Home</a></li>
        <li><a href="about.php">About</a></li>
        <li><a href="contact.php">Contact</a></li>
    </ul>
</nav>

CSS

This isn't really a tutorial about CSS, but if you want to peak at it, go for it. Shout out to Mike Rundle who shared the CSS for those buttons the other day on Twitter as I was working on this and I stole it.

jQuery JavaScript

The JavaScript is the fun part here! This is the plan in plain English:

  1. When a navigation button is clicked...
  2. Change the hash tag of the URL
  3. When the hash tag in the URL changes...
  4. Fade out the old content
  5. Load and fade in the new content
  6. Update the current navigation highlighting

So why bother with the "hash tag" changing stuff? Several reasons:

  • By using the hashchange event plugin by Ben Alman, we can enable the browsers back/forward button. Super modern browsers support the hashchange event by themselves, this plugin enables support for it for older browsers.
  • We can look for the hash when the page loads and load the appropriate page (i.e. "deep linking")

Prereq

We'll be using the jQuery library, the onhashchange plugin, and then loading our own script last.

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script>
<script type='text/javascript' src='js/jquery.ba-hashchange.min.js'></script>
<script type='text/javascript' src='js/dynamicpage.js'></script>

Code Dump

$(function() {

    var newHash      = "",
        $mainContent = $("#main-content"),
        $pageWrap    = $("#page-wrap"),
        baseHeight   = 0,
        $el;
        
    $pageWrap.height($pageWrap.height());
    baseHeight = $pageWrap.height() - $mainContent.height();
    
    $("nav").delegate("a", "click", function() {
        window.location.hash = $(this).attr("href");
        return false;
    });
    
    $(window).bind('hashchange', function(){
    
        newHash = window.location.hash.substring(1);
        
        if (newHash) {
            $mainContent
                .find("#guts")
                .fadeOut(200, function() {
                    $mainContent.hide().load(newHash + " #guts", function() {
                        $mainContent.fadeIn(200, function() {
                            $pageWrap.animate({
                                height: baseHeight + $mainContent.height() + "px"
                            });
                        });
                        $("nav a").removeClass("current");
                        $("nav a[href='"+newHash+"']").addClass("current");
                    });
                });
        };
        
    });
    
    $(window).trigger('hashchange');

});

Not much to it really. It's only 41 lines with some blanks in there for readability. This even includes adjusting the height of the whole wrapper to adjust for the new content.

View Demo   Download Files

Comments

  1. Simon

    IFrames… O RLY?

  2. Why use jQuery?

    The whole jQuery hash-change functionality seems already built into PHP by using a switch and GET. You therefore end up with ?x=subpage, for example. Using this method also opens up a lot of other dynamic content possibilities which would not require javascript or the jQuery library to run.

    I like the animated transitions, but this seems like a lotta code just for dynamic sub-pages…

    • I guess I’m a little confused about what you are saying. The point of this demo is dynamically loading new content into a page without page refresh. That is AJAX territory, client side technology. PHP is server side technology, incapable of dynamically adding content to a page all by itself.

    • You’re right, it is server-side and it does refresh the page.

      My point is simply that the functionality in both cases is basically the same–when a user clicks a given link, only a certain bit of content (in your example div#guts, in my example, an include) is loaded into the page; an entirely new document (say, about.html) doesn’t need to be loaded.

      In order for this “selective loading” to take place in your scheme, the user must have JavaScript enabled, must load the jQuery library, a plugin, and a few dozen lines of javascript.

      Using PHP none of that is necessary. Unless it’s simply an issue of animation (which, sure, is cool), I don’t see why the jQuery method is better.

    • Really they’re just different methods–good for different things. I just think, in most cases, this is probably not the best way to handle navigation.

      Anyway, great tutorial, as always.

    • LuK

      @Philip,

      I see your point as a developer, but the user on a website like you said (“dynamic PHP”) wouldn’t really recognize that the content is loaded dynamically if I would do it your way…but if you do it with JS/jQuery the users sees “woooah, fading out, sliding up, new content” (biiiig thumbs up, telling all his friends about the site…)…now you tell me what’s more important =)…

    • Alright, so again, the entire point of this entire tutorial is that the content gets loaded dynamically, as in, without a page refresh. If that isn’t a concern, there are a million different server side technologies that can create websites with navigation. For example, see every single CMS ever made in any server side language.

      And why isn’t a good way to handle navigation? It works perfectly fine with or without JavaScript.

    • Goodness gracious. Yes, yes, I know: without page refresh, CMS’s, yada yada. I know.

      I didn’t say this was “not a good way to handle navigation.” It’s a perfectly good method in some cases.

      I said in most cases, this is probably not the best method. Why? Because I doubt it’s as efficient as other, simpler methods of dynamic page population (by dynamic, I don’t just mean “without page refresh,” which seems to me a narrow description).

      Do most of the sites you build use this method? If the answer is no, then I figure you already agree with me.

    • traq

      I wouldn’t even say “in most cases.” AJAX is the “in” thing -much like jQuery- and there are many cases where it would be the preferable way to do things.

      This demo doesn’t really touch it (not its point), but reducing the server load and increasing response time are a few good reasons.

      Look at Facebook, for example. There’s a LOT of server-side stuff (database queries, processing, etc.) going on there, and if they used pure server-side interaction methods you’d be stuck waiting while the ENTIRE page was reprocessed and reloaded every time you looked at a photo.

      With AJAX, the server only has to deal with the part of the page that’s actually changing.

      In any case, having a variety of ways to do things is always good. Some people might want to bring this sort of dynamic interaction on their websites, but not have a host that allows them server-side scripting (e.g., a free host – or like my example above, a page on Facebook).

      And, finally,

      Yes, yes, I know: without page refresh, CMS’s, yada yada. I know.

      Chris is only responding to your comments and asking for clarification where he needs it.

    • James
      Permalink to comment#

      I have not looked at the downloadable code yet, but from what I saw in the video, the JavaScript loads an entire page before extracting the #guts and throwing the rest away. So I have to agree with Philip that it’s more efficient (or, at least, equally efficient) to do this with a template on the server. Except you would lose the “seamless” effect, of course.

      However, it wouldn’t take much work to point to a PHP script with a little parameter that indicates whether to send only the guts or, by default, to merge them into a template for the direct links. This would also eliminate some parsing on the client side.

    • So, like I said:

      “Really they’re just different methods–good for different things.”

    • Tyler Grad

      I think traq means to say your phrasing makes it appear as though you are personally offended by Chris’s tutorial/suggestion, you come off as impolite – just my two cents.

    • traq

      Well, Philip, I do understand your position about server-side includes. I don’t believe you’re trying to be impolite, either. What I’m getting at is that you seem to be brushing aside Chris’ responses: the point being that this tutorial is not simply a “solution” for including a site navigation, but showcases a method for dynamically importing, replacing, and transitioning between external content on the client side. PHP can’t do that (which is not a downfall – just pointing out that it serves a different environment). Client-side scripting is whole other dimension to interactive web design.
      The most immediate example I can think of is changing individual pieces of content on a page (not necessarily the entire page) in a way that is visually elegant and avoids completely reloading the page – which does reduce some demand on the client’s browser as well as the server. If you have a good amount of related content on a single page, would your instinct be to split it into several pages, or use some sort of “tab” or “accordion” feature to remove the clutter? And if you wanted it to be easily maintainable, wouldn’t it make sense to put each section in its own external file (or database entry)?

      …I doubt it’s as efficient as other, simpler methods of dynamic page population (by dynamic, I don’t just mean “without page refresh,” which seems to me a narrow description).

      I think there’s a distinction to be made between “population” and “interaction” here. Both methods are dynamic -I didn’t take Chris’ comment as “limiting” his definition in that way. In the end, though, they are each pursuing their own goals.

    • Right–I guess I phrased things a little too strongly. My initial comment was a sincere question and not just a rhetorical one:

      Why use jQuery?

      You don’t often see this kind of navigation across sites. Ajax methods are used to load sections of pages, but not usually whole pages.

      So let me restate my question:

      If I am trying to make my site efficient and its inner workings clean and logical, would it be better to use this method (where the “cons” are loading a JavaScript library, a plugin, as well as a few dozen lines of additional script), or to use PHP (which, on the downside, means more server requests and the entire page reload). Is using Ajax methods to load a new page (even if the entire page is not loaded) really a better/more efficient approach than using PHP switch navigation? What if the page has more data than just text or a form?

      I honestly don’t know. I tend to guess that for general navigation, PHP is more efficient, but I could be wrong.

      But maybe, too, there is a way of utilizing both of these methods, where the JavaScript “fallback” is a PHP “subpage.”

      Thanks for your opinions–It’s always good to get different perspectives.

    • Keep digging.

  3. Zlatan

    Here’s a little suggestion: why not use the loader image to indicate to the user that something is happening behind the scenes. After all, users are accustomed to seeing that whenever the content of the page is updated; like for example in an ajax web app.

    Cheers mate…and thanks for the nice article :)

    • I feel like the fade out is a pretty good indication that something is happening. But AJAX loading graphics are cool too. Here is a resource:

      http://www.ajaxload.info/

      Also, you could use loading dots:

      http://css-tricks.com/loading-dots-plugin/

    • Grat resources, this what I was always searching for, thank’s Chris!

    • Zlatan

      Yeah, but this is just plain text you’re updating here. What about those pages that contain images and other content that could slow down the loading of the page? How would the whole thing look then?

      btw, tnx for the useful resources :)

    • heldopslippers

      Ehm i don’t think this would work. I mean..
      People with a good internet connection (like every body in the Netherlands) Won’t see the loader. Because It would update so fast. So I think the fadeOut fadeIn option would be the best idea. Then every body (slow or fast connections) will see that the page is updating. And that there is new information.

      Maybe for image loading it would be a good solution. But also in this case I think fading images in would be even better.

  4. This is a really cool function for use within a certain page, ie, want to display a few product pics and descriptions. But as too use it as the actual site navigation in “my opinion” is bad move, only reason I think this is because I like my SEO and only having one page wouldn’t be my cup of tea when it came to optimising my site.

    But still really good and smooth I like. Used something similar on my portfolio page, where as I had this under the main portfolio navigation the had different sections and each container had a list of sites/graphics in it.

    Might use the one you have here though, seems to work smoother than the current code I have! Also that link to ajax-load is a big bonus, I think a loading graphic adds that little extra to it :)

    • I’m no SEO expert, but all three of these pages is fully functioning stand-alone page, that is linked to the in the navigation. That’s what a search-bot would see and follow and read, just like any other website.

    • traq

      I probably wouldn’t use it for navigation – I think it’s better suited to small sections of a page that might need to be independently interactive.

      But since the navigation degrades just fine, I don’t see anything wrong with it (especially since it’s just a demo).

    • Hey Chris!

      I had the same concern and maybe I can clarify the SEO problem. It looks like bots will follow all of your nav links and find new content and successfully spider it. However, the PRIMARY SEO concern is always tags so I’m wondering if it’s possible to use this approach for a whole site and have dynamic title tags to go with the dynamic content.

      Cheers!
      Brian

  5. Anil

    nice post and please tell me how do i show loading image instead of fade effects.

  6. William

    Nice tutorial. I am really looking up to the remake of your wordpress tutorials.

  7. Al

    White text on yellow background?

  8. This is great!

    Is it technically possible to somehow swap the .fadeIn and the .animate lines so that the content fades in after the wrapper resizes.

    I realize that might sound crazy with the code as-is because the wrapper relies on the height of the content to load before it resizes.

    It just seems more visually correct the opposite way so that content will not spill out before the wrapper resizes.

    There has to be another way to get the content height before it fades in…Know what I mean?

    :)

    • Aaron Mc Adam

      That’s exactly the problem with this in Chrome. The final page with the form on it shows a blank page for a second before it resizes and loads the form in.

  9. Hi Chris, could you explain why the “$pageWrap.height($pageWrap.height());” line?
    I didn’t get it…
    Thanks!

    • Sure.

      The #page-wrap div doesn’t have a set height to start with, so by default it just grows to be whatever height it needs to be for the content inside it. That line measures that height, and sets a static height value on it. You won’t notice any change. But then… when the insides fade out to get ready for new content, the #page-wrap won’t collapse upon itself, because now it has a set height.

    • Hey! I’ve get it!
      Thanks for the attention :)

    • Balazs

      I was about to ask the same thing. Great trick. Thanks Chris

    • Nice tip. When I first looked at the code, I didn’t get this, too. Didn’t think about the page-wrap will collapse without specifying height attribute.

      Thank you very much for the tutorial and explanation.

  10. Nice, Chris.

    Always enjoy your tuts and although they don’t look good in any version of IE, they sure are sexy!

  11. Wow, I love this. Really opened my mind to some neat possibilities. Love the effect on that Boulder Acoustic Society… great practical example.

  12. I am very thankful for JQuery for solutions like this. (oh and I’m secretly in love with HTML5 and CSS3, but don’t tell JQuery!)

  13. very nice working thanks for tutorial

  14. Hmmm…. seems like a lot to accomplish something somewhat trivial.

    How about this?

    var $j = jQuery.noConflict();
    $j(document).ready(function(){
    $j(‘a’).click(function(){
    $j.ajax({
    url: $j(this).attr(‘href’),
    success: function(response) {
    $j(‘#content’).html(response);
    }
    });
    return false;
    });
    });

    • Maybe I should have done it as a complete item…

      This seems somewhat lengthy…

      Perhaps simpler?

      var $j = jQuery.noConflict();
      $j(document).ready(function(){
      $j(‘a’).click(function(){
      $j.ajax({
      url: $j(this).attr(‘href’),
      success: function(response) {
      $j(‘#content’).html(response);
      }
      });
      return false;
      });
      });



    • Maybe I should have done it as a complete item…

      <html>
      <head>
      <script type=’text/javascript’ src=’http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js’></script>
      var $j = jQuery.noConflict();
      $j(document).ready(function(){
      $j(‘a’).click(function(){
      $j.ajax({
      url: $j(this).attr(‘href’),
      success: function(response) {
      $j(‘#content’).html(response);
      }
      });
      return false;
      });
      });
      </head>
      <body>
      <div id=”menu”>
      <ul>
      <li><a href=”page1.htm”></li>
      <li><a href=”page2.htm”></li>
      <li><a href=”page3.htm”></li>
      </ul>
      </div>
      <div id=”content”></div>
      </body>
      </html>

  15. DeannRie

    Thank u Chris great tutorial :)
    Спасибо Крис классный урок :)

  16. heldopslippers

    @Chris Coyier
    I don’t know if I should email you about this or just post it here. But You did a lot of (very nice) articles about small problems etc. the last few months.

    Could you maybe do an article sometime about how you would structure your jquery/js in classes. Especially when there is a lot of js involved. It would be very interesting to see a more.. “advanced” article about js/jquery and how click/live events would/should be implemented.

    Greets!

  17. fero

    You only changing class=”current” thought jquery fix that :).

  18. thanks for tutorial, great stuff:)

  19. I wish i knew even half of this!

  20. I have to point out that the contact page does not animate properly in Chrome.

  21. fjpoblam

    Chris. Curious. The end-effect for the client is to display three web pages. What is the bandwidth/server processing/response time improvement (for the website visitor) of your method versus the simple process of three separate pages with button href links?

    • whiskey

      The fact that it could be used to make any CMS have AJAX functionality for some parts of its content, for example.

      Think about it, tag clouds that render lists on the fly, image galleries that change pages without a full reload, search results that come to you faster.

  22. O'Ryan

    oO sweetness.

    in Firefox 3.5.9 on an XP machine the content box has a very blue tint and not gray like your screenshot.

    In chrome however it looks almost identical to your screen.

    but seeing how this isn’t a CSS example… sweet jQuery example! lol

  23. My apologies…

    I made a couple of typo’s

    <html>
     <head>
      <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script>
      <script type='text/javascript'>
       var $j = jQuery.noConflict();
       $j(document).ready(function(){
        $j("a").click(function(){
         $j.ajax({
          url: $j(this).attr("href"),
          success: function(response) {
           $j("#content").html(response);
          }
         });
         return false;
        });
       });
      </script>
     </head>
     <body>
      <div id="menu">
       <ul>
        <li><a href="page1.html">page 1</a></li>
        <li><a href="page2.html">page 2</a></li>
        <li><a href="page3.html">page 3</a></li>
       </ul>
      </div>
      <div id="content"></div>
     </body>
    </html>
    • This is about the same thing in theory, just a little clunkier…

      1) We aren’t using more than one JavaScript library here, no need for .noConflict()

      2) You are loading the entire returned response into the #content div, so basically you’ll be left with a “page within a page” thing going on. The .load() function leverages .ajax() anyway, but allows you to narrow down what you want returned, in our case, just the content only.

      3) This doesn’t have any of the dynamic height adjustment stuff and fading stuff that makes the demo work smoothly.

      4) Since you are attaching three click handlers, you might consider using .live or .delegate instead.

      But otherwise… looks like you have a good grasp on how all this works, so gold star!

    • Having control over conflicting libraries by assigning jquery a handler to me is just good practice.

      Adding animations during the ajax call would be just as effective without the extra libraries, as I do not see any reason to turn our href value into an anchor.

      Using .live or .delegate are other options but why not use the function for what it was designed for?

      Applying height and width attributes to the specified div using CSS will accomplish the same thing which I did not add to keep the javascript simple.

      To each their own I suppose. I figure the less libraries and code will reduce the file size resulting in faster load times.

      Thanks for the tutorial.

  24. DennisEdward

    Hey Chris,

    Thanks for this tutorial, its great.

    I had the same question as skhot^ above, that wasn’t answered. Is it possible to have the content box resize before the new content fades in?

    Thanks..

    • traq

      If you notice, when the new content is larger than the old (e.g., between the “about” and “contact” panels), the box does resize first. When that’s not an issue (going from larger to smaller content), I think it’s fine to have the content show up before the resize – saves some wait time.

    • traq

      … and of course, now that I click Submit, it no longer happens that way consistently. : )

    • DennisEdward

      right, but if you go from “about” to “home”, look closely, and you can see the text before the box resizes..is there any way around this, or no?

      thanks..

    • traq

      yeah, I saw that as soon as I posted. jQuery isn’t my expertise, but I would venture to say that it could be fixed.

  25. I at my folks house today looking at this on their slower than average internet connection and noticed that the Contact page is quite slow to load. Is this because it is a wufoo page and needs to load from their server before it gets to yours?

  26. Jyri

    crap on internet explorer, crap on safari, partly ok on firefox. other browsers unknown.

  27. If you load the page without hash, the current navigation is not indented. Also, if you navigate within this hashless url to the about page, you’ll get:

    /DynamicPage/index.php#about.php

    The navigation still works but I think it’s nicer without a siamese pageURL :)

    Anyways, love the screencasts, Chris! Really honest and inspiring.

  28. I’m not a programmer, and there probably are some “hidden” issues to why you updated the old script…. but I think that was better and looked better. :-) Though, it does take a long time before it load on my webpage. Why is that?

  29. Interesting. I’m starting to see similar techniques used more often. I personally like it. It’s not good for SEO, but works in certain situations.

    • I’d normally delete or bury this, because I don’t like it when people use some ridiculous SEO term as their “name”… however, I want to set the record straight here.

      Using this technique is perfectly acceptable from an SEO perspective. The navigation and content is all regular ol’ links like any other website. The fancy AJAX stuff is purely progressive enhancement that sits on top of that.

    • I have to agree with Mr. Coyier here… SEO really has nothing to do with the navigational content of using ajax to load content within a div.

      Search engine optimization takes place primarily within the header content of the page which does not change in this case.

      Hell in another scenario you could utilize various header content not only within the primary header but also within the dynamically loaded content.

      Meta tags, url submissions, link backs and site maps are your targets with SEO not dynamic content, well unless its flash of course.

    • This would definitely get picked up fine by search engines but you would lose a little PageRank on the secondary pages I think because there would be 2 different links for the same content.

      Obviously inbound links have a lot to do with how Google determines importance. They would have your about page as /about.php whereas someone who comes to your site organically and clicks ‘About’ would see index.php#about.php and would probably use that to link to it.

      It still helps the ranking of your site just messes up the ranking of internal content a little. I would say about 99.9% of web developers should be more worried about actually having good content than crap like this though.

  30. sage

    I DO have javascript enable, yet, a side effet of the “made even for non javascript users” :

    When you middle click on a button, it still works like you would expect (open in a new tab/window) !

    So this is quite important even for javascript users !

  31. Paige

    Hello, I’m always interested in your tutorials but I can’t quite grasp how this all works. Could you in your spare time make a full tutorial video explaining how to make the demo layout? Just so that it becomes more clear.
    I’m not sure when I’m designing a layout I have to take into consideration this code, or code it like normal with css and just add in that 41 line Java code randomly into the main .html home page and it’ll function how it’s supposed to.

    Feedback is much appreciated<3 :3

  32. CraftyDevon

    Thanks for redoing this one Chris, I’ve been looking to give this a go.

    While I can’t contribute directly to this article, I’d like to say thanks for churning out such great content on a constant basis, I visit your site daily (why I missed the article I was looking for is beyond me). I like how you take real world problems you encounter in the course of your work and share the solutions with us; it’s a nice change from a lot of blogs.

    / end praise

  33. Brandon

    Isn’t it better for SEO to have these links like so:

    subpage.php

    Instead of:

    ?x=subpage

    I think that is the most important thing. I’ve always stayed about from using these one page site ideas that load content with a smooth animation, but Chris seems to have a nice solution here.

    If search engines think that they are crawling different pages, and the viewer thinks they are on the same page the whole time. This is awesome…

    - Brandon Rager

  34. hello, im trying to put the slimbox feature on this, but im not able to do it, is there anything that is causing it?

    Thanks!

  35. Dont worry, i made it =) if you`d like to see it you can click the link of my name, and you will see :D

    thanks anyway..

  36. very nice i have been testing this and i like alot hwowever i have to agree with most post so far i just would not use this as a main nav as not all people have java enabled however it works fab for little snippets of info with in a page very nice. look forward to more fab tips like this as it was very good to learn, thanks

  37. Great tutorial, as always.
    This is very nice for static AJAX looking websites.

    Thanks

  38. Hey Chris,

    Great tutorial here, Good to see it revisited and updated with new techniques as mentioned in the screencast.

    Shame to see some readers feel the need to pick and every detail.

    I see this method as perfectly acceptable for a whole site – It works with and without Javascript, which some commenters here have clearly overlooked.

    The Javascript is only used to manipulate the DOM/Browser Defaults and change the content as so clearly explained in this post.

    The fact that the back/forward button works and you can link to pages directly makes this a highly favourable solution for any projects I might need to use this in.

    @Brandon, The changes in page content are appended to the url as a anchor, this does not affect SEO or indexing in anyway as they are individual pages indexed as just that. It’s been clearly explained on the comment threads here.

    Cheers!

    Thanks for the great tutorial/screencast Chris.

  39. whiskey

    Once again the ugly head of the “if it’s good enough for me why approach it differently” monster has made an appearance.

    Of course this technique is maybe not suitable for all cases and scenarios, like pages that rely heavily on ad ‘prints’ for income, but it has it’s own place and I really like it.

    Thanks Chris, you just gave me the perfect idea to upgrade the looks on the kids’ school web page!

  40. Splicker

    Hi Chris!

    I love your tutorial! It’s exactly what I was looking for to create my new site!

    I’m having a problem putting floating divs within the “guts” div though, it seems the dynamic page size changing doesn’t work anymore with floating divs.

    Do you have any tips on how I could get this working at all?

    Thanks again for the awesome tutorial! It’s people like you that make the web a better place!

  41. Tom

    I’ve implemented this code and as soon as i click into a new page, all of my other jquery coded animations get disabled. Is anyone else seeing the same thing?

  42. Kuba

    Tom I have similar problem, I’m trying add gallery script to one of pages and it doesn’t work. I tried flash, ajax, javascript and php galleries :( Is anyone have an idea how to fix this problem ?

  43. is there a way to do this within the content that’s on a page? I want to not have to create separate pages for each of my portfolio pages. I’ve seen this done on other sites, but I can’t seem to make this work.

    any ideas?

  44. Simon

    Just wondering, if I’d like to use this in a website, do I have to have a link back to your website?

  45. Luke

    The one oversight of this method is it’s handling of HTTP Errors. Adding a non-existant filename behind the hash resulted in an empty page – no error message, nothing to alert/educate the user.
    Maybe the AJAX Handler needs to be extended to handle these errors.

    • LuK

      Where did you put this in (in the dynamicpage.js)? Could I also load a page (.html) instead of hardcoding the errormsg into the js…

      So the error-catching would do the same, just loading the 404 page and so on

      thanks for this mod…!

  46. Hi Chris,

    thanks for the screencast. I learned something from it :-)

    Why do we need to bind the ‘delegate’ event to the <a> – tags in the first place? Because the browser default is exactly what we do in this function, isn’t it?

  47. Thanks for the great tut’, Chris.

    I’m trying to bend your tutorial to work within Magento, but can’t seem to get it to work using templates. Don’t know if you have any familiarity with the platform, but am curious if you know of any “aha” steps/tricks to start with or avoid in trying to design for Magento.

    Will keep tinkering though! Thanks.

    • My progress thus far:
      Made a template off your index.html example and have two CMS pages using the new template (dynamic.html). Each Content section of the CMS are pulling in Static blocks.

      But when I’m putting code back in, I noticed that my jQuery noConflict snippit breaks the dynamicpage.js (and/or hashchange.js).

      I changed the function $ to jQuery, but the pages still did a full page refresh, rather than the dynamic loading. How would one go about making noConflict work with this setup?

      Thanks, Chris.

  48. Braden
    Permalink to comment#

    Hey, very nice man thanks for the tut, one thing I noticed was that it works better if you switch a few lines of code. Make it like this instead….

    if (newHash) {
                $mainContent
                    .find("#guts")
                    .fadeOut(200, function() {
                        $mainContent.hide().load(newHash + " #guts", function() {
                                $pageWrap.animate({
                                    height: baseHeight + $mainContent.height() + "px"
                                });
    							$mainContent.fadeIn(200); 
                            $("nav a").removeClass("current");
                            $("nav a[href="+newHash+"]").addClass("current");
                        });
                    });
            };
  49. Streptocock

    I would like to use the code with the prettyphoto gallery script, is this possible with a no “noConflict” command ?

  50. JTK

    Chris,

    Thank you for this excellent article. I am only having one major issue, which I’ll detail below.

    Perhaps it’s just me, but when I click one link in your demo, to enter the “About” page (1 action), if I try to immediately use the back button (in order to reach the “Home” page again), nothing will happen.

    If I however click “About” and then “Home” (2 actions) I will be able to then click the back button to return to “About”.

    From my quick test, the code does not allow a user to use the back button to return from only one page action. A user must navigate to at least two pages before the back button is functional.

    How can I fix this error? Or is this something I’m only encountering on my platform: Mac OSX 10.6.4, Safari 5? That seems unlikely.

  51. Very useful thanks.
    just made a site like this and used hash.js which is great.

  52. Justin
    Permalink to comment#

    This is exactly what I’ve been looking for. Really excellent and robust implementation. Just an fyi, if anyone else is having problems with this code working on their system, try editing the $("nav").delegate("a", "click", function() { portion. For some reason this would only trigger if I clicked the button corresponding to the current page I was on (i.e. it would work for the “contact” button if I was on the contact page; if I clicked any of the other buttons while on the “contact” page it would not trigger the function). Thanks Chris!!!

  53. vsathish
    Permalink to comment#

    Thanks a lot, this is what i want. I need one more help, how can i add preloader while loading page content.

  54. Hey Chris,

    This tutorial is wonderful, thank you very much.

    I was wondering if you’d quickly be able to explain how to implement a loading gif (or CSS animation) whilst the content loads?

    Best,
    Oliver

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".