Prototype Event Handling


Event management is one of the biggest challenges to achieve cross-browser scripting. Every browser has different approaches to handle key strokes.

Prototype Framework handles all cross browser compatibility issues and keeps you free from all trouble related to event management.

Prototype Framework provides Event namespace, which is replete with methods, that all take the current event object as an argument, and happily produce the information you're requesting, across all major browsers.

Event namespace also provides a standardized list of key codes you can use with keyboard-related events. The following constants are defined in the namespace:

Key ConstantDescription
KEY_BACKSPACERepresent back space key.
KEY_TABRepresent tab key.
KEY_RETURNRepresent return key.
KEY_ESCRepresent esc key.
KEY_LEFTRepresent left key.
KEY_UPRepresent up key.
KEY_RIGHTRepresent right key.
KEY_DOWNRepresent down key.
KEY_DELETERepresent delete key.
KEY_HOMERepresent home key.
KEY_ENDRepresent end key.
KEY_PAGEUPRepresent page up key.
KEY_PAGEDOWNRepresent page down key.

To understand it in better way you can Try it yourself.

How to Handle Events

Before we start, let us see an example of using an event method. This example shows how to capture the DOM element on which the event occurred.

<title>Prototype examples</title>
   <script type="text/javascript" 

// Register event 'click' and associated call back.
Event.observe(document, 'click', respondToClick);
// Callback function to handle the event.
function respondToClick(event) {
  var element = event.element();
  alert("Tag Name : " + element.tagName );



   <p id="note"> Click on any part to see the result.</p>

   <p id="para">This is paragraph</p>

   <div id="division">
       This is divsion.


To understand it in better way you can Try it yourself.

Here is a complete list of all the methods related to Event. The functions you're most likely to use a lot are observe, element and stop.

Prototype Event Methods

NOTE: Make sure you at least have the version 1.6 of prototype.js.

element()Returns the DOM element on which the event occurred.
extend()Extends the event with all of the methods contained in Event.Methods.
findElement()Returns the first DOM element with a given tag name, upwards from the one on which the event occurred.
isLeftClick()Determines whether a button-related mouse event was about the "left" (primary, actually) button.
observe()Registers an event handler on a DOM element.
pointerX()Returns the absolute horizontal position for a mouse event.
pointerY()Returns the absolute vertical position for a mouse event.
stop()Stops the event's propagation and prevents its default action from being triggered eventually.
stopObserving()Unregisters an event handler.
unloadCache()Unregisters all event handlers registered through observe. Automatically wired for you. Not available since 1.6.