views:

126

answers:

4

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.....

Thanks for the help.

+3  A: 

You can detect if the browser supports the event by:

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

See also:

CMS
Thanks for that and for the quick response.
Ian Herbert
A: 

I think Chris Coyier has solution for that hashing problem, have a look at his screencast:

Best Practices with Dynamic Content

Sarfraz
Thank you, I will look into that.
Ian Herbert
A: 

To make sure an event is available, use this code:

won't work for onhashchange, see comments

var el         = document.createElement('div'),
    supported  = ('onhashchange' in el);

if(!supported){
   el.setAttribute('onhashchange', 'return;');
   supported   = typeof el['onhashchange'] === 'function';
}

if(!supported){
        // no support for that event
}
else{
        // event is supported by the browser
}

This should work crossbrowser.

jAndy
This technique works very well with other events, but it [fails](http://jsbin.com/oqiwe3/edit) detecting `hashchange` on IE8, Chrome, Safari and WebKit. The problem is that it checks for the event in a DOM element, and this event is available on the `window` object.
CMS
@CMS: indeed, just tested it. Schooled me :)
jAndy
+1  A: 

There is a hashchange plug-in which wraps up the functionality and cross browser issues available here.

James Westgate