Cross browser preventDefault() without jQuery

Tommy picture Tommy · May 13, 2012 · Viewed 8.2k times · Source

I wrote this bind method and am having an issue in my preventDefault() method to work in IE. The callback line never executes. Can someone provide assistance? Thanks!

var preventDefault = function (event) {
    if (window.event) { window.event.returnValue = false; }
    else if (event.preventDefault) { event.preventDefault(); }
    else { event.returnValue = false; }
};

var bindEvent = function (ele, type, cb) {
    if (window.addEventListener) {
        ele.addEventListener(type, cb, false);
    } else if (window.attachEvent) {
        ele.attachEvent('on' + type, function () {
            event.preventDefault = function () {
                preventDefault(event);
            }.call(this);
           cb.call(ele, event);  //this does not execute
        });
    }
};

Answer

undefined picture undefined · May 13, 2012
// cancel event
function cancelEvent(event) {
   if (event.preventDefault) { 
      event.preventDefault();
   } else {
      event.returnValue = false; 
   }
}