HTML5 and CSS3, Second Edition

(singke) #1

Tip 30


Tip 30. Preserving History


The HTML5 specification introduces an API to manage browser history.^1 With
it, we can add entries into the history, replace entries, and even store data,
which we can retrieve when we revisit the page. This is great for single-page
applications where things update dynamically but you still want to allow the
user to use the Back button.

In Tip 15, Creating an Accessible Updatable Region, on page 98, we built a
prototype for AwesomeCo’s new home page that switched out the main content
when we clicked one of the navigation tabs. One drawback with the approach
we used is that there’s no support for the browser’s Back button. If we click
a tab, pressing the Back button in the browser takes us to the previous web
page we visited, rather than the previous tab. Let’s use the History API to fix
the example code we built in that tip.

Storing the Current State


When a visitor brings up a new web page, the browser adds that page to its
history. When a user brings up a new tab, we need to add that new tab to
the history ourselves. The current home-page prototype already has the code
for switching tabs. We just need to add code to store the tab the user selects.
Create a new method called addTabToHistory():

html5_history/javascripts/application.js
Line 1 varaddTabToHistory=function(target){
2 vartab = target.attr("href");
3 varstateObject= {tab:tab};
4 window.history.pushState(stateObject,"", tab);
5 }

This function takes in the tab the user clicked on. We use the href attribute’s
value to add a history state to the browser using pushState(), which takes three
arguments. The first argument is an object that we’ll be able to interact with
later. We’ll use this object to store the ID of the tab we want to display when
our user navigates back to this point. For example, when the user clicks the
Services tab, we’ll store "#services" in the state object, under a property called
tab.


  1. http://www.w3.org/TR/html5/browsers.html#history


report erratum • discuss

Preserving History • 209


Download from Wow! eBook <www.wowebook.com>

Free download pdf