Activate your free membership today | Log-in

Monday, March 19th, 2007

Cross Browser Keyboard Handler

Category: Browsers, JavaScript, Library

<>p>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:
  1.  
  2. document.onkeydown = function(e) {handleKeys(e)}
  3. document.onkeypress = function(e) {handleKeys(e)}
  4. var nonChar = false;
  5.  
  6. function handleKeys(e) {
  7.     var char;
  8.     var evt = (e) ? e : window.event;       //IE reports window.event not arg
  9.     if (evt.type == "keydown") {
  10.         char = evt.keycode;
  11.         if (char <16 ||                    // non printables
  12.             (char> 16 && char <32) ||     // avoid shift
  13.             (char> 32 && char <41) ||     // navigation keys
  14.             char == 46) {                   // Delete Key (Add to these if you need)
  15.             handleNonChar(char);            // function to handle non Characters
  16.             nonChar = true;
  17.         } else
  18.             nonChar = false;
  19.     } else {                                // This is keypress
  20.         if (nonChar) return;                // Already Handled on keydown
  21.         char = (evt.charCode) ?
  22.                    evt.charCode : evt.keyCode;
  23.         if (char> 31 && char <256)        // safari and opera
  24.             handleChar(char);               //
  25.     }
  26.     if (e)                                  // Non IE
  27.         Event.stop(evt);                    // Using prototype
  28.     else if (evt.keyCode == 8)              // Catch IE backspace
  29.         evt.returnValue = false;            // and stop it!
  30. }
  31.  

Related Content:

4 Comments »

Comments feed TrackBack URI

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

Comment by Liming Xu — March 19, 2007

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

Comment by Binny V A — March 21, 2007

Great solution, I look forward to trying it. Thanks.

Comment by SlackAlice — September 13, 2007

I have just tried this wrapper and it is simple and very effective, I would cetrainly recommend giving it a try.

Comment by The Chauffeur — September 29, 2007

Leave a comment

You must be logged in to post a comment.