A cross-browser keypress detection javascript
March 30, 2007
Javascript | Snippets | Web Building

We have learning modules that have a lot of pages, and it occurred to me it would be easier on people's hands if they could simply use the right and left arrow keys to navigate through the module.

After a day of great frustration, I realized that it's nearly hopeless. Not only do all the browsers report different keycodes for the right and left arrow keys, but Firefox and Safari report both of them as "0" which makes it impossible to distinguish between them.

keys.jpg


Ads by Google

Posted by ellen at March 30, 2007 09:33 PM


But I found that if the "4" and "6" keys on the number keypad are used instead, browsers are consistent. So the the following code is based on
How to cancel a keystroke before it is displayed in a text input box in NS6 by Loofa Sponge and Jim Fuqua. and uses the "4" and "6" keys to turn pages.

I've commented out all the keypress events I don't need in my script, but left them in in case you need to use them in yours. The final "if" statement contains functions called "PreviousPage()" and "NextPage()" which are specific to my own application. You can replace them with whatever function you want to occur onKeypress.

self.focus();
document.onkeypress = function (evt) {
  var r = '';
  if (document.all) {
   // r += event.ctrlKey ? 'Ctrl-' : '';
   // r += event.altKey ? 'Alt-' : '';
   // r += event.shiftKey ? 'Shift-' : '';
    r += event.keyCode;
  }
  else if (document.getElementById) {
   // r += evt.Left ? 'left-' : ''; //left and right arrow keys produce different results on every browser - and can't be distinguished accurately.
    //r += evt.ctrlKey ? 'Ctrl-' : '';
   // r += evt.altKey ? 'Alt-' : '';
  // r += evt.shiftKey ? 'Shift-' : '';
     r += evt.charCode;
  }
  else if (document.layers) {
   // r += evt.modifiers & Event.CONTROL_MASK ? 'Ctrl-' : '';
   // r += evt.modifiers & Event.ALT_MASK ? 'Alt-' : '';
  //  r += evt.modifiers & Event.SHIFT_MASK ? 'Shift-' : '';
    r += evt.which;
  }
// alert(r);
if (r==52){PreviousPage();}   //replace my PreviousPage() function with your own function
else if (r==54){NextPage();} //replace my NextPage() function with your own function

return true;
}


Ads by Google


Ads by Google

 RSS   |   Contact Me


Ads by Google