Friday, January 11, 2008

Unobtrusive JavaScript - Tie Events to Links with Prototype

Often, it is a good practice to separate your presentation layer from the the logic of your application. In web application, the presentation layer is your html pages, while the logic usually resides on the server or in JavaScript on the client (such as validation of user submitted values). Separating presentation and logic usually has to do with as little as possible logic inside your presentation layer.
With this in mind, it would be nice to have your application do something with JavaScript when you click on a link. In previous years that would be written something like this:
<a href="#" onClick="alert('You Clicked on Link 1');">Link 1</a>
<a href="#" onClick="alert('You Clicked on Link 1');">">Link 1</a>
While that works for this simple example, it is much nicer not to duplicate your code and not to mix your html with JavaScript. There is more than one reason the above approach is no longer the desired on, but here are few reasons: you need to write the "alert" call in each link you create, if your functionality changes, you will have to track each one of those calls and change them. The newer, desired, approach is to leave the JavaScript in a separate file and instead use the element's CSS class name to apply some logic to the element. So instead of the way above, you will simply define your links as follows:
<a href="#" class="clickMe">Link 1</a>
<a href="#" class="clickMe">Link 2</a>

Now you just need to write the JavaScript which will look for all "a" elements with the CSS class name of "clickMe" and for each one found, it will invoke the "whatDidIClick" function.

<script type="text/javascript" language="javascript">
// For each link element with CSS class name "clickMe"
$$('a.clickMe').invoke('observe', 'click', whatDidIClick);

function whatDidIClick(event) {
// Event.element(event) returns the element that caused the click event
alert('You clicked on ' + Event.element(event).innerHTML));

No comments:

Post a Comment

// //]]>