Detecting support for a given JavaScript event?

Well, the best approach is not going through browser sniffing, Juriy Zaytsev (@kangax) made a really useful method for detecting event support:

var isEventSupported = (function(){
  var TAGNAMES = {
    'select':'input','change':'input',
    'submit':'form','reset':'form',
    'error':'img','load':'img','abort':'img'
  }
  function isEventSupported(eventName) {
    var el = document.createElement(TAGNAMES[eventName] || 'div');
    eventName = 'on' + eventName;
    var isSupported = (eventName in el);
    if (!isSupported) {
      el.setAttribute(eventName, 'return;');
      isSupported = typeof el[eventName] == 'function';
    }
    el = null;
    return isSupported;
  }
  return isEventSupported;
})();

Usage:

if (isEventSupported('hashchange')) {
  //...
}

This technique is now used in some libraries like jQuery.

Read more here:

  • Detecting event support without browser sniffing

The Mozilla documentation suggests the following:

if ("onhashchange" in window) {
    alert("The browser supports the hashchange event!");
}

This works in IE8 and the Chrome 5 beta too (I didn't test Chrome 4.1), and correctly fails in Opera and Safari.