'Cancelling JavaScript events in IE11

I have some historical code that's using event.returnValue = false to prevent CR from causing a post back in an ASP.NET via the onkeydown event:

onkeydown = "if (event.keyCode == 13) {event.returnValue = false; event.cancel = true;}"

I've ported the code to my new development PC and the above code stopped working, i.e. pressing CR performed the post back in a text box.

It's taken me ages to track it down. My historical app is so old that it has to run in compatibility mode in IE11 so my old PC had localhost added to the list of compatible sites.

My new PC doesn't have localhost so my new app is running in "native" IE11 mode.

Aside: I know there is a different way to do this by simply returning false:

onkeydown = "return event.keyCode != 13"

My question is more about why event.returnValue = false doesn't work in IE11 when not in compatibility mode, i.e. what changes have there been to the JavaScript event system which makes this code not valid anymore?



Solution 1:[1]

event.returnValue was an IE proprietary mechanism which is now deprecated.IE has been moving away from its old proprietary APIs and moving towards web standard adoption since around IE 9.

The standard, and what will work on IE 11, is event.preventDefault.

If you want to cover all your bases, you can continue to include the old APIs in your code, and use feature detection for preventDefault:

onkeydown = "if (event.keyCode == 13) {
                event.returnValue = false; 
                event.cancel = true;
                if (event.preventDefault) {
                    event.preventDefault();
                }
             }"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JLRishe