JS Keyboard Events


Published: 2016-01-13
Updated: 2016-07-08
Web: https://fritzthecat-blog.blogspot.com/2016/01/js-keyboard-events.html


Keyboards are normally not well supported in web applications. Pressing ENTER in a field not always commits input, but sometimes unexpectedly triggers buttons, mostly those on top left where the browser's default focus is.

But it is not the browser's fault when keyboard control is nasty, it's the web page's fault. Times are getting hotter, especially for web developers, because there is a brand new keyboard event specification on the w3c. (By the time of this writing, just Firefox implements it.) And there is the Web Accessibility Initiative, propagating ARIA, which makes web page navigation for challenged people easier. And this is something very positive also for "normal" people, because it standardizes web UIs a little bit.

If you just want to test your keyboard, click here!

Receive Keyboard Events with JS

Here is an example how to receive keyboard events in JavaScrip (JS), conforming to the new specification. It is the event.key and event.code that are new. Possible values of key are specified by the w3c.

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"/>
</head>

<body>

<p>Press any key!</p>
<textarea cols="30" rows="2" placeholder="Phone Input Field"></textarea>
<p id="keydown">...</p>
<p id="keyup">...</p>

<script type="text/javascript">
document.addEventListener("keydown", function(event) {
keyboardInput("keydown", event);
});
document.addEventListener("keyup", function(event) {
keyboardInput("keyup", event);
});

var keyboardInput = function(outputId, event) {
var outputElement = document.getElementById(outputId);
var key = event.key;
var code = event.code;
outputElement.innerHTML = "key = "+key+", code = "+code;
};
</script>

</body>
</html>

The script is the last element in HTML, so all elements will already exist when the script is executed. It installs listeners on the document element. The function keyboardInput() outputs key and code of any received event in the paragraph elements with according ids.

This is the JS way to install event listeners (don't tell me about IE :-)

      document.addEventListener("keydown", function(event) {
keyboardInput("keydown", event);
});

Some people prefer to use HTML callbacks like:


onkeydown="keyboardInput('keydown', arguments);"
onkeyup="keyboardInput('keyup', arguments);">

Which would then look like the following:

  <body
onkeydown="keyboardInput('keydown', arguments);"
onkeyup="keyboardInput('keyup', arguments);">

...

<script type="text/javascript">
var keyboardInput = function(outputId, arguments) {
var e = arguments[0]; /* the keyboard event */
var outputElement = document.getElementById(outputId);
outputElement.innerHTML = "key = "+e.key+", code = "+e.code;
};
</script>

</body>

Legacy Events

The code above might not work in your browser, because the keyboard specification is quite new. Below is legacy code to recognize keyboard events also in browsers that do not yet implement this.

      var keyboardInput = function(outputId, event)  {
var outputElement = document.getElementById(outputId);
var key = (event.which || event.keyCode);
outputElement.innerHTML = "which || keyCode = "+key;
};

This is the way recommended on w3schools. (For more readable JS code I would stick to the w3c specification.)

IE Edge sends what was the code in the new event field event.key. So we will still have to hardcode IE in our keyboard interpretation JS source :-(

Interpreting Events

Just receiving events does not help very much, we need to know which key the user pressed.

The string in event.key is standardized by the w3c. It is beautiful for programming, you achieve readable code, other than with legacy key-codes. There are boolean properties in the event to find out key-modifier states, which are present in the same way also in legacy-keyboard events:

This is it for generic keyboards. In certain countries you may want to find out the state of non-standard keys like "AltGr". This can be done using the event-function getModifierState("AltGraph"). Parameters are also standardized on w3c pages (look for "Modifier Keys").

  document.addEventListener("keydown", function(event) {
var altGraphIsDown = event.getModifierState("AltGraph"));
var capsLockIsDown = event.getModifierState("CapsLock");
....
});

For legacy events, here is a JS function to convert the which || keyCode to a character:

  var key = event.which || event.keyCode;
var character = String.fromCharCode(key);

Test your Keyboard

Here is a web UI to test your browser's keyboard sensitivity. Amazingly and contrary to various documentations about key events I could not discover any keypress events. So here are just keyup and keydown.

Mind that your operating-system needs to provide the key for your browser to receive it, and mind that, although the events should be neutralized by event.preventDefault()(prevent the browser default action for the key) and event.stopPropagation() (prevent event "bubbling"), the operating system might interpret certain key combinations you enter.

Click into this rectangle, or set input focus to the text-area below, and then press any key. In the tables below you find all details about the events that occur.


Key Down
Key
 
Code
 
Shift
 
Ctrl
 
Alt
 
Meta
 
AltGr
 
Caps
 
Location
 

Key Up
Key
 
Code
 
Shift
 
Ctrl
 
Alt
 
Meta
 
AltGr
 
Caps
 
Location
 

Key Down
 
Key Up

You can use this key detector and its source code also on my homepage.





ɔ⃝ Fritz Ritzberger, 2016-01-13