Javascript : onHashchange Test

Adam Halasz picture Adam Halasz · Oct 27, 2010 · Viewed 8.2k times · Source

I'm trying to check if the browser supports onHashChange or not to hide some code from it if not, in this way:

if(window.onhashchange){
    ...code...
} else {
   ...other code...
}

I tried this too:

if(typeof window.onhashchange === "function"){
    alert("Supports");  
} else {
    alert("Doesn't Supports");  
}

As described on Quirksmode this should work but if I do an alert for example in true state in Safari than alerts me but Safari is not supporting onHashChange :S

What's the problem with it? If I'm not on the right way how should I check it?

Answer

Christian C. Salvadó picture Christian C. Salvadó · Oct 27, 2010

You can detect this event by using the in operator:

if ("onhashchange" in window) {
  //...
}

See also: