Working With the Keyboard

by kirupa   |   7 March 2016

We spend a lot of time in various applications tapping away at our keyboards. In case you are wondering what a keyboard looks like, here is a sweet one from I think about a hundred years ago:

Look! It's a keyboard.

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.

By the end of this tutorial, 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.

Onwards!

Meet the Keyboard Events

To work with keyboards in a HTML document, there are three events that you will need to familiarize yourself with. Those events are:

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, etc.). 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, function keys, etc.), 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.

Using These Events

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 window:

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.

The Keyboard Event Properties

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:

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.

Some Examples

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.

Checking that a Particular Key Was Pressed

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") {
		alert("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. You can find a handy list of all key and character codes at the following link. 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 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") {
		alert("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.

Doing Something When the Arrow Keys are Pressed

You 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. The only potentially weird thing is the switch statement, and you can learn more about them in this tutorial!

Detecting Multiple Key Presses

Now, this is going to be epic! An interesting case revolves around detecting when you need to react to multiple key presses. Below is an example of how to do that:

window.addEventListener("keydown", keysPressed, false);
window.addEventListener("keyup", keysReleased, false);

var 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 tutorial by itself, but let's just look at how this works.

First, we have a keys array that stores every single key that you press:

var 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;
}

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 are two things you need to keep in mind. The order of your checks matter. Ensure the checks are arranged in decreasing order of the number of keys that are pressed. Second, some key combinations result in your browser doing something. To avoid your browser from doing its own thing, use the preventDefault method like I show 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 prevents your browser from reacting to it by showing the Find dialog for Ctrl + f. You put all of this together, and you have a basic blueprint for how to check for multiple key presses easily.

Conclusion

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. For those kinds of apps, this tutorial exists.

This tutorial 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.

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!