Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross browser preventDefault() without jQuery

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
        });
    }
};
like image 401
Tommy Avatar asked May 13 '12 21:05

Tommy


People also ask

What is e preventDefault () method?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

What is the opposite of preventDefault in Javascript?

As you probably might have already worked out based on the simple explanation above: the opposite of event. preventDefault() is nothing. You just don't prevent the event, by default the browser will allow the event if you are not preventing it.

What is preventDefault jquery?

preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form. Prevent a link from following the URL.


1 Answers

// cancel event
function cancelEvent(event) {
   if (event.preventDefault) { 
      event.preventDefault();
   } else {
      event.returnValue = false; 
   }
}
like image 147
undefined Avatar answered Sep 26 '22 07:09

undefined