Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting support for a given JavaScript event?

I'm interested in using the JavaScript hashchange event to monitor changes in the URL's fragment identifier. I'm aware of Really Simple History and the jQuery plugins for this. However, I've reached the conclusion that in my particular project it's not really worth the added overhead of another JS file.

What I would like to do instead is take the "progressive enhancement" route. That is, I want to test whether the hashchange event is supported by the visitor's browser, and write my code to use it if it's available, as an enhancement rather than a core feature. IE 8, Firefox 3.6, and Chrome 4.1.249 support it, and that accounts for about 20% of my site's traffic.

So, uh ... is there some way to test whether a browser supports a particular event?

like image 300
Will Avatar asked May 20 '10 20:05

Will


1 Answers

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
like image 132
Christian C. Salvadó Avatar answered Sep 22 '22 18:09

Christian C. Salvadó