Cross-browser event handler using Prototype

Event handling in JavaScript is a great thing. Unfortunately, there are some cross-browser issues with event handling (IE rant omitted). Once again, Prototype comes to the rescue.

Using Prototype, it’s almost too easy to set an event handler for an element. Here’s how to set the ‘onclick’ event handler for element with id=’foo’:

$('foo').observe('click', respondToClick);

A note about the parameters:

  1. The first parameter (’foo’) is the DOM element you want to observe. As always in Prototype, this can be either an actual DOM reference, or the ID string for the element.
  2. The second parameter (’click’) is the standardized event name, as per the DOM level supported by your browser (usually DOM Level 2 Events). This can be as simple as ‘click’.
  3. The third parameter is the handler function. This can be an anonymous function you create on-the-fly, a vanilla function, a bound event listener, etc…

This does not replace existing handlers for that same element+event pair. It adds to the list of handlers for that pair. Using observe will never incapacitate earlier calls.

Now let’s use the event handler to set the class name on our field to highlight it when clicked.

function respondToClick(event) {
  var element = event.element();
  element.addClassName('highlight');
}

There are a few things to note about how the handler function is called:

  1. Its first argument is always the event object (on all browsers, including Internet Explorer).
  2. (New as of 1.6.0.) The event object is extended with methods like stop, so you can write event.stop() rather than Event.stop(event).
  3. (New as of 1.6.0.) Within the handler, this is a reference to the extended element the handler is associated with.
  4. (New as of 1.6.0.) The element on which the event actually occurred (the “target”) is available from findElement(). (Prior to 1.6.0, you would call element() method, which still works.) Note that the target might be a child of the observed element rather than the observed element itself, because of bubbling.

This technique of using Prototype to add the event handlers for an element is very useful when dynamically adding elements. The code is simple and clean:

//add new input element and set onclick handler
var newElement = document.createElement('input');
newElement.id = 'foo';
$('foo').observe('click', respondToClick);
//add a select element and set onclick handler
var newSelectElement = document.createElement('select');
newSelectElement.id = 'footwo';
$('footwo').observe('click', respondToSelectClick);

Remember that the element must exist in the DOM before you can set the event handler for it. Check out the Prototype site for more detail on event handling with Prototype.

Live free…code hard (but don’t hard code).

Tags: ,

Leave a Reply

You must be logged in to post a comment.