Building Interactive Systems with Keyboard Events

When things happen in web browsers, JavaScript thinks about those things as events. To have our code do something when an event happens, we write code that listens for different kinds of events. Events and event listeners are strange at first, but they make sense once you see some code. So let’s code!

Add the following at the very bottom of our code, below the animate line that we added in Chapter 3, ​Project: Making an Avatar​.

​ document.addEventListener(​'keydown'​, sendKeyDown);
​ ​function​ sendKeyDown(event) {
​  alert(event.code);
​ }

This code listens for a keydown event. You probably guessed that these events happen when any key is… pressed down. When our code ...

Get 3D Game Programming for Kids, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.