I just made a website where all pages are loaded using ajax. Now I am trying to make the back & forward browser buttons work. The back button was quite easy, all I had to do was this:
$(window).on('popstate', function(e) {
get_page_content(location.href);
});
Where get_page_content()
is the function I use to get and replace the page content when a link is clicked. And this is how I use the pushstate inside get_page_content()
:
window.history.pushState('', '', url);
Them problem is whenever I go back the forward button is not available. How can I use the forward button?
I just realized I had window.history.pushState('', '', url);
inside get_page_content()
which then was called each time onpopstate
event fired and eventually there was nothing to go forward to. I simply moved pushState
outside of get_page_content()
and everything works. Here's what I currently have:
$('body').on('click', 'a:not([href^="#"])', function(e) {
if ( this.host === window.location.host ) {
e.preventDefault()
get_page_content($(this).attr('href'));
window.history.pushState('', '', url);
}
});
$(window).on('popstate', function(e) {
get_page_content(location.href);
});
function get_page_content(url) {
// ...
}