arozwalak
11/15/2013 - 12:00 PM

HTML5: History API

HTML5: History API

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>History API</title>
  </head>
  <body>
    <ul>
      <li><a href="img/Penguins.jpg" title="Penguin" data-url="penguin">Penguin</a></li>
      <li><a href="img/Chrysanthemum.jpg" title="Chrysanthemum" data-url="chrysanth">Chrysanthemum</a></li>
      <li><a href="img/Jellyfish.jpg" title="Jellyfish" data-url="jellyfish">Jellyfish</a></li>
    </ul>

    <div class="result">
      <script id="template" type="template">
        <h2>{{title}}</h2>
        <img src="{{imgSrc}}" alt="{{title}}">
      </script>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
    <script>
      ;(function() {
        if (!!(window.history && history.pushState)) {
          var Viewer = {
            template: $('#template').html(),

            init: function() {
              $('ul').on('click', 'a', function(e) {
                Viewer
                  .applyTemplate(this)
                  .updateHistory(this);

                e.preventDefault();
              });

              this.handleState(); //listen of back or forward button
            },

            applyTemplate: function(data) {
              var template = this.template.replace(/{{title}}/g, data.title)
                                          .replace(/{{imgSrc}}/g, data.href);
              $('.result').children()
                            .remove()
                            .end()
                          .append(template);

              return this;
            },

            updateHistory: function(data) {
              var dataToSave = {
                title: data.title,
                href: data.href,
                url: data.dataset.url
              };

              history.pushState(
                dataToSave,
                data.title,
                data.dataset.url
              );
            },

            handleState: function() {
              $(window).on('popstate', function(e) {
                // console.log(e);
                if (e.originalEvent.state) {
                  Viewer.applyTemplate(e.originalEvent.state);
                }
              })
            }
          };
          Viewer.init();
        };
      })();
    </script>

    <script>
    //   history.pushState(
    //     // data
    //     // title
    //     // url
    //     'some data',
    //     'My Page Title', // show in menu of Prewious button
    //     'page'
    //   );

    //   window.addEventListener('popstate', function(e) {
    //     console.log(e);
    //   });
    </script>
  </body>
</html>