[javascript] event.preventDefault() function not working in IE

Following is my JavaScript (mootools) code:

$('orderNowForm').addEvent('submit', function (event) {
    event.preventDefault();
    allFilled = false;
    $$(".required").each(function (inp) {
        if (inp.getValue() != '') {
            allFilled = true;
        }
    });

    if (!allFilled) {
        $$(".errormsg").setStyle('display', '');
        return;
    } else {
        $$('.defaultText').each(function (input) {
            if (input.getValue() == input.getAttribute('title')) {
                input.setAttribute('value', '');
            }
        });
    }

    this.send({
        onSuccess: function () {
            $('page_1_table').setStyle('display', 'none');
            $('page_2_table').setStyle('display', 'none');
            $('page_3_table').setStyle('display', '');
        }
    });
});

In all browsers except IE, this works fine. But in IE, this causes an error. I have IE8 so while using its JavaScript debugger, I found out that the event object does not have a preventDefault method which is causing the error and so the form is getting submitted. The method is supported in case of Firefox (which I found out using Firebug).

Any Help?

The answer is


Here's a function I've been testing with jquery 1.3.2 and 09-18-2009's nightly build. Let me know your results with it. Everything executes fine on this end in Safari, FF, Opera on OSX. It is exclusively for fixing a problematic IE8 bug, and may have unintended results:

function ie8SafePreventEvent(e) {
    if (e.preventDefault) {
        e.preventDefault()
    } else {
        e.stop()
    };

    e.returnValue = false;
    e.stopPropagation();
}

Usage:

$('a').click(function (e) {
    // Execute code here
    ie8SafePreventEvent(e);
    return false;
})

I know this is quite an old post but I just spent some time trying to make this work in IE8.

It appears that there are some differences in IE8 versions because solutions posted here and in other threads didn't work for me.

Let's say that we have this code:

$('a').on('click', function(event) {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;
});

In my IE8 preventDefault() method exists because of jQuery, but is not working (probably because of the point below), so this will fail.

Even if I set returnValue property directly to false:

$('a').on('click', function(event) {
    event.returnValue = false;
    event.preventDefault();
});

This also won't work, because I just set some property of jQuery custom event object.

Only solution that works for me is to set property returnValue of global variable event like this:

$('a').on('click', function(event) {
    if (window.event) {
        window.event.returnValue = false;
    }
    event.preventDefault();
});

Just to make it easier for someone who will try to convince IE8 to work. I hope that IE8 will die horribly in painful death soon.

UPDATE:

As sv_in points out, you could use event.originalEvent to get original event object and set returnValue property in the original one. But I haven't tested it in my IE8 yet.


if (e.preventDefault) {
    e.preventDefault();
} else {
    e.returnValue = false;
}

Tested on IE 9 and Chrome.


To disable a keyboard key after IE9, use : e.preventDefault();

To disable a regular keyboard key under IE7/8, use : e.returnValue = false; or return false;

If you try to disable a keyboard shortcut (with Ctrl, like Ctrl+F) you need to add those lines :

try {
    e.keyCode = 0;
}catch (e) {}

Here is a full example for IE7/8 only :

document.attachEvent("onkeydown", function () {
    var e = window.event;

    //Ctrl+F or F3
    if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
        //Prevent for Ctrl+...
        try {
            e.keyCode = 0;
        }catch (e) {}

        //prevent default (could also use e.returnValue = false;)
        return false;
    }
});

Reference : How to disable keyboard shortcuts in IE7 / IE8


preventDefault is a widespread standard; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:

if (typeof Event.prototype.preventDefault === 'undefined') {
    Event.prototype.preventDefault = function (e, callback) {
        this.returnValue = false;
    };
}

This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general. Now you can use e.preventDefault with no problem.


I was helped by a method with a function check. This method works in IE8

if(typeof e.preventDefault == 'function'){
  e.preventDefault();
} else {
  e.returnValue = false;
}

FWIW, in case anyone revisits this question later, you might also check what you are handing to your onKeyPress handler function.

I ran into this error when I mistakenly passed onKeyPress(this) instead of onKeyPress(event).

Just something else to check.


return false in your listener should work in all browsers.

$('orderNowForm').addEvent('submit', function () {
    // your code
    return false;
}

If you bind the event through mootools' addEvent function your event handler will get a fixed (augmented) event passed as the parameter. It will always contain the preventDefault() method.

Try out this fiddle to see the difference in event binding. http://jsfiddle.net/pFqrY/8/

// preventDefault always works
$("mootoolsbutton").addEvent('click', function(event) {
 alert(typeof(event.preventDefault));
});

// preventDefault missing in IE
<button
  id="htmlbutton"
  onclick="alert(typeof(event.preventDefault));">
  button</button>

For all jQuery users out there you can fix an event when needed. Say that you used HTML onclick=".." and get a IE specific event that lacks preventDefault(), just use this code to get it.

e = $.event.fix(e);

After that e.preventDefault(); works fine.


Mootools redefines preventDefault in Event objects. So your code should work fine on every browser. If it doesn't, then there's a problem with ie8 support in mootools.

Did you test your code on ie6 and/or ie7?

The doc says

Every event added with addEvent gets the mootools method automatically, without the need to manually instance it.

but in case it doesn't, you might want to try

new Event(event).preventDefault();

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to internet-explorer

Support for ES6 in Internet Explorer 11 The response content cannot be parsed because the Internet Explorer engine is not available, or Flexbox not working in Internet Explorer 11 IE and Edge fix for object-fit: cover; "Object doesn't support property or method 'find'" in IE How to make promises work in IE11 Angular 2 / 4 / 5 not working in IE11 Text in a flex container doesn't wrap in IE11 How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript? includes() not working in all browsers

Examples related to events

onKeyDown event not working on divs in React Detect click outside Angular component Angular 2 Hover event Global Events in Angular How to fire an event when v-model changes? Passing string parameter in JavaScript function Capture close event on Bootstrap Modal AngularJs event to call after content is loaded Remove All Event Listeners of Specific Type Jquery .on('scroll') not firing the event while scrolling

Examples related to mootools

preg_match in JavaScript? Uncaught SyntaxError: Unexpected token : Comparing date part only without comparing time in JavaScript event.preventDefault() function not working in IE

Examples related to preventdefault

React onClick and preventDefault() link refresh/redirect? Bootstrap 3 - disable navbar collapse How to preventDefault on anchor tags? Stop form from submitting , Using Jquery Prevent Default on Form Submit jQuery What's the difference between event.stopPropagation and event.preventDefault? What is the opposite of evt.preventDefault(); How to unbind a listener that is calling event.preventDefault() (using jQuery)? event.preventDefault() function not working in IE