Languages
[Edit]
EN

JavaScript - get keyboard key property value

3 points
Created by:
Cassia
1265

In this article, we would like to show you how to get keyboard key code value using JavaScript.

Quick solution:

element.addEventListener('keydown', function(e) {
    var message = 'key: '                  + e.key     + '\n' + 
                  'code: '                 + e.code    + '\n' + 
                  'keyCode (depricated): ' + e.keyCode + '\n\n';
    console.log(message);
});

Where:

  • e.key returns symbol or key name as string,
  • e.code returns key code as a string (similar to a key name in e.key),
  • e.keyCode returns key code as a number - deprecated approach.

Note: keydown can be changed to keyup up keypress.

 

Practical example

In this example, we use the keycode and keyCode properties to get information about pressed key.

Warnings:

  • key and code were introduced around 2016 and is recommended to use,
  • keyCode is marked as depricated but is still used as legacy.
// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div>Click here to get focus and press a key on the keyboard.</div>
  <script>

    document.addEventListener('keydown', function handleKeydown(e) {
        var message = 'key:      ' + e.key      + '\n' + 
                      'code:     ' + e.code     + '\n' + 
                      'keyCode:  ' + e.keyCode  + '\n' + 
                                                  '\n' +
                      'altKey:   ' + e.altKey   + '\n' + 
                      'ctrlKey:  ' + e.ctrlKey  + '\n' + 
                      'shiftKey: ' + e.shiftKey + '\n' +
                      'metaKey:  ' + e.metaKey;          // Windows key or Cmd key on macOS
        console.clear();
        console.log(message);
	});

  </script>
</body>
</html>

 

References

  1. KeyboardEvent.key - Web APIs | MDN

Alternative titles

  1. JavaScript - display keyboard key code value
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join