History.pushState API in HTML5

History.pushState API in HTML5 

 
HTML5 includes history.pushState API, which allows you to add history entries and change the URL currently displayed in the browser.
 
Syntax:
    history.pushState({id: 'idGivenToEntry'}, 'title of page', 'c-sharp-objective?page=2');
 
Attributes:
  1. ID used to identify history entry.
  2. Title of page (Still not implemented in any browser).
  3. URL of the page to access (It can be relative or absolute) [Note: URL should be internal].
If the current URL in the browser is http://infonexus.in/c-sharp-objective?page=1, the URL will become http://infonexus.in/c-sharp-objective?page=2, similar to as if a link had been followed. Add this URL as a history entry.
 
We will use jQuery to implement this.
  1. $(document).ready(function()     
  2. {    
  3.   $("a").on('click',function(evt)     
  4.     {    
  5.     history.pushState({}, '', $(this).attr("href"));    
  6.     evt.preventDefault();    
  7.     return false;    
  8.     });    
  9. });     
It uses history.pushState to add a history entry to the browser with the href attribute of the link.
 
In most sites, there are header and footer areas, which don't change, and a main area, which changes.
 
Create a function to load a new content.
  1. function loadPage(url)    
  2. {    
  3.    $("#divMain").load(href); //divMain is the div containing changeable information.    
  4.    document.title = html.match(/  
  5. <title>(.*?)<\/title>/)[1].trim(); //Set title from html    
  6. }     
Now, we need to listen for the back button being clicked.
  1. $(window).on("popstate", function() {    
  2.    loadPage(location.href);    
  3. });     
Final code is as follows:
  1. $(document).ready(function() {     
  2.     $("a").on('click', function(evt) {    
  3.         var href = $(this).attr("href");    
  4.         history.pushState({}, '', href);    
  5.         evt.preventDefault();    
  6.         loadPage(href);    
  7.         return false;    
  8.     });    
  9.     $(window).on("popstate", function() {    
  10.         loadPage(location.href);    
  11.     });    
  12. });     
Source: Infonexus.in.