Html5 History Api Demo
Solution 1:
Ok, I made this example for you. Start with HTML code (index.html):
<!DOCTYPE html><html><head><title>Stackoverflow</title><scripttype="text/javascript"src="sof.js"></script></head><bodyonLoad="load();"><ulid="menu"><li><ahref="/home">home</a></li><li><ahref="/about">about</a></li><li><ahref="/blog">blog</a></li><li><ahref="/photos">photos</a></li></ul><buttononclick="back ();">Back</button><buttononclick="ff ();">Forward</button><div>
Action: <spanid="action"></span><br/>
Url: <spanid="url"></span><br/>
Description: <spanid="description"></span></div></body></html>
And then the javascript file (sof.js):
var menu, url, description, action, data, historyState, act;
function$ (id) {returndocument.getElementById (id);}
// Updates infosfunctionupdate (state) {
action.innerHTML = act;
url.innerHTML = state.url;
description.innerHTML = state.description;
}
// Goes backfunctionback () {
act = 'Back';
history.back ();
}
// Goes forwardfunctionff () {
act = 'Forward';
history.forward ();
}
functionload () {
menu = $ ('menu');
url = $ ('url');
description = $ ('description');
action = $ ('action');
// State to save
historyState = {
home: {
description: 'Homepage'
} ,
about: {
description: 'Infos about this website'
} ,
blog: {
description: 'My personal blog'
} ,
photos: {
description: 'View my photos'
}
};
// This is fired when history.back or history.forward is calledwindow.addEventListener ('popstate', function (event) {
var hs = history.state;
if ((hs === null) || (hs === undefined)) hs = event.state;
if ((hs === null) || (hs === undefined)) hs = window.event.state;
if (hs !== null) update (hs);
});
menu.addEventListener ('click', function (event) {
var el = event.target;
// Prevents url reload
event.preventDefault ();
// Handles anchors onlyif (el.nodeName === 'A') {
// Gets url of the page
historyState[el.innerHTML].url = el.getAttribute ('href');
// Creates a new history instance and it saves state on it
history.pushState (historyState[el.innerHTML], null, el.href);
act = 'Normal navigation';
update (historyState[el.innerHTML]);
}
});
// Handles first visit navigationvar index = location.pathname.split ('/');
index = index[index.length-1];
if (index !== '') {
historyState[index].url = location.pathname;
history.pushState (historyState[index], null, location.pathname);
act = 'First visit';
update (historyState[index]);
}
}
And a .htaccess for direct request:
RewriteEngine On
RewriteRule ^home$ ./index.html
RewriteRule ^about$ ./index.html
RewriteRule ^blog$ ./index.html
RewriteRule ^photos$ ./index.htm
Each time that an anchor is clicked, a new history instance is pushed onto history stack and an object (called state) is saved with it: the local url is changed but the loading is stopped by 'event.preventDefault()' method. Further more, some information (as URL, Description and Action) are updated.
Then, with 'back' and 'forward' buttons, you can travel through the history and use 'history.state' (or event.state or window.event.state, it depends on browsers) to retrieve the current state.
And, in the end, if you type the entire url directly into the address bar, it works as the same with the above .htaccess ;)
I hope this example helps you ;)
Ciao
Wilk
PS: For further details:
Solution 2:
Ok, I created what I think is the SIMPLEST form of history API demo.
It can't work in jsfiddle because it needs to run in its own window. It will however work if you copy-paste the code in notepad, add a reference to jquery where indicated, and save it on your desktop as an html file. Of course, it doesn't work in IE, but we all know that. I've put in two versions: the one that works without the URL rewrite component (it'll work from your desktop) and I've also commented out the version where you can manipulate the URL. For the latter, you need to run it from a server, either remote or local.
I've struggled to get it working across all browsers because Chrome, Safari and Firefox work differently! Here's the code:
<html><head><styletype="text/css">.Panel{
width:200px;
height:100px;
background:red;
display:none;
color:white;
padding:20px20px;}
.ChangeButton{
margin:10px10px;
float:left;}
</style>
// add reference to jquery.js file here
// <scripttype="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><scripttype="text/javascript">varTheURL; // if you don't need URL rewrite, then we're always going to // show the same URL. Remove this line if you want URL rewrite.varMyDivs = { // this object stores the name and the URL of each possible stateShowPanel1: {panelID:'Panel1', DisplayURL:'/panel1'},
ShowPanel2: {panelID:'Panel2', DisplayURL:'/panel2'},
ShowPanel3: {panelID:'Panel3', DisplayURL:'/panel3'},
ShowPanel4: {panelID:'Panel4', DisplayURL:'/panel4'},
};
$(document).ready(function () {
TheURL = document.URL; // You can remove this line if you're doing// URL rewritewindow.addEventListener('popstate', function (event) {
//cross-browser nightmare here!!!!!varHistoryState = history.state;
if (HistoryState === null || HistoryState === undefined) {
HistoryState = event.state; }
if (HistoryState === null || HistoryState === undefined) {
HistoryState = window.event.state; }
SwitchPanel(HistoryState);
});
$('.ChangeButton').click(function () {
DoChange(parseInt($(this).attr('id').charAt(6), 10)); });
DoChange(1);
});
functionDoChange(ButtonID) {
switch (ButtonID) {
// here's the 2-version option: // toggle the commented and uncommented history.pushState// lines to see the change to the URL in actioncase1:
SwitchPanel(MyDivs.ShowPanel1.panelID);
history.pushState(MyDivs.ShowPanel1.panelID, "", TheURL);
// history.pushState(MyDivs.ShowPanel1.panelID, "", MyDivs.ShowPanel1.DisplayURL);break;
case2:
SwitchPanel(MyDivs.ShowPanel2.panelID);
history.pushState(MyDivs.ShowPanel2.panelID, "", TheURL);
// history.pushState(MyDivs.ShowPanel2.panelID, "", MyDivs.ShowPanel2.DisplayURL);break;
case3:
SwitchPanel(MyDivs.ShowPanel3.panelID);
history.pushState(MyDivs.ShowPanel3.panelID, "", TheURL);
// history.pushState(MyDivs.ShowPanel3.panelID, "", MyDivs.ShowPanel3.DisplayURL);break;
case4:
SwitchPanel(MyDivs.ShowPanel4.panelID);
history.pushState(MyDivs.ShowPanel4.panelID, "", TheURL);
// history.pushState(MyDivs.ShowPanel4.panelID, "", MyDivs.ShowPanel4.DisplayURL);break;
}
}
functionSwitchPanel(PanelID) {
if (PanelID === null) {returnfalse;}
$('.Panel').hide();
$('#' + PanelID).fadeIn('medium');
}
</script></head><body><inputtype="button"id="Button1"class="ChangeButton"value="panel 1" /><inputtype="button"id="Button2"class="ChangeButton"value="panel 2" /><inputtype="button"id="Button3"class="ChangeButton"value="panel 3" /><inputtype="button"id="Button4"class="ChangeButton"value="panel 4" /><divid="PanelContainer"style="clear:both;"><divclass="Panel"id="Panel1">panel 1</div><divclass="Panel"id="Panel2">panel 2</div><divclass="Panel"id="Panel3">panel 3</div><divclass="Panel"id="Panel4">panel 4</div></div></body></html>
Upvote if it works for you.
Enjoy!
Post a Comment for "Html5 History Api Demo"