9

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.

Derek 朕會功夫
  • 84,678
  • 41
  • 166
  • 228

3 Answers3

5

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

Mike Dotterer
  • 978
  • 1
  • 9
  • 16
0

This is all quite simple. What you have to do is to make hash not to get added to the browser address bar.

For this basically you have to add click event handler, in there check if the link is the one you want to avoid firing popstate on hash change and, if yes, prevent default behaviour with event.preventDefault().

I just wrote an answer with code example and detailed explanations on the similar question here.

Valentine Shi
  • 3,093
  • 2
  • 25
  • 35
0

You could be checking window.location.hash to see what # type of anchor is added to it and take the appropriate action.

Also, by checking window.onhashchange you can distinguish between full URL changes in window.location.href or just hash changes.

Example:

window.onhashchange = function()
{
    console.log('Hash change:' + window.location.hash);
}
denicio
  • 522
  • 1
  • 6
  • 20