Keyboard events

Using the mouse to play notes on our piano works okay, but it would be better if we could play more than one note at a time. To do that, we can use the computer's keyboard to play notes. To do this we will add keyboard event handlers to the DOM document in JavaScript and map keyboard keys to piano keys.

The top two rows of the keyboard will be used for the first octave and the bottom two for the second octave. For example, pressing the Q key will play the lowest C note. Pressing the 2 key will play C#, W will play D, and so on. For the second octave, pressing Z will play middle C, S will play C#, and so on:

Keyboard events

You can find the code for ...

Get HTML5 Web Application Development By Example Beginner's guide 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.