I've been reading about the HTML5 history API and so far, I haven't found a simple working demo that shows the mechanics with code.
Here is a working jsfiddle: 4 buttons and 4 divs. When the user presses a button, it shows the corresponding panel.
What I'm looking to do is:
1) rewrite the URL so that when the user is on panel 4 the url ends with /Panel4
2) make the back button and forward button work with the history API.
I know there's the history.js plug-in but I want to understand how the API works in its simplest form.
Hopefully, the jsfiddle will help others who'll come to this page looking for a code demo.
Thanks.
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:
Upvote if it works for you.
Enjoy!
here you can see an simple example HTML5 History API: https://stackoverflow.com/a/9470183/1236238
Ok, I made this example for you. Start with HTML code (index.html):
And then the javascript file (sof.js):
var menu, url, description, action, data, historyState, act;
And a .htaccess for direct request:
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: