Keyboard Event Handling: onkeydown

JavaScript FAQ | Keyboard & Mouse Events FAQ  

Question: Which key did the user press?

Answer: To find out which key the user has pressed, your script should check the

keydown
event properties:
keydown event.keyCode
(the key code of the key just pressed)
keydown event.shiftKey
(
true
if the event occured while Shift was pressed)
keydown event.ctrlKey
(
true
if the event occured while Ctrl was pressed)
keydown event.altKey
(
true
if the event occured while Alt was pressed)

(Similarly, to identify the key that the user just released, use the

keyup
event properties.)

Click here and press any key

-
the key name will be displayed below:
 

This example uses the function fromKeyCode that maps the

keydown
event
keyCode
value back to the corresponding key name. Here is the source code of this example:
function keydownHandler(e) {
  var evt = e ? e:event;
  var keyCode = evt.keyCode;
  var sModifiers = ''
      +(evt.ctrlKey  ? 'Ctrl ' :'')
      +(evt.shiftKey ? 'Shift ':'')
      +(evt.altKey   ? 'Alt '  :'') ;

  document.getElementById('sKeyCode').innerHTML =
     'keyCode='+keyCode;
  if (keyCode==16 || keyCode==17 || keyCode==18)
       document.getElementById('sKeyName').innerHTML=
       ' key: '+sModifiers;
  else document.getElementById('sKeyName').innerHTML=
       ' key: '+sModifiers
       +fromKeyCode(keyCode);

  //return true to allow the browser's default response
  //return false to cancel the default response 
  return true;
}

//Register the keydown event handler:
document.onkeydown=keydownHandler;

Caution: Do not use the

keypress
event for analyzing keys. Unlike
keydown
, the
keypress
event is suitable for identifying characters rather than keys;
keypress
may or may not occur for special/functional keys, while
keydown
and
keyup
events are triggered for practically every key.* This is precisely why we use the
keydown
event here: we want to be able to identify every key (or as many keys as realistically possible).

* The

keydown
event is not normally triggered for the PrntScrn key;
keyup
is triggered for PrntScrn in most browsers.

See also:

Copyright © 1996-2018, JavascriptFAQ.net.