Friday, February 3, 2012

Cross browser event listener

Sometimes, we need to attach or detach an action with an element for specific event where listener function depends on browser. By using following code snippet anyone can do that in all browsers:
function addEvent(obj, evType, fn, useCapture) {
    useCapture = (useCapture === undefined ? false : useCapture);

    if (obj.addEventListener) {
        obj.addEventListener(evType, fn, useCapture);
    } else if (obj.attachEvent) {
        obj.attachEvent("on" + evType, fn);
    } else {
        obj['on' + evType] = fn;
    }
}
// Use: addEvent(element, 'mousemove', function_name);

function removeEvent(obj, evType, fn, useCapture) {
    useCapture = (useCapture === undefined ? true : useCapture);

    if (obj.removeEventListener) {
        obj.removeEventListener(evType, fn, useCapture);
    } else if (obj.detachEvent) {
        obj.detachEvent("on" + evType, fn);
    } else {
        obj['on' + evType] = fn;
    }
}
// Use: removeEvent(element, 'mousemove', function_name);