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:

Press + to interact
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.