I'm using ajax to simulate a menu. All is fine but the back and forward buttons are not perfectly working.
So the code is:
$('#sdt_menu a').on('click', function (e) {
href = $(this).attr("href");
e.preventDefault();
window.onpopstate = function (event) {
document.url = event.state.url;
loadSpecificPage(window.location.pathname);
};
pushingState(href);
})
window.onpopstate
looks for changes in the history.
pushingState
just pushes the new page to the history.
With this the menu items are correctly loaded into the browser history. But when I hit the back button for instance, the window.onpopstate
as well as my pushingState
function is triggered. So let's say I'm on page 1 and now load page 2. When I hit the back button now in the browser, I correctly go back to page 1 but I reload page 1 and go to it. So at the end I was not going back correctly. So the pushingState
function shall not be triggered, then it should work properly. I at least just replaced the current page with the last in the current way.
Summary: the window.onpopstate
is working properly. But the pushingState
function shall not be triggered when hitting the browser back/forward button.
So my idea was to create an if statement that checks if one of the buttons was clicked. But I did not find something like that. Here some links that did not work for me: detect back button click in browser and JavaScript or jQuery browser back button click detector
Maybe I'm thinking too hard into this direction and it's even easier somehow?
Added pushingState function
function pushingState(href){
if (href == "/about" || href == "/about/") {
history.pushState('About', 'about', href);
}
if (href == "/creator" || href == "/creator/") {
history.pushState('Creator', 'creator', href);
}
}