Page Navigation for AJAX driven websites using HTML5 History API

Page 1

HTML5 History API provides a way to maintain history of the current session. This information can be used for page navigations. It will really come handy when you are using AJAX to load pages and want to have browser navigation (back/forward) active. Here we will simulate an AJAX like behavior, with sections acting like pages. Consider it to be like retreiving JSON data and dynamically adding them to DOM. Using HTML5 History API, we will maintain the history and use it for navigating back and forth using browser's navigation button. We will use 'hashchange' event and hashtags for urls.

Before proceeding, it would be better if you have some idea on how jQuery works because, we'll use jQuery for DOM manipulation. However, I'll give a brief introduction to jQuery in the next page.

Note that this example doesn't use AJAX. It simulates that behavior. For making AJAX requests you need a server to which the webpage will sent requests using XMLHttpRequest (XHR) and the server will respond by sending data preferably in XML or JSON format.

Page 2

This is a brief introduction to jQuery and its usage. jQuery is mainly used for DOM manipulation. We will use jQuery's ready() method. You listen for the ready event and once the DOM elements are ready to be manipulated, you proceed with the code. The general syntax is like $(document).ready(callbackFunction);

We can use anonymous function and the code will now look more familiar

$(document).ready(function () {
    //all you code will go here..
});
You can select an element with an id similar to the way you use CSS selectors.
var myElem = $('#myElemId') will make the 'myElem' variable hold the html element with id 'myElemId'.

Now jQuery is out of the way, we can focus on page navigation.

Page 3

As you can see that this tutorial itself works based on the HTML5 history APIs. Now let's focus on the core ideas behind page navigation and history. To navigate using the browser's default navigation buttons, i.e, by using the back and forward buttons, there must be a change in the URL. The navigation buttons get active only if the URL of the current window (page) changes. When we use AJAX (JSON), the URL of the current window doesn't change. So we won't have any active navigation, which implies, no history as well. That's where the History API comes to our rescue. When we make an AJAX call or when we show some page change, we'll add a new hashtag to the current URL using 'pushState' function. This will append a hashtag to the current URL, but won't navigate to that URL.

To add hash to the URL without causing the page navigation, we'll use window.history.pushState(null, "", "#hashtag") method. We need to be concerned mainly about the third parameter, which is the hashtag string. After that we'll trigger a 'hashchange' event $(this).trigger("hashchange");. We'll listen for that event, and when it gets captured, we can get the current hash value from window.location.hash and do the necessary action, like populating contents, hiding elements etc.

Next we'll discuss history API methods in more detail.

Page 4

These are some of the notable functions in the history API.

window.history.pushState(data, title, url)

@param data
data is generally something that is specific to the context of the particular page. Say in the first page you retreive data in JSON format. Say our data is:

{
    page: '1',
    title: "Tutorial",
    category: "HTML5",
    desc: "intro"
}
So when we want to navigate to another page we can save that data so that, the next time when we revisit, popstate will fire and you can retreive the data through event.originalEvent.state object.

@param title
The second parameter can be any string.

@param url
Can be hashtag or a string. Note that you can't change the baseURI, or it will throw SECURITY_ERR exception. Otherwise it will be easy for URL spoofing. This value will be appended to the baseURI without loading the appended URL. This will activate the browser history, so that we'll have active back and forward button.

The 'popstate' event
When you navigate in history, popstate will be fired, and the data corresponding to the state will be popped. These data objects are kept in a stack using the pushState function explained above.

window.location.hash
This variable will contain the current hashtag of the window

The 'hashchange' event
'hashchange' event will be fired whenever there is a change in navigation, i.e if you travel back and forth in history, each time the hashchange event will be fired. So we can listen for the hashchange event and depending on the hash, which we can obtain from window.location.hash, we can take the necessary action. Since we already listen for the hashchange event, we'll trigger the event when the user clicks the page's anchor link to go to that particular page. Otherwise, we can write a separate way to deal with clicking anchor links as opposed to clicking back/forward buttons, which isn't really necessary. So that's the reason we trigger 'hashchange' event manually.

window.history.replaceState(data, title, url)
This function is same as that of push state. But instead of pushing a new state to the stack, it will replace the top state (from the stack) with the one specified in this function.

window.history.forward() will go one step forward in history and window.history.backward() will go one step backward in history. We are not using these methods in this tutorial.

View Source