pushState test
by doug65536
HTML
<button data-where="A">Go to virtual page A</button>
<button data-where="B">Go to virtual page B</button>
<button data-where="C">Go to virtual page C</button>
<button data-purpose="makechanges">Make changes</button>
<h1>Place:</h1>
<div id="where"></div>
<h1>URL</h1>
<div id="url"></div>
JavaScript
var changed = false;
var currentPlace = '';
var currentTitle = '';
function LocationManager() {
this.href = location.href;
this.changed = false;
this.confirmHandler = function() {
return confirm("Really leave? There are unsaved changes");
}
}
LocationManager.prototype = {
setChanged: function() {
this.changed = true;
},
go: function(href) {
if (this.changed) {
if (!this.confirmHandler) {
}
}
}
};
function confirmIfChanged() {
return !changed || confirm("Really leave? There are unsaved changes");
}
$(window).on('popstate', function(event) {
console.log(event);
if (event.originalEvent.state !== null) {
if (confirmIfChanged()) {
//history.pushState({ where, "dummy", location.href);
return;
}
var newplace = event.originalEvent.state.where;
$('#where').text(newplace);
$('#url').text(location.href);
changed = false;
} else {
$('#where').text('nowhere');
$('#url').text('nowhere');
console.log('state is null!');
}
});
$('button[data-where]').on('click', function(event) {
var element = $(this);
var where = element.data('where');
if (where) {
history.pushState({ where: where }, 'You are at ' + where, '?place=' + where);
$('#url').text(location.href);
$('#where').text(where);
changed = false;
}
});
$('button[data-purpose=makechanges]').on('click', function() {
changed = true;
});