It does load a new page and the url does update, but when I press the back button, only the url has changed without refreshing but the content doesn't.
$('button').click(function(){
window.history.pushState({}, '', 'page2.php');
$('body').html('<div class="loading.gif"></div>');
//Load Page
$.get('page2.php', function(data){
$('body').html(data);
};
//Edited
$(window).bind('popstate', function(){
//What should I code here??
});
});
The big difference is, that while pushState will create a new entry in the browser's history, replaceState will only replace the current state. As a side effect of this, using the replaceState method will change the URL in the address bar, without creating a new history entry.
The history. pushState() method can be used to push a new entry into the browser's history—and as a result, update the displayed URL—without refreshing the page. It accepts three arguments: state , an object with some details about the URL or entry in the browser's history.
The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history. back() or history. forward() in JavaScript). Browsers tend to handle the popstate event differently on page load.
In an HTML document, the history. pushState() method adds an entry to the browser's session history stack.
I use this to change bar adress and save current state, including current html body, and i reload it on back bouton click without any other ajax call. All is saved in your browser :
$(document).ajaxComplete(function(ev, jqXHR, settings) {
var stateObj = { url: settings.url, innerhtml: document.body.innerHTML };
window.history.pushState(stateObj, settings.url, settings.url);
});
window.onpopstate = function (event) {
var currentState = history.state;
document.body.innerHTML = currentState.innerhtml;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With