HTML5 and CSS3, Second Edition

(singke) #1
The second argument is a title that we can use to identify the state in our
history. It has nothing to do with the page’s <title> element; it’s just a way to
identify the entry in the browser’s history. Most browsers don’t do anything
with this, so we’ll give it an empty string value.

The third argument is the URL that should display in the title bar. This can
be anything we want. We’ll use the tab’s ID again here because it’ll add a
hash to the URL. If we were working with a back-end server and doing some
Ajax, it might make more sense to give a relative URL like /about or /services.
That way, when a user goes directly to the URL, the back end could respond
appropriately. Since we don’t have any static pages like that, we can’t just
tinker with the URL and have it work.

To activate this new code, we place a call to the addTabToHistory() method inside
the click handler for the links, passing in the tab the user clicked on:

html5_history/javascripts/application.js
$("navul").click(function(event){
vartarget= $(event.target);
if(target.is("a")){
event.preventDefault();
if( $(target.attr("href")).attr("aria-hidden")){
➤ addTabToHistory(target);
activateTab(target.attr("href"));
};
};
});

Although our current code adds a history state, we still have to write the code
to handle what happens when the user presses the Back button.

Retrieving the Previous State


When the user clicks the Back button, the window.onpopstate() event gets fired.
We use this hook to display the tab we stored in the state object.

html5_history/javascripts/application.js
varconfigurePopState=function(){
window.onpopstate=function(event){
if(event.state){
vartab = (event.state["tab"]);
activateTab(tab);
}
};
};

All we have to do is grab the tab out of the object we stored in history and
pass it to our activateTab() function. Hurray for code reuse!

Chapter 10. Creating Interactive Web Applications • 210


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf