207

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?

danwellman
  • 9,068
  • 8
  • 60
  • 88
sv_in
  • 13,929
  • 9
  • 34
  • 55
  • It does; according to the docs (http://mootools.net/docs/core/Native/Event#Event:preventDefault) what he has should work: "Event Method: preventDefault - Cross browser method to prevent the default action of the event." – Paolo Bergantino Jun 16 '09 at 10:15
  • My bad, i deleted my comment, which was "doesn't mootools have a method to stop events?". So there's a problem with mootools on ie8... – Alsciende Jun 16 '09 at 10:17
  • 2
    Can't reproduce this issue. [This fiddle](http://jsfiddle.net/tofu/6E4Eq/show/) "works for me on ie 8" Could you setup a reduced fiddle to show the error? http://jsfiddle.net/ – drivenuts May 24 '11 at 10:04

11 Answers11

480

in IE, you can use

event.returnValue = false;

to achieve the same result.

And in order not to get an error, you can test for the existence of preventDefault:

if(event.preventDefault) event.preventDefault();

You can combine the two with:

event.preventDefault ? event.preventDefault() : (event.returnValue = false);
Alsciende
  • 26,583
  • 9
  • 51
  • 67
  • 48
    The following code worked for me: if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } – sv_in Jun 16 '09 at 10:32
  • 229
    `event.preventDefault ? event.preventDefault() : event.returnValue = false;` – mortiy Mar 06 '11 at 13:43
  • 31
    It's worth noting that "event" must be the global event object in IE8. You can't use the event passed into the event handler, like e.preventDefault, it *must* be event.preventDefault in order for this to work in IE8. – jamesmortensen Apr 05 '12 at 17:16
  • `event.preventDefault();` stopped working for me in FireFox for some reason, out of the blue. Used mority's code and it worked great. Thanks~ – James Apr 05 '12 at 18:29
  • If the event comes from an eventhandler bound with mootools addEvent(), the event parameter passed to your handler will always have preventDefault(). If you use IE specific AddEventListener or HTML onclick="" you won't get this help from mootools. – oldwizard Nov 21 '12 at 14:27
  • Thank you! I used this solution in a mousedown handler and in my system with IE8 I need to add an handler to "ondragstart" that returns false. – Edoardo Panfili Aug 10 '13 at 19:23
  • Is this workaround really needed? It looks like jQuery has worked correctly since v1.3. See the [source](https://github.com/jquery/jquery/blob/2df1aad6a1c9376c2a477eba26ee992113ed1c23/src/event.js#L672-L673) and [blame](https://github.com/jquery/jquery/blame/2df1aad6a1c9376c2a477eba26ee992113ed1c23/src/event.js#L672-L673). – Kevin Kuszyk Mar 12 '14 at 10:26
  • 8
    Just to add some clarity to @jmort253's comment: `$('.something').click(function(e){ e.preventDefault ? e.preventDefault() : event.returnValue = false; });` – Luke Dec 18 '14 at 10:01
  • It worked for me. I was working on a Angular 4 application and in Typescript I need to use switch(event.keyCode.toString()) to check what key user selected... – Ziggler Dec 23 '17 at 00:35
23

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.

oldwizard
  • 5,012
  • 2
  • 31
  • 32
12

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.

Community
  • 1
  • 1
muffir
  • 447
  • 5
  • 16
  • 1
    You can also get the original browser event object from `event.originalEvent`. More Info: http://stackoverflow.com/a/16675056/22550 – sv_in Dec 29 '13 at 14:11
6

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();
Alsciende
  • 26,583
  • 9
  • 51
  • 67
5
if (e.preventDefault) {
    e.preventDefault();
} else {
    e.returnValue = false;
}

Tested on IE 9 and Chrome.

Eliran Malka
  • 15,821
  • 6
  • 77
  • 100
RolandoCC
  • 868
  • 1
  • 14
  • 19
4

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

JBE
  • 11,917
  • 7
  • 49
  • 51
  • You are the only answerer to hit the nail on the head. The only reason anyone here is talking about early IE is that they need cross platform functionality. "e.keyCode = 0;" will kill any default action in early IE. – www-0av-Com May 21 '20 at 20:10
3

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;
})
Eliran Malka
  • 15,821
  • 6
  • 77
  • 100
  • 1
    I have never seen this `stop` method before, and I couldn't find it in msdn. What does it do? – Oriol Sep 23 '13 at 18:27
  • 1
    `.stop()` throws an exception, because it doesn't exist. Any exception will have the desired effect. – Jay Bazuzi Jun 30 '14 at 15:35
  • 1
    and why would you want to throw an exception? I mean, if you want to throw an exception, you could simply call `e.preventDefault()` cause it'd throw an exception anyway... – Matthias Burger Sep 26 '19 at 09:50
2

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.

Spike0xff
  • 1,246
  • 1
  • 15
  • 24
EliuX
  • 11,389
  • 6
  • 45
  • 40
0

return false in your listener should work in all browsers.

$('orderNowForm').addEvent('submit', function () {
    // your code
    return false;
}
daemon1981
  • 246
  • 2
  • 6
0

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.

KWallace
  • 1,570
  • 1
  • 15
  • 25
0

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;
}
Pablo
  • 586
  • 5
  • 14