The first thing we need to do is add keycodes.js
to our application. This file contains a global static object named keyCodes
that maps keys on the keyboard to their associated key code. For example, keyCodes.ENTER
is equal to 13
. Using this will make our code more readable than using key code numbers.
The next thing we need to do is open the HTML and add a new custom data attribute to the piano-key
elements. We will call it data-keycode
and it will be set to the value in the keyCode
object we want to associate with the piano key:
<div data-note="2C" data-keycode="Q" class="piano-key white" title="C2"></div> <!—elements not shown --> <div data-note="4C" data-keycode="COMMA" class="piano-key white" title="C4"></div>
Now we need to map key codes to the notes. We will add an object to our application called keyCodesToNotes
to hold our mappings. We will initialize it in the initKeyboard()
method:
function initKeyboard() { ...