HTML5 and CSS3, Second Edition

(singke) #1

Setting the Default State


We have a couple of issues to resolve. When we first bring up our page, our
history state is going to be null, so we’ll need to set it ourselves. Also, the URL
changes whenever we click a tab, but if we press Reload, the Welcome tab
shows up instead of the tab we want. So, on page load we check the URL, see
what tab should be open, and set it.

html5_history/javascripts/application.js
varactivateDefaultTab=function(){
tab = window.location.hash||"#welcome";
activateTab(tab);
window.history.replaceState({tab:tab},"", tab);
};

If there’s no value for location.hash, we give it the default value. We then use
history.replaceState() to set the tab. This works like pushState(), but instead of adding
a new entry, it replaces the current one.

Now, to keep things nicely organized, let’s create an init() function that calls
these new methods and the original configureTabSelection():

html5_history/javascripts/application.js
➤ varinit=function(){
configureTabSelection();
➤ configurePopState();
➤ activateDefaultTab();
➤ };

Then we just need to call init() to start things off.


html5_history/javascripts/application.js
init();

When we bring up the page, we can cycle through our tabs and easily use
the Back button to return to previously visited tabs—thanks to the History
API.

Falling Back


This works in Chrome, Firefox, Safari, and Internet Explorer 9 and higher.
The best solution out there for legacy browsers is History.js,^2 which creates
a cross-browser layer to make this functionality work. However, it’s not a
drop-in replacement. To use it, you include the library and then modify your
code to use it instead of the browser’s history object. Thankfully, it follows the
specification very closely, and eliminates the need for you to check for history


  1. https://github.com/browserstate/history.js/


report erratum • discuss

Preserving History • 211


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

Free download pdf