Cross Browser Processing

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)  //w3c
    {
        elem.addEventListener(evt, func, false);
        r = true;
    }
    else if (elem.attachEvent)  //ie
    {
        elem[evt + func] = function ()
        {
            func.call(this, window.event);
        };
        r = elem.attachEvent("on" + evt, elem[evt + func]);
    }
    else                        //old
    {
        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;
}
+3
source share
1 answer

There is a problem on this line:

r = elem.attachEvent("on" + evt, func.call(elem, window.event));

This will lead to the immediate execution of the func () function, instead of attaching it as an event handler. Instead, the return value of func () will be assigned to the event, which will throw an error if it is not "function".

, , () - . John Resig Google "javascript addEvent" .

http://www.google.com/search?q=javascript+addevent

+3

Source: https://habr.com/ru/post/1761565/


All Articles