0

Trying to detect back button event by this sample javascript code:

document.location.hash="#1";
document.location.hash="#2";
document.location.hash="#3";

function check() {
    if("#3"!=window.location.hash) {
        alert("Back button clicked");
    }
    setTimeout(check, 100);
}
check();

In FF and Chrome it works, in IE window.location.hash is always "#3" even though I'm clicking the Back button and watching how the URL in the address bar is changing #2, #1.

Any ways to get IE to see the change of hash when it's changing after pressing back and forward?

Maxim Suponya
  • 1,419
  • 2
  • 20
  • 43

1 Answers1

0

I am assuming you are changing the hash dynamically through user or timed events.

You don't need to use setTimeout to check hash because there is a window.onhashchange event that you can use to fire off you code.

window.onhashchange = function(e) {
  alert('Back button clicked');
}

This code will fire every time the hash changes whether through using back/forward history buttons or when you change the hash with code. If you don't want your code to fire when you change the hash with your code you can either use an if statement so that it will only work with the back/forward history navigation like in this example: https://stackoverflow.com/a/11545805/1534818

or

you can use the window.onhashchange to execute all your code based on the hash and just change the hash with your onclick events to insure your code executes only once.

html:

<a href='#1' class='nav'>1<a/>
<a href='#2' class='nav'>2<a/>
<a href='#3' class='nav'>3<a/>

javascript/jquery:

/*$('.nav').click(function() {                 //do this if you aren't
  window.location.hash = '#' + $(this).html(); //changing the hash in your html
});*/
function getLocationHash() {
  return window.location.hash.substring(1);
} 
window.onhashchange = function(e) {
  switch(getLocationHash()) {
    case '1': 
      execute code block 1;
      break;
    case '2':
      execute code block 2;
      break;
    case '3':
      execute code block 3;
      break;
    default: 
      code to be executed if different from case 1, 2, and 3;
  }
}

I did something simular on my site: http://www.designhandler.com

Community
  • 1
  • 1
Damian
  • 86
  • 3