Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : onHashchange Test

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?

like image 689
Adam Halasz Avatar asked Oct 27 '10 06:10

Adam Halasz


2 Answers

You can detect this event by using the in operator:

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

See also:

  • onhashchange - MDC
  • Detecting event support without browser sniffing
  • Emulating onhashchange without setInterval
like image 59
Christian C. Salvadó Avatar answered Oct 19 '22 06:10

Christian C. Salvadó


Be warned that you're better off using feature detection rather than existence inference (such as "onhashchange" in window).

@xkit explained to me a good feature test to work around the fact that although IE7 doesn't support onhashchange it would still return true for existence inference such as if("onhashchange" in window){/code/} when using IE7 Standard Document Mode in IE8.

What @xkit suggested was setting a flag (such as var isSet = true;) within a handler function for the onhashchange event. Then changing window.location.hash using JavaScript and see if the flag was set.

like image 6
Mark McDonnell Avatar answered Oct 19 '22 06:10

Mark McDonnell