The popState
event will be triggered when the url has changed (either back or forward). And recently I have noticed that, for example, in http://www.example.com/
:
<a href="#anchor">Top</a>
will also trigger popState
, causing the page to "reload".
How can I know that if it is the same url and only the #
part has changed?
$(window).bind("popstate",function(){
swap(location.href);
})
In the example, when you click on "Top" link (see above), the page will go to #anchor
, but also it will trigger popState
and causes reloading, which is I do not expect.
The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history. back() or history. forward() in JavaScript). Browsers tend to handle the popstate event differently on page load.
PopStateEvent is an interface for the popstate event. A popstate event is dispatched to the window every time the active history entry changes between two history entries for the same document. If the history entry being activated was created by a call to history. pushState() or was affected by a call to history.
I couldn't find anything from the event to determine if that this was just an anchor change, so I had to keep track of it myself with code like the following:
function getLocation() {
return location.pathname + location.search;
}
var currentLocation = getLocation();
$(function() {
$(window).on("popstate", function() {
var newLocation = getLocation();
if(newLocation != currentLocation) {
// DO STUFF
}
currentLocation = newLocation;
});
})
The location is stored without the hash, so when the popstate fires due to clicking on the link with the anchor, the getLocation method will return the same result as before and the code to swap the page won't happen.
To make sure you keep track of the current location properly, you also need to update the variable whenever you change the state with pushState() or replaceState()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With