Eight Weeks of Prototype: Week 4, Event Handling in Prototype
Handling Keyboard Events
So far we haven't concerned ourselves with any specifics of an event that occurs, other than on which element the event occurred. Often an event will be triggered by a particular key press or by some movement or action with the mouse. In this section we will look at how to handle events that are triggered by the keyboard.
To determine which key was pressed, you can read the
keyCode property of the event object passed to your event handler. Prototype defines a number of useful constants that help you determine which key was pressed. Specifically, these are:
To demonstrate how these codes can be used, I have written a simple example, shown in Listing 12. In this example there is a text input. If you hit the escape key the text in the input is selected, while hitting backspace results in the entire value being cleared. While this doesn't serve much practical use, hopefully it demonstrates how you can read the key codes.