3

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.

Charles
  • 48,924
  • 13
  • 96
  • 136
frenchie
  • 46,331
  • 96
  • 283
  • 483
  • This can help you: http://html5demos.com/history And this too: https://github.com/remy/html5demos/blob/652fd1c914a475d0d5e96b76d81db383190806c0/demos/history.html – Wilk May 13 '12 at 12:41
  • We already have a tag to cover the HTML5 History API, please do not add another. – Charles May 14 '12 at 03:56

2 Answers2

3

Ok, I made this example for you. Start with HTML code (index.html):

<!DOCTYPE html>
<html>
    <head>
        <title>Stackoverflow</title>
        <script type="text/javascript" src="sof.js"> </script>
    </head>
    <body onLoad="load();">
        <ul id="menu">
            <li><a href="/home">home</a></li>
            <li><a href="/about">about</a></li>
            <li><a href="/blog">blog</a></li>
            <li><a href="/photos">photos</a></li>
        </ul>
        <button onclick="back ();">Back</button>
        <button onclick="ff ();">Forward</button>
        <div>
            Action: <span id="action"></span><br/>
            Url: <span id="url"></span><br/>
            Description: <span id="description"></span>
        </div>
    </body>
</html>

And then the javascript file (sof.js):

var menu, url, description, action, data, historyState, act;

function $ (id) {return document.getElementById (id);}

// Updates infos
function update (state) {
    action.innerHTML = act;
    url.innerHTML = state.url;
    description.innerHTML = state.description;
}

// Goes back
function back () {
    act = 'Back';
    history.back ();
}

// Goes forward
function ff () {
    act = 'Forward';
    history.forward ();
}

function load () {
    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 called
    window.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 only
        if (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 navigation
    var 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:

  1. Manipulating the browser history
  2. History object
  3. History howto
Wilk
  • 6,287
  • 8
  • 45
  • 65
  • I think there's some problem with jsFiddle because when I click on an anchor, the page is loaded although if it shouldn't... I suggest you to try into your localhost, creating the index.html and sof.js files in the web server root directory ;) It works for me :D – Wilk May 13 '12 at 15:48
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>
    <style type="text/css">

    .Panel{
       width:200px;
       height:100px;
       background:red;
       display:none;
       color:white;
       padding:20px 20px;}

    .ChangeButton{
       margin:10px 10px;
       float:left;}   

    </style>

   // add reference to jquery.js file here 
   // <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>        

    <script type="text/javascript">

    var TheURL; // 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.

    var MyDivs = { // this object stores the name and the URL of each possible state
       ShowPanel1: {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 rewrite

    window.addEventListener('popstate', function (event) {

       //cross-browser nightmare here!!!!!
       var HistoryState = 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);

    });

    function DoChange(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 action
       case 1:
           SwitchPanel(MyDivs.ShowPanel1.panelID);
           history.pushState(MyDivs.ShowPanel1.panelID, "", TheURL);
           // history.pushState(MyDivs.ShowPanel1.panelID, "", MyDivs.ShowPanel1.DisplayURL);
           break;
       case 2:
           SwitchPanel(MyDivs.ShowPanel2.panelID);
           history.pushState(MyDivs.ShowPanel2.panelID, "", TheURL);
           // history.pushState(MyDivs.ShowPanel2.panelID, "", MyDivs.ShowPanel2.DisplayURL);
           break;
       case 3:
           SwitchPanel(MyDivs.ShowPanel3.panelID);
           history.pushState(MyDivs.ShowPanel3.panelID, "", TheURL);
           // history.pushState(MyDivs.ShowPanel3.panelID, "", MyDivs.ShowPanel3.DisplayURL);
           break;
       case 4:
           SwitchPanel(MyDivs.ShowPanel4.panelID);
           history.pushState(MyDivs.ShowPanel4.panelID, "", TheURL);
           // history.pushState(MyDivs.ShowPanel4.panelID, "", MyDivs.ShowPanel4.DisplayURL);
           break;
       }
    }

    function SwitchPanel(PanelID) {

       if (PanelID === null) {return false;}

       $('.Panel').hide();
       $('#' + PanelID).fadeIn('medium');
    }

    </script>
    </head>

    <body>

    <input type="button" id="Button1" class="ChangeButton" value="panel 1" />
    <input type="button" id="Button2" class="ChangeButton" value="panel 2" />
    <input type="button" id="Button3" class="ChangeButton" value="panel 3" />
    <input type="button" id="Button4" class="ChangeButton" value="panel 4" />

    <div id="PanelContainer" style="clear:both;">

       <div class="Panel" id="Panel1">panel 1</div>
       <div class="Panel" id="Panel2">panel 2</div>
       <div class="Panel" id="Panel3">panel 3</div>
       <div class="Panel" id="Panel4">panel 4</div>

    </div>

    </body>
    </html>

Upvote if it works for you.

Enjoy!

frenchie
  • 46,331
  • 96
  • 283
  • 483
  • Interesting how you can use popstate event to get it working on any browser ;) However, in your example, there's no url navigation as you requested. – Wilk May 16 '12 at 20:34
  • @Wilk: ok, I added that URL update functionality; I decided not to use URL rewrite for my app. And of course it doesn't work in IE but I wasn't looking for that, just something simple that I can put on my site. For IE, I just tell users that hitting "back" will log them out with a cancel or proceed message. My app will launch in October and by then IE10 should have launched. – frenchie May 16 '12 at 21:51
  • many thanks! I just edited my solution with your suggestion :D Now it works good on Chrome too ;) – Wilk May 24 '12 at 15:49