Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel popState in certain condition

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.

like image 834
Derek 朕會功夫 Avatar asked Mar 16 '12 04:03

Derek 朕會功夫


People also ask

What triggers Popstate?

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.

What is Popstate event listener?

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.


1 Answers

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()

like image 108
Mike Dotterer Avatar answered Oct 01 '22 08:10

Mike Dotterer