Kyle-Falconer
2/12/2014 - 10:03 PM

More compatible ways of adding and removing events on elements. It's not quite as complete a solution as what jQuery provides, but it works

More compatible ways of adding and removing events on elements.

It's not quite as complete a solution as what jQuery provides, but it works.

(jQuery's solution is here: https://github.com/jquery/jquery/blob/master/src/event.js)



var EventUtils = EventUtils || {};

/**
* A more compatible way of attaching event listeners.
* Works on IE 7+
* Note that if Element.prototype.addEventListener is not supported,
*   useCapture will be ignored.
* @see http://stackoverflow.com/a/12949687/940217
* @param {Element} ele
* @param {string} type
* @param {function(?)} handler
* @param {boolean=} useCapture
* @return {undefined}
*/
EventUtils.addEventListener = function (ele, type, handler, useCapture) {
  useCapture = useCapture || false;
  if (ele.addEventListener) {
    ele.addEventListener(type, handler, useCapture);
  } else if (ele.attachEvent) {
    ele.attachEvent("on" + type, handler);
  } else {
    ele["on" + type] = handler;
  }
};

/**
* A more compatible way of removing event listeners.
* Works on IE 7+.
* Note that if Element.prototype.removeEventListener is not supported,
*   useCapture will be ignored.
* @see http://stackoverflow.com/a/12949687/940217
* @param {Element} ele
* @param {string} type
* @param {function(?)} handler
* @param {boolean=} useCapture
* @return {undefined}
*/
EventUtils.removeEventListener = function (ele, type, handler, useCapture) {
  useCapture = useCapture || false;
  if (ele.removeEventListener) {
    ele.removeEventListener(type, handler, useCapture);
  } else if (ele.detachEvent) {
    ele.detachEvent("on" + type, handler);
  } else {
    ele["on" + type] = null;
  }
};