I have the following example where when a user clicks a navigation line it loads in some content using AJAX and also updates the url and title using the jquery history.js https://github.com/browserstate/History.js/ plugin to do some HTML5 History.
ajaxNav: function () {
$('#uiTabs li a, .ajax').live('click', function (e) {
e.preventDefault();
$('<div id="uiLoader"></div>').appendTo('body').hide().fadeIn();
var url = $(this).attr('href');
var bodyid = $(this).data('body');
$.ajax({
url: url,
timeout: 5000,
success: function (responseHtml) {
isAjaxNav = true;
var content = $(responseHtml).find('#ajax-nav-html');
$('.uiContent > .uiPadding').html(content.hide().fadeIn('slow'));
History.pushState(null, $(responseHtml).filter('title').text(), url);
$('body').attr('id', bodyid);
$('#uiLoader').fadeOut(function () { $('#uiLoader').remove() });
},
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus == 'timeout') {
uiModal.errorTimeoutModal(jqXHR, textStatus, errorThrown);
} else if (jqXHR.status == "500") {
uiModal.error500Modal(jqXHR, textStatus, errorThrown);
} else if (jqXHR.status == "404") {
uiModal.error404Modal(jqXHR, textStatus, errorThrown);
} else {
uiModal.errorUnknownModal(jqXHR, textStatus, errorThrown);
}
$('#uiLoader').fadeOut(function () { $('#uiLoader').remove() });
}
});
});
},
However when a user clicks the back or forth buttons it will change the url and title (as the plugin supports this fine) but the content will not change! How would I detect this so that I can read the new url using for example $('location').att('pathname'); then do some more ajax?
So for example:
//IF back button or forward button clicked or relevant function e.g backspace
$(<!-- ? -->).click(function() {
// Get the current url when the back or forward button was clicked
var url = $('location').att('pathname');
$.ajax({
url: url,
timeout: 5000,
success: function (responseHtml) {
isAjaxNav = true;
var content = $(responseHtml).find('#ajax-nav-html');
$('.uiContent > .uiPadding').html(content.hide().fadeIn('slow'));
History.pushState(null, $(responseHtml).filter('title').text(), url);
$('body').attr('id', bodyid);
$('#uiLoader').fadeOut(function () { $('#uiLoader').remove() });
},
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus == 'timeout') {
uiModal.errorTimeoutModal(jqXHR, textStatus, errorThrown);
} else if (jqXHR.status == "500") {
uiModal.error500Modal(jqXHR, textStatus, errorThrown);
} else if (jqXHR.status == "404") {
uiModal.error404Modal(jqXHR, textStatus, errorThrown);
} else {
uiModal.errorUnknownModal(jqXHR, textStatus, errorThrown);
}
$('#uiLoader').fadeOut(function () { $('#uiLoader').remove() });
}
});
});
You need to attach to the
window.onpopstateevent: