I need a cross-browser function to register event handlers and a (mostly) compatible handler. I don't need the full weight or functionality of a library like jQuery, so I wrote my own. I believe that I have achieved my goals with the code below, and so far my testing has been successful, but I have looked at it for too long. Are there any flaws in my logic or gotchas that I am missing?
EDIT 1: Comment on each block with a browser purpose for clarity. Updated IE block so you don’t call right away func(thanks Andy E to the eyes ).
EDIT 2: Updated IE block to call func.call()with thisinstead elem.
EDIT 3: Updated for JSLint transition using the "Good Parts".
function hookEvent(elem, evt, func)
{
if (typeof elem === "string")
{
elem = document.getElementById(elem);
}
if (!elem)
{
return null;
}
var old, r;
if (elem.addEventListener)
{
elem.addEventListener(evt, func, false);
r = true;
}
else if (elem.attachEvent)
{
elem[evt + func] = function ()
{
func.call(this, window.event);
};
r = elem.attachEvent("on" + evt, elem[evt + func]);
}
else
{
old = elem["on" + evt] ? elem["on" + evt] : function (e) { };
elem["on" + evt] = function (e)
{
if (!e)
{
e = window.event;
}
old.call(this, e);
func.call(this, e);
};
r = true;
}
return r;
}
source
share