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.
[…] 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 […]