Preventing default keystroke actions in Internet Explorer
internet-explorer, internet-explorer-10, javascript, jquery
Solution
To prevent the default behaviour
- use attachEvent instead of addEventListener
- set `event.keyCode` to 0
- return false
For example. (Prevent default behaviour for Ctrl+O and Ctrl+P)
/*jslint browser: true */
(function scriptInitScript() {
"use strict";
document.attachEvent("onkeydown", function handleKeyDown(event) {
if (event.ctrlKey) {
switch (event.keyCode) {
case 79: // o
case 80: // p
event.keyCode = 0;
return false;
}
}
});
}());
JSFiddle
Please note. jQuery 1.9 uses `addEventListener` if available. See in github.
Problem
I'm attempting to override ControlP in Internet Explorer 10, but can't seem to figure out how to do it. I've mocked up a Fiddle with some very simple code that works in Chrome (on my Mac, at least). But running this in IE 10 and using ControlP still brings up the print dialog box. Here's my simple code: ``` $('.test').on('keydown', function(e){ if (e.metaKey || e.ctrlKey){ $('body').append('ctrl p pressed'); e.preventDefault(); return false; } }); ``` Anyone know what's going on here?