O'Reilly logo

Prototype and Scriptaculous: Taking the Pain out of JavaScript by Chris Angus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required