The following prevents autorepeated keypresses for "normal" keys (i.e. those that generate text input), even when several keys are pressed simultaneously. Note that the keypress
event is the only event sure to be fired in all mainstream browsers for autorepeats and the keyCode
value for a keypress event will not be the same as the keyCode
value for the corresponding keypress event, which complicates things a little.
var textBox = document.getElementById("my_textbox");
var lastKeyDown, keyIsPressed = {}, keyCodeForCharCode = {},
charCodeForKeyCode = {};
textBox.onkeydown = function(evt) {
evt = evt || window.event;
lastKeyDown = evt.keyCode;
};
textBox.onkeyup = function(evt) {
evt = evt || window.event;
var charCode = charCodeForKeyCode[evt.keyCode];
if (charCode) {
keyIsPressed[charCode] = false;
}
};
textBox.onkeypress = function(evt) {
evt = evt || window.event;
var keyCode, charCode = evt.which || evt.keyCode;
if (keyIsPressed[charCode]) {
// This keypress is an autorepeat
return false;
} else {
keyIsPressed[charCode] = true;
// Get the key code for the corresponding keydown event
keyCode = keyCodeForCharCode[charCode];
if (!keyCode) {
// Create two-way mapping for keyCode and charCode
keyCodeForCharCode[charCode] = lastKeyDown;
charCodeForKeyCode[lastKeyDown] = charCode;
}
}
};