HTML History API

Posted by Joe Yates Mon, 18 Jul 2011 18:25:00 GMT

The HTML5 history API allows AJAX-based sites to avoid "breaking the back button". Every time you update the page, you store the new content is the window.history object. When the user presses the back button, you retrieve the current item from window.history and update the page with it.

What follows is an "all-in-one page" Sinatra/jQuery program. You can find the code here.

Run it like this:

$ ruby history_api.rb

The program allows you to browse through pages from a menu: Screenshot

When the first page is shown, the initial content of the container is stored in the history object:

history.replaceState( $( '#container' ).html"s">'', location.href );

As you select links, only the content of the 'container' DIV gets updated. An AJAX call is made to get the content, which is stored in the history object:

   var anchor = this;
    $.get( this.href, function( data ) {
      history.pushState( data, '', anchor.href );
      $( '#container' ).html"s">'data-number' ) );
    } );

Each time the back button is pressed, the content is retrieved and placed in the container:

onpopstate = function( event ) {
  $( '#container' ).html"meta">
    
  • Posted in
  • Tags , , ,
  • Meta permalink, rss, atom