Synook

Using the location hash with AJAX

This technique describes how to use the location hash (the bit after the # in the address) to simulate different URLs within an AJAX-based navigation framework. The good thing about the location hash is that it can be changed without the page being reloaded, and having unique page names allows people to bookmark and directly access different parts of your site.

I will write generically in this article, as everyone probably has a differently coded navigation system. Anyway, the addition needed is very simple.

In the function that loads each page, you can store the argument that defines what content to load to the hash (available in the window.location.hash property).

function load(page) {
    window.location.hash = page;
}

This will make every page appear as a different URL in the address bar. Then, when you load the document, you check the hash and if there is something you call the relevant load() function.

window.onload = function() {
    if (window.location.hash.length > 1) {
        page = window.location.hash.split("#")[1];
        load(page);
    }
}

That was easier than even I thought.