2

I have attached certain actions to the existence of a URL hash in order to mimic traditional 'back' behavior.

The trouble is, if you go back from the hash, the hash is removed from the URL string, but the JavaScript doesn't pick up that that hash has gone.

How can I make it pick up the removal of the hash?

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148

3 Answers3

1

Usually clicks go first, then location changes. After a click is a good idea to set TimeOut to get an updated window.location.hash as shown below.

    $(".nav").click(function(){
    setTimeOut(function(){
      updatedHash = location.hash
    },100);
    });

or you can listen for the location with:

    window.onhashchange = function(evt){
       updatedHash = "#" + evt.newURL.split("#")[1]
    };

I wrote a jQuery plugin that does something like what you want to do. https://github.com/rgarro/Route32 It's a simple anchor router.

Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
Rolando
  • 131
  • 1
  • 3
0

check the window.location.hash string, it will return the hash part of your url

Dau
  • 8,578
  • 4
  • 23
  • 48
0

Poll window.location.href to detect changes. Use the change to work out what needs to be reverted. see How can I detect an address bar change with JavaScript?

Community
  • 1
  • 1
Gareth A. Lloyd
  • 1,774
  • 1
  • 16
  • 26