PhpRiot
Download This Article
Download this article or the entire “Eight Weeks of Prototype” series with all listings and files.




More information
Related Books
JavaScript: The Good Parts

JavaScript: The Good Parts

Most programming languages contain good and bad parts, but JavaScript has more than its share of...

Practical Prototype and script.aculo.us (Expert's Voice in Web Development)

Practical Prototype and script.aculo.us (Expert's Voice in Web Development)

As a JavaScript developer, you will already be aware of some of the time saving, convenience,...
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

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

In This Article


Tagged in ,