HTML5 includes the 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, and add this URL as a history entry.
We will use JQuery to implement this.
$(document).ready(function() {
$("a").on('click', function(evt) {
history.pushState({}, '', $(this).attr("href"));
evt.preventDefault();
return false;
});
});
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 new content
function loadPage(url)
{
$("#divMain").load(href); //divMain is the div containing changeable information.
document.title = html.match(/<title>(.*?)<\/title>/)[1].trim(); //Set title from html
}
Now, we need to listen for the back button being clicked.
$(window).on("popstate", function() {
loadPage(location.href);
});
Final Code is as follows:
$(document).ready(function() {
$("a").on('click', function(evt) {
var href = $(this).attr("href");
history.pushState({}, '', href);
evt.preventDefault();
loadPage(href);
return false;
});
$(window).on("popstate", function() {
loadPage(location.href);
});
});
Source : http://infonexus.in/article-historypushstate-api
