src code

class Event

Description

The namespace for Prototype's event system.

Events: a fine mess

Event management is one of the really sore spots of cross-browser scripting.

True, the prevalent issue is: everybody does it the W3C way, and MSIE does it another way altogether. But there are quite a few subtler, sneakier issues here and there waiting to bite your ankle — such as the keypress/keydown issue with KHTML-based browsers (Konqueror and Safari). Also, MSIE has a tendency to leak memory when it comes to discarding event handlers.

Prototype to the rescue

Of course, Prototype smooths it over so well you'll forget these troubles even exist. Enter the Event namespace. It is replete with methods that help to normalize the information reported by events across browsers.

Event also provides a standardized list of key codes you can use with keyboard-related events, including KEY_BACKSPACE, KEY_TAB, KEY_RETURN, KEY_ESC, KEY_LEFT, KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_DELETE, KEY_HOME, KEY_END, KEY_PAGEUP, KEY_PAGEDOWN and KEY_INSERT.

The functions you're most likely to use a lot are Event.observe, Event.element and Event.stop. If your web app uses custom events, you'll also get a lot of mileage out of Event.fire.

Instance methods on event objects

As of Prototype 1.6, all methods on the Event object are now also available as instance methods on the event object itself:

Before

$('foo').observe('click', respondToClick);
 function respondToClick(event) {
  var element = Event.element(event);
  element.addClassName('active');
}

After

$('foo').observe('click', respondToClick);
 function respondToClick(event) {
  var element = event.element();
  element.addClassName('active');
}

These methods are added to the event object through Event.extend, in the same way that Element methods are added to DOM nodes through Element.extend. Events are extended automatically when handlers are registered with Prototype's Event.observe method; if you're using a different method of event registration, for whatever reason,you'll need to extend these events manually with Event.extend.

Classes

  • Event.Handler

    Creates an observer on an element that listens for a particular event on that element's descendants, optionally filtering by a CSS selector.