I am using:

$(window).bind( 'hashchange', function(e) { });

to bind a function to the hash change event. This seems to work in IE8, Firefox and Chrome, but not in Safari and I assume not in earlier version of IE. For these browsers, I want to disable my JavaScript code that uses the hash and hashchange event.

Is there a way with jQuery that i can detect if the browser supports the hashchange event? Maybe something with jQuery.support...


Solution 1:

You can detect if the browser supports the event by:

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

See also:

  • Detecting event support without browser sniffing
  • Emulating onhashchange without setInterval
  • window.onhashchange

Solution 2:

An updated answer here as of 2017, should anyone need it, is that onhashchange is well supported in all major browsers. See caniuse for details. To use it with jQuery no plugin is needed:

$( window ).on( 'hashchange', function( e ) {
    console.log( 'hash changed' );
} );

Occasionally I come across legacy systems where hashbang URL's are still used and this is helpful. If you're building something new and using hash links I highly suggest you consider using the HTML5 pushState API instead.