Monday, March 19th, 2007
Cross Browser Keyboard Handler
Santosh Rajan has struggled with keyboard handling across browsers.
His article discusses some of the pain, and he came up with a simple wrapper to help out:
JAVASCRIPT:
-
-
document.onkeydown = function(e) {handleKeys(e)}
-
document.onkeypress = function(e) {handleKeys(e)}
-
var nonChar = false;
-
-
function handleKeys(e) {
-
var char;
-
var evt = (e) ? e : window.event; //IE reports window.event not arg
-
if (evt.type == "keydown") {
-
char = evt.keycode;
-
if (char <16 || // non printables
-
(char> 16 && char <32) || // avoid shift
-
(char> 32 && char <41) || // navigation keys
-
char == 46) { // Delete Key (Add to these if you need)
-
handleNonChar(char); // function to handle non Characters
-
nonChar = true;
-
} else
-
nonChar = false;
-
} else { // This is keypress
-
if (nonChar) return; // Already Handled on keydown
-
char = (evt.charCode) ?
-
evt.charCode : evt.keyCode;
-
if (char> 31 && char <256) // safari and opera
-
handleChar(char); //
-
}
-
if (e) // Non IE
-
Event.stop(evt); // Using prototype
-
else if (evt.keyCode == 8) // Catch IE backspace
-
evt.returnValue = false; // and stop it!
-
}
-





3.9 rating from 26 votes







That’s pretty handy without the need to download a whole framework just for keyboard detection.
It’ll be useful later on when we add Ajax to our product.
Liming
Jumptree Project management
http://www.jumptree.com
I have created a function to handle Keyboard shortcuts. My approach completely abstracts the handling - you just have to specify the key combination and the function to be called when that combination is pressed - Handling Keyboard Shortcuts in JavaScript
Great solution, I look forward to trying it. Thanks.
I have just tried this wrapper and it is simple and very effective, I would cetrainly recommend giving it a try.