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 Events

I will now show you how to write event handlers when observing events with Prototype. I showed you some basic examples in the previous section of handling some events, but there is more to it than that!

When you define an event handler, the event object is passed as the first argument to the handler. This allows you to find out more information about the event, such as which specific element the event occurred on or to determine which key was pressed (for a key-related event).

Listing 5 shows a basic example of how to access this object. My own personal preference for the name of the event object is to use e, since if you use event you may confuse this with the JavaScript Event object.

Typically this variable will be used in conjunction with the Event variable. That is, rather than methods being available to call directly on e, they are passed to the relevant Event method (such as Event.element(e)).

Listing 5 Demonstrating how the event object is passed to handlers (listing-5.html)
        <title>Demonstrating how the event object is passed to handlers</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
        <div id="foo">
            Click me!
        <script type="text/javascript">
            function handleFooClick(e)
                // you can now do something with e,
                // such as call Event.element(e)
            $('foo').observe('click', handleFooClick);

In This Article