Dealing With the Keyboard

With our triangle drawn, our next job is to deal with the keyboard. This involves the following steps:

  1. Listening for the events your keyboard fires
  2. Inside the event handler, accessing the KeyboardEvent's keyCode property.

Handling the cases when the left, right, up, and down arrow keys are pressed. There are several ways of doing this, but we are going to use a familiar (but less-than-ideal approach). Go ahead and add the following lines of code just above where you defined your drawTriangle function:

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

With the code we have just added, we first listen for a key press by listening for the keydown event. When that event gets overheard, we call the moveSomething event handler that deals with each arrow key press. It does this dealing by matching the keyCode property with the appropriate key value each arrow key is known by.