views:

48

answers:

0

Here is my solution for this. I'd appreciate any criticisms so I can improve. Here is the markup:

<div id="menu>
    <ul>
        <li><a rel="foo" href="folder/foo.html">Foo</a></li>
        <li><a rel="bar" href="folder/bar.html">Bar</a></li>
    </ul>
</div>
<div id="ajax-content></div>

And the jQuery using http://benalman.com/projects/jquery-hashchange-plugin/ to ensure cross-browser support for the hashchange event.

$(document).ready(function () {
    $(window).bind('hashchange', function () {
        if (location.hash == '#' || !location.hash) {
            var content = 'folder/index.html #content';
        }
        else {
            var content = ('folder/' + location.hash.slice(1) + '.html #content');
        }
        $('#ajax-content').load(content);
    });
    $('#menu a').click(function (e) {
        window.location.hash = $(this).attr('rel');
        e.preventDefault();
    });
    $(window).trigger('hashchange');
});

When javascript is off or when the page is getting crawled the full content page is returned by the link. When javascript is enabled, the url hash is changed to the value of the rel attribute. This is then picked up by the hashchange plugin which loads the appropriate content into the div of interest.

One side-question: How can I prevent the page from scrolling to the top after new content is loaded in via AJAX?