Event-binding with plain JS

hi,

I haven’t done event-binding with plain JS in a long time…

so when I test on FF get error… attachEvent is not a function… so this is the one that works only in IE, right? (and I can’t test on IE right now… man, that’s just grand…)

so what do you need to do to not get errors on the browsers for which one of these two event-binding methods doesn’t work? you have to do browser-sniffing?

thank you…

You might be interested to checkout the recent JavaScript Challenge thread. The idea was to convert a set of tabs that used jQuery into vanilla JS. There are some good links in the thread to further information, and several people have given JS functions for cross-browser event binding. AussieJohn’s solution is particularly well commented and useful to study IMO.

Cross browser addEvent function (that includes attachEvent for those people still using IE8).

if (window.addEventListener)
addEvent = function(ob, type, fn ) {
  ob.addEventListener(type, fn, false );
};
else if (document.attachEvent)
addEvent = function(ob, type, fn ) {
  var eProp = type + fn;
  ob['e'+eProp] = fn;
  ob[eProp] = function(){ob['e'+eProp]( window.event );};
  ob.attachEvent( 'on'+type, ob[eProp]);
};

You can then attach all your events simply by specifying the element, event and function as follows:

addEvent(document.getElementById('myid'),
  'click',
  myfunction);

You can then detach again using the following function and a removeEvent call specifying the exact same parameters as was used for the addEvent:

if (window.addEventListener)
removeEvent = function(ob, type, fn ) {
  ob.removeEventListener(type, fn, false );
};
else if (document.attachEvent)
removeEvent = function(ob, type, fn ) {
  var eProp = type + fn;   ob.detachEvent('on'+type, ob[eProp]);   
  ob[eProp] = null;
  ob["e"+eProp] = null;
};

If you don’t need to support IE8 then just use addEventListener and removeEventListener.