1.1. Writing Event Handlers Without Prototype

Prior to Prototype, writing cross-browser event-handling code probably meant writing code like:

function clickHandler(evt)
{
       evt = (evt) ? evt : ((event) ? event : null);
       if (evt)
       {
              var elem = (evt.target) ? evt.target :
                           ((evt.srcElement) ? evt.srcElement : null);
              if (elem)
              {
                     // act on event
                     ...
              }
       }
}

Figuring this out is painful! Fortunately, with Prototype, you can forget all this and work with portable events. Consider the following cross-browser JavaScript that finds the enclosing DIV element closest to the element that fired the event, and then cancels the default action associated with that event.:

function clickHandler(evt)
{
       evt = (evt) ? evt : ((event) ? event : null);
       if (evt)
       {
              var elem = (evt.target) ? evt.target :
                           ((evt.srcElement) ? evt.srcElement : null);

              while (elem != null && elem.tagName != 'DIV')
              {
                     elem = elem.parent;
              }
              if (elem)
              {
                     // some processing on this DIV element
              }
              if (evt.returnValue)
              {
                     evt.returnValue = false;
              }
              else if (evt.preventDefault)
              {
                     evt.preventDefault();
              }
              else
              {
                     return false;
              }
       }
}

Using Prototype this can be written as:

function clickHandler(evt)
{
       var elem = Event.findElement(evt,'DIV')
       if (elem)
       {
              // some processing on this DIV element
       }
       Event.stop(evt);
}

Which is far simpler and far more understandable.

Get Prototype and Scriptaculous: Taking the Pain out of JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.