Learn Create Your Own Split Screen

Next Page

There's a couple of different ways to deal with keystrokes in Javascript.

We'll start with the simple one, then in a later lesson introduce a slightly more complex, but much more powerful method.


We declare that we want to "listen" for a certain type of event. The event we're listening for is keydown, and when the event occurs, we want our handler function to be called.
addEventListener("keydown", MyKeyDownHandler);

We also define our handler function. The function automatically gets called with a parameter, and we'll choose to call it "MyEvent". It will come pre-loaded with information about the event.

function MyKeyDownHandler (MyEvent) { // Do something interesting with MyEvent.keyCode }

The type of information you get in an event parameter depends on what sort of event it is. For a mouseclick, it would be the x-y position of the mousepointer, and which button was clicked. For a keydown event, it holds the keyCode.