Javascript awesomeness with Prototype

I've talked a bit about the Ajax features of Prototype in a previous post. Now I want to talk about some of the other fun things Prototype can do.

The first thing to do is add the appropriate Prototype includes to your HTML file. You can do this by downloading the latest version from http://www.prototypejs.org and hosting it yourself.

Or you can let Google do the hard work by adding this to your HTML header:

~~~~ {.html name="code"} wzxhzdk:0

The basic format of Event.observe is Event.observe(<element>, '<event>', <event-handling-function>)

We could just as easily have done this

~~~~ {.js name="code"} function HelloWorld() { alert('Hello World!');}Event.observe(window, 'load', HelloWorld); wzxhzdk:1

Let's set up an event handler for the click event on that submit button. We just need to add a few lines to our existing window load event handler.

~~~~ {.js name="code"} Event.observe(window, 'load', function() { Event.observe( $('dostuff'), 'click', function() { alert('Hello World!'); });}); wzxhzdk:2

Let's update our window load javascript code

~~~~ {.js name="code"} Event.observe(window, 'load', function() { Event.observe( $('dostuff'), 'click', function() { $$('input[type=checkbox]').each( function(elem) { alert(elem.id); }); });}); ~~~~

The example above shows a simple example of the $$ utility method which takes a CSS rule as an argument and returns a list of Prototype-enhanced elements.

In our example, we're using the each method to apply a function to every item in the list returned by $$.

Here are a few more simple examples of $$:

  • $$('input') returns a list all input elements.
  • $$('td.even') returns a list of all td elements that have a class of even
  • $$('table#stuff td') returns a list of all td elements that are inside the table element that has an id of stuff

So those are few simple examples of using Prototype to retrieve DOM elements. I'll come back and cover some other Prototype fun in a later post.