In This Chapter
• Listen and react to the keyboard
• Understand how to work with the various keyboard-related events
• See some examples that highlight how common keyboard scenarios work
We spend a lot of time in various applications tapping away at our keyboards. In case you are wondering what a keyboard looks like, Figure 34.1 features a sweet one from I think about a hundred years ago.
Anyway, our computers (more specifically, the applications that run on them) just know how to deal with our board of plastic depressible keys. You never really think about it. Sometimes, depending on what you are doing, you will have to think about them. In fact, you’ll have to deal with them and make them work properly. Better cancel any plans you have, for this chapter is going to be pretty intense!
By the end of this chapter, you will learn all about how to listen to the keyboard events, what each of those events do, and see a handful of examples that highlight some handy tricks that may come in...um...handy.
Onward!
To work with keyboards in an HTML document, there are three events that you will need to familiarize yourself with. Those events are
keydown
keypress
keyup
Given what these events are called, you probably already have a vague idea of what each event does. The keydown
event is fired when you press down on a key on your keyboard. The keyup
event is fired when you release a key that you just pressed. Both of these events work on any key that you interact with.
The keypress
event is a special bird. At first glance, it seems like this event is fired when you press down on any key. Despite what the name claims, the keypress
event is fired only when you press down on a key that displays a character (letter, number, and the like). What this means is somewhat confusing, but it makes sense in its own twisted way.
If you press and release a character key such as the letter y, you will see the keydown
, keypress
, and keyup
events fired in order. The keydown
and keyup
events fire because the y key is simply a key to them. The keypress
event is fired because the y key is a character key. If you press and release a key that doesn’t display anything on the screen (such as the spacebar, arrow key, or function keys), all you will see are the keydown
and keyup
events fired.
This difference is subtle but very important when you want to ensure your key presses are actually overheard by your application.
Say What?
It is weird that an event called keypress
doesn’t fire when any key is pressed. Maybe this event should be called something else like characterkeypress
, but that is probably a moo point. (What is a “moo point”? Well... http://bit.ly/kirupaMoo)
The way you listen to the keydown
, keypress
, and keyup
events is similar to any other event you may want to listen and react to. You call addEventListener
on the element that will be dealing with these events, specify the event you want to listen for, specify the event handling function that gets called when the event is overheard, and a true/false value indicating whether you want this event to bubble.
Here is an example of me listening to our three keyboard events on the window
object:
window.addEventListener("keydown", dealWithKeyboard, false); window.addEventListener("keypress", dealWithKeyboard, false); window.addEventListener("keyup", dealWithKeyboard, false); function dealWithKeyboard(e) { // gets called when any of the keyboard events are overheard }
If any of these events are overheard, the dealWithKeyboard
event handler gets called. In fact, this event handler will get called three times if you happen to press down on a character key. This is all pretty straightforward, so let’s kick everything up a few notches and go beyond the basics in the next few sections.
When an event handler that reacts to a keyboard event is called, a Keyboard
event argument is passed in. Let’s revisit our dealWithKeyboard
event handler that you saw earlier. In that event handler, the keyboard event is represented by the e
argument that is passed in:
function dealWithKeyboard(e) { // gets called when any of the keyboard events are overheard }
This argument contains a handful of properties:
KeyCode
Every key you press on your keyboard has a number associated with it. This read-only property returns that number.
CharCode
This property only exists on event arguments returned by the keypress event, and it contains the ASCII code for whatever character key you pressed.
ctrlKey
, altKey
, shiftKey
These three properties return a true if the Ctrl key, Alt key, or Shift key is pressed.
MetaKey
The metaKey
property is similar to the ctrlKey
, altKey
, and shiftKey
properties in that it returns a true if the Meta key is pressed. The Meta key is the Windows key on Windows keyboards and the Command key on Apple keyboards.
The Keyboard
event contains a few other properties, but the ones you see above are the most interesting ones. With these properties, you can check for which key was pressed and react accordingly. In the next couple of sections, you’ll see some examples of this.
Caution
The charCode
and keyCode
properties are currently marked as deprecated by the web standards people at the W3C. Its replacement might be the mostly unsupported code
property. Just be aware of this and be ready to update your code in the future when whichever successor to charCode
and keyCode
has taken his/her rightful place on the throne.
Now that you’ve seen the horribly boring basics of how to work with Keyboard events, let’s look at some examples that clarify (or potentially confuse!) everything you’ve seen so far.
The following example shows how to use the keyCode
property to check if a particular key was pressed:
window.addEventListener("keydown", checkKeyPressed, false); function checkKeyPressed(e) { if (e.keyCode == 65) { console.log("The 'a' key is pressed."); } }
The particular key I check is the a key. Internally, this key is mapped to the keyCode
value of 65. In case you never memorized all of them in school, you can find a handy list of all key and character codes at the following link: http://bit.ly/kirupaKeyCode Please do not memorize every single code from that list. There are far more interesting things to memorize instead.
Some things to note. The charCode
and keyCode
values for a particular key are not the same. Also, the charCode
is only returned if the event that triggered your event handler was a keypress
. In our example, the keydown
event would not contain anything useful for the charCode
property.
If you wanted to check the charCode
and use the keypress
event, here is what the above example would look like:
window.addEventListener("keypress", checkKeyPressed, false); function checkKeyPressed(e) { if (e.charCode == 97) { console.log("The 'a' key is pressed."); } }
The charCode
for the a key is 97. Again, refer to the table of key and character codes I listed earlier for such details.
We see this most often in games where pressing the arrow keys does something interesting. The following snippet of code shows how that is done:
window.addEventListener("keydown", moveSomething, false); function moveSomething(e) { switch (e.keyCode) { case 37: // left key pressed break; case 38: // up key pressed break; case 39: // right key pressed break; case 40: // down key pressed break; } }
Again, this should be pretty straightforward as well. And, would you believe it—an actual use for the switch
statement that you learned about forever ago in Chapter 4, “Conditional Statements: if, else, and switch.”
Now, this is going to be epic! An interesting case revolves around detecting when we need to react to multiple key presses. What follows is an example of how to do that:
window.addEventListener("keydown", keysPressed, false); window.addEventListener("keyup", keysReleased, false); let keys = []; function keysPressed(e) { // store an entry for every key pressed keys[e.keyCode] = true; // Ctrl + Shift + 5 if (keys[17] && keys[16] && keys[53]) { // do something } // Ctrl + f if (keys[17] && keys[70]) { // do something // prevent default browser behavior e.preventDefault(); } } function keysReleased(e) { // mark keys that were released keys[e.keyCode] = false; }
Going into great detail about this will require another chapter by itself, but let’s just look at how this works very briefly.
First, we have a keys array that stores every single key that you press:
let keys = [];
As keys get pressed, the keysPressed
event handler gets called:
function keysPressed(e) { // store an entry for every key pressed keys[e.keyCode] = true; // Ctrl + Shift + 5 if (keys[17] && keys[16] && keys[53]) { // do something } // Ctrl + f if (keys[17] && keys[70]) { // do something // prevent default browser behavior e.preventDefault(); } }
When a key gets released, the keysReleased
event handler gets called:
function keysReleased(e) { // mark keys that were released keys[e.keyCode] = false; }
Notice how these two event handlers work with each other. As keys get pressed, an entry gets created for them in the keys
array with a value of true. When keys get released, those same keys are marked with a value of false. The existence of the keys you press in the array is superficial. It is the values they store that is actually important.
As long as nothing interrupts your event handlers from getting called properly such as an alert window, you will get a one-to-one mapping between keys pressed and keys released as viewed through the lens of the keys
array. With all of this said, the checks for seeing which combination of keys have been pressed is handled in the keysPressed
event handler. The following highlighted lines show how this works:
function keysPressed(e) { // store an entry for every key pressed keys[e.keyCode] = true; // Ctrl + Shift + 5 if (keys[17] && keys[16] && keys[53]) { // do something } // Ctrl + f if (keys[17] && keys[70]) { // do something // prevent default browser behavior e.preventDefault(); } }
There is one thing you need to keep in mind. Some key combinations result in your browser doing something. To avoid your browser from doing its own thing, use the preventDefault
method as highlighted when checking to see if Ctrl + F is being used:
function keysPressed(e) { // store an entry for every key pressed keys[e.keyCode] = true; // Ctrl + Shift + 5 if (keys[17] && keys[16] && keys[53]) { // do something } // Ctrl + f if (keys[17] && keys[70]) { // do something // prevent default browser behavior e.preventDefault(); } }
The preventDefault
method prevents an event from triggering a default behavior. In this case, it was preventing the browser from showing the Find dialog box. Different key combinations will trigger different reactions by the browser, so keep this method handy to put a stop to those reactions.
Anyway, looking at the code in aggregate, you have a basic blueprint for how to check for multiple key presses easily.
The Absolute Minimum
The keyboard is pretty important when it comes to how people interact with their computer-like devices. Despite its importance, you often won’t have to deal with them directly. Your browser, the various text-related controls/elements, and everything in-between just handle it as you would expect by default. There are certain kinds of applications where you may want to deal with them, though, which is why you have this chapter.
This chapter started off in the most boring way possible by explaining how to work with the Keyboard
events and their event arguments. Along the way, things (hopefully) got more interesting as you saw several examples that address common things you would do when dealing with the keyboard in code. If you have any questions about working with the keyboard or anything else, don’t hesitate to post on the forums at https://forum.kirupa.com.
18.222.120.133