Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

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:

  • Event.KEY_TAB
  • Event.KEY_RETURN
  • Event.KEY_ESC
  • Event.KEY_LEFT
  • Event.KEY_UP
  • Event.KEY_RIGHT
  • Event.KEY_DOWN
  • Event.KEY_DELETE
  • Event.KEY_HOME
  • Event.KEY_END
  • Event.KEY_PAGEUP
  • Event.KEY_INSERT

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.

Listing 12 Determining which key was pressed (listing-12.html)
        <title>Determining which key was pressed</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
            <input type="text" id="foo" />
        <script type="text/javascript">
            function onFooKeyup(e)
                var element = Event.element(e);
                switch (e.keyCode) {
                    case Event.KEY_ESC:
                    case Event.KEY_BACKSPACE:
                        element.value = '';
            $('foo').observe('keyup', onFooKeyup);

In This Article