Introduction

To know which key has been pressed, use the keyCode property to determine what key was involved with the event.

The keyCode property has a numeric value for the physical key pressed.

If the user pressed the "a" key, the keyCode would contain the number 65.

If the user pressed the Shift key first and then "a" you would get two keyboard events: one for Shift (keyCode 16) and one for "a" (keyCode 65).

Demo

ResultView the demo in separate window

<!doctype html>  
    <html>  
     <head>  
      <meta charset="utf-8">  
      <title>Key Codes</title>  
     </head>  
     <body>  
      <script>  
      window.onload = function () {  
      //  ww w  .  j av  a  2 s . c  om
        function onKeyboardEvent (event) {  
          switch (event.keyCode) {  
          case 38:  
            console.log("up!");  
            break;  
          case 40:  
            console.log("down!");  
            break;  
          case 37:  
            console.log("left!");  
            break;  
          case 39:  
            console.log("right!");  
            break;  
          default:  
            console.log(event.keyCode);  
      }  
    }  
  
    window.addEventListener('keydown', onKeyboardEvent, false);  
  };  
  </script>  
 </body>  
</html>

Related Topic