I'm using the history API to push a new URL to the web page without reloading it. I have multiple buttons that all have different functionality.
My script now works almost without problems. When I press the button something happens, and when I go back the script fires event listener without reloading the page.
However, when I now press the forward button, I want to go forward. The URL is changed correctly to the next one, but the event listener still fires as if the back button was pressed
Example:
index1.html
- button press →
index2.html
- button press →
index3.html
- back button pressed →
index2.html
- forward button pressed → URL is now
index3.html
, but the content isindex1.html
I guess this is because I have a listener, that listens for popstate
which happens for back button and forward button pressed. How can I differ what kind of button was pressed?
This is the part that binds the listener:
if (window.history && window.history.pushState) {
$(window).unbind('popstate');
$(window).bind('popstate', function (e) {
clearOverlays();
var url = URL
$.ajax ( {
url : url
}).done ( function ( data ) {
console.log(data);
});
});
}
state
variable to store the state that the user navigates to. It looks like you're currently storing it in a global variable,URL
? P.S. You should useon
/off
in place ofbind
/unbind
in modern versions of jQuery – Polashstate
variable you passed into pushState:history.pushState(**{ status: "OpenFile" }**, "Open", "irrelevanturl.html");
– Polash