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:
- ID used to identify history entry.
- Title of page (Still not implemented in any browser).
- 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.
- $(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 a new content.
- function loadPage(url)
- {
- $("#divMain").load(href);
- document.title = html.match(/<title>(.*?)<\/title>/)[1].trim();
- }
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: Infonexus.in.