Developer Notes for prototype.js
This guide is based on the
Developer Notes for prototype.js by Sergio Pereira.
What is that?
In case you haven't already used it, prototype.js is a
JavaScript library written by Sam Stephenson.
This amazingly well thought and well written piece of standards-compliant code takes a lot of
the burden associated with creating rich, highly interactive web pages that characterize the Web 2.0 off your back.
If you tried to use this library recently, you probably noticed that documentation is not one
of its strongest points. As many other developers before me, I got my head around prototype.js by
reading the source code and experimenting with it. I thought it would be nice to take notes while
I learned and share with everybody else.
As you read the examples and the reference, developers familiar with the Ruby
programming language will notice an intentional similarity between Ruby's
built-in classes and many of the extensions implemented by this library.
Using the $() function
The $() function is a handy shortcut to the all-too-frequent document.getElementById() function
of the DOM. Like the DOM function, this one returns the element that has the id passed as an argument.
Unlike the DOM function, though, this one goes further. You can pass more than one id and
$() will return an Array object with
all the requested elements. The example below should illustrate this.
<com:TClientScript UsingClientScripts="prado" />
<div id="myDiv">
<p id="830731" class="block-content">This is a paragraph</p>
</div>
<div id="myOtherDiv">
<p id="830732" class="block-content">This is another paragraph</p>
</div>
<input type="button" value=Test1 onclick="test1();" />
<input type="button" value=Test2 onclick="test2();" />
<script type="text/javascript">
function test1()
{
var d = $('myDiv');
alert(d.innerHTML);
}
function test2()
{
var divs = $('myDiv','myOtherDiv');
for(i=0; i<divs.length; i++)
{
alert(divs[i].innerHTML);
}
}
</script>
Another nice thing about this function is that you can pass either the id string or the element object itself,
which makes this function very useful when creating other functions that can also take either form of argument.
Using the $F() function
The $F() function is a another welcome shortcut. It returns the value of any field input control,
like text boxes or drop-down lists. The function can take as argument either the element id or the element object itself.
<input type="text" id="userName" value="Joe Doe" />
<input type="button" value=Test3 onclick="test3();" />
<script type="text/javascript">
function test3()
{
alert($F('userName'));
}
</script>