views:

20

answers:

2

I would like to have the following function being able to work on all objects that support events, by passing the corresponding event and not only for onload.

function eve(ev, fnc) {
    if(typeof window.addEventListener!= 'undefined'){
        window.addEventListener('load',fnc,false); 
        }elseif(typeof window.attachEvent!='undefined'){
        window.attachEvent('onload', fnc );
    }else{
        var old = this.onload;  
        this.onload=function(e){  
            old();  
            fnc();  
        };
    }
}
// for instance onclick
eve('onclick', myFunc);

Any ideas will be appreciate it

A: 

function eve(obj, ev, fnc) {
    if(typeof window.addEventListener!= 'undefined'){
        obj.addEventListener(ev.replace(/on/,""),fnc,false); 
        }elseif(typeof window.attachEvent!='undefined'){
        obj.attachEvent(ev, fnc );
    }else{
        var old = obj[ev];  
        obj[ev]=function(e){  
            old();  
            fnc();  
        };
    }
}
// for instance onclick
eve(obj, 'onclick', myFunc);

Vincent
+2  A: 

The easiest and most robust way to do this is to use a library to do it for you, like Prototype, jQuery, Closure, etc. That way, you get the benefit of other people finding and reporting/fixing bugs rather than having to do it all yourself. :-)

But:

DOM elements have addEventListener (and attachEvent, on IE) on them as well, so it's fairly easy to create a general function for this:

function hook(obj, event, handler) {

    if (obj.attachEvent) {
        obj.attachEvent("on" + event, handler);
    }
    else if (obj.addEventListener) {
        obj.addEventListener(event, handler);
    }
    else {
        // Fail, probably
    }
}

(Note that the IE variant uses "on" [e.g., "onclick"], the standard doesn't ["click"].)

It's a bit more efficient to test once and then use whichever the browser has, though:

var hook = (function() {
    var elm = document.createElement('div');

    if (elm.attachEvent)
    {
        return hookWithAttachEvent;
    }
    if (elm.addEventListener)
    {
        return hookWithAddEventListener;
    }
    return hookFail;

    function hookWithAttachEvent(obj, event, handler) {

        obj.attachEvent("on" + event, handler);
        return obj;
    }

    function hookWithAddEventListener(obj, event, handler) {

        obj.addEventListener(event, handler);
        return obj;
    }

    function hookFail() {
        throw "Don't know how to hook events on this platform.";
    }
})();

That detects, once, which variant should be used and returns a function using that variant, which will then be called directly when you use hook.

T.J. Crowder