Event Listener //JavaScript Repository

Description

Cross-browser addEvent and removeEvent.
Created: 2005.08.13 - Modified 2013.09.17

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/geral/event-listener [rev. #6]

addEvent = function(o, e, f, s){
    var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
    r[r.length] = [f, s || o], o[e] = function(e){
        try{
            (e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
            e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
            e.target || (e.target = e.srcElement || null);
            e.keyValue = e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
        }catch(f){}
        for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
        return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
    for(var i = (e = o["_on" + e] || []).length; i;)
        if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
            return delete e[i];
    return false;
};

Example (Example)

Help

Functions

addEvent(object: Object, event: String, handler: Function(e: Event): Boolean, [scope: Object = object]): void
Adds an event listener to an object.
object
object that will receive the listener
event
event name without the "on" prefix (click, mouseover, ...)
handler
function that will be called when the event occur, the event object will be sent as argument to this function, and besides the normal properties, it will *always* have:
  • target: object that generated the event
  • keyValue: keeps the character key code on keyboard events
  • stopPropagation: method to avoid the event propagation
  • preventDefault: method to avoid the default action
the preventDefault method can be emulated by returning "false" in the function
scope
scope (who the "this" inside the callback will refer to) that will be used when the function get invoked, the default value is the object on the first argument
removeEvent(object: Object, event: String, handler: function(e: Event): Boolean, [scope: Object = object]): Boolean
Removes a previously added listener from the object and returns true in case of success.
object
object that received the listener
event
event name without the "on" prefix (click, mouseover, ...)
handler
same function that was assigned on the addEvent
scope
same scope that was assigned on the addEvent (if you provided a scope, it's necessary to send the same object as argument, otherwise the listener won't be removed), the default value is the object on the first argument

Rank (Votes: 182)

4.25