event.preventDefault() is not working in IE 11 for custom events

mohanaravind picture mohanaravind · Apr 28, 2014 · Viewed 9.1k times · Source

I have a polymer element which triggers a custom event synchronously and I want to know whether the event was cancelled using event.preventDefault(). Using event.defaultPrevented I can know the intended action. This works on all browsers(Chrome, Canary, Firefox, Opera) but on IE 11 (not worried about older browsers) its not working. I know I can set some property on my event and check for that back where I am triggering and handle but want to know if there is something else which I missed.

You can try out the code from http://jsbin.com/husamupi/1/edit

Answer

Joel Richard picture Joel Richard · Dec 28, 2014

I had the same problem and could solve it with the following hack:

var event = document.createEvent('CustomEvent');
event.initCustomEvent('custom', true, true, {});
event.preventDefault = function () {
    Object.defineProperty(this, "defaultPrevented", {get: function () {return true;}});
};
event.preventDefault();
event.defaultPrevented; // true