Introduction

Keyboard event types are defined as strings.

There are only two:

  • keydown
  • keyup

In many cases, we should listen for keyboard events on the web page, regardless of what has focus.

To do that, attach a keyboard event listener on the global window object.

Demo

ResultView the demo in separate window

<!doctype html>  
<html>  
 <head>  
  <meta charset="utf-8">  
  <title>Keyboard Events</title>  
 </head>  /*  w w w  .j a v a 2s  .  c  om*/
 <body>  
  <script>  
  window.onload = function () {  
      
    function onKeyboardEvent (event) {  
      console.log(event.type);  
    }  
    window.addEventListener('keydown', onKeyboardEvent, false);  
    window.addEventListener('keyup', onKeyboardEvent, false);  
  };  
  </script>  
 </body>  
</html>

Related Topic