Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  66] [ 1]  / answers: 1 / hits: 49087  / 14 Years ago, mon, june 14, 2010, 12:00:00

How can I cancel the keydown of a specific key on the keyboard, for example(space, enter and arrows) in an HTML page.


More From » html

 Answers
10

If you're only interested in the example keys you mentioned, the keydown event will do, except for older, pre-Blink versions of Opera (up to and including version 12, at least) where you'll need to cancel the keypress event. It's much easier to reliably identify non-printable keys in the keydown event than the keypress event, so the following uses a variable to set in the keydown handler to tell the keypress handler whether or not to suppress the default behaviour.


Example code using addEventListener and ignoring ancient version of Opera


document.addEventListener("keydown", function(evt) {
// These days, you might want to use evt.key instead of keyCode
if (/^(13|32|37|38|39|40)$/.test("" + evt.keyCode)) {
evt.preventDefault();
}
}, false);

Original example code from 2010


var cancelKeypress = false;

document.onkeydown = function(evt) {
evt = evt || window.event;
cancelKeypress = /^(13|32|37|38|39|40)$/.test("" + evt.keyCode);
if (cancelKeypress) {
return false;
}
};

/* For pre-Blink Opera */
document.onkeypress = function(evt) {
if (cancelKeypress) {
return false;
}
};

[#96506] Friday, June 11, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
malaysias

Total Points: 619
Total Questions: 110
Total Answers: 107

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;