Cross Browser Event Handling in JavaScript

On May 22, 2013, in Javascript, by Anuj Gakhar

If you are using jQuery, you can easily use .bind() and .unbind(), or .on() and .off() to attach/detach event handlers on DOM elements. But there are times when jQuery is not available/desirable in the project for various reasons.

This is actually quite easy to do in native JavaScript, without any libraries. Most browsers register the specific listeners on the element using addEventListener and removeEventListener. But IE8 and below use a different API (attachEvent/detachEvent) for this. It’s easy to write a simple cross-browser Event Handler script to take care of this.

[js]var EventHandler = {
bind:function(el, ev, fn){
if(window.addEventListener){ // modern browsers including IE9+
el.addEventListener(ev, fn, false);
} else if(window.attachEvent) { // IE8 and below
el.attachEvent(‘on’ + ev, fn);
} else {
el[‘on’ + ev] = fn;
}
},

unbind:function(el, ev, fn){
if(window.removeEventListener){
el.removeEventListener(ev, fn, false);
} else if(window.detachEvent) {
el.detachEvent(‘on’ + ev, fn);
} else {
elem[‘on’ + ev] = null;
}
},

stop:function(ev) {
var e = ev || window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}
}[/js]

The above code also handles the stopPropagation difference between IE8(and below) and other browsers. IE8 and below need the “cancelBubble” property to be turned on in order to stop event propagation.

Tagged with:  

One Response to Cross Browser Event Handling in JavaScript

  1. […] e.g. toggling between addEventListener and attachEvent for event handlers. I’ve got a separate post for this, if someone’s interested. Also, things like querying DOM nodes where it’s not […]

Leave a Reply to Dojo and IE8 Compatibility | Anuj Gakhar Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2011 Anuj Gakhar
%d bloggers like this: