Introduction to JavaScript Programming using Prototype.JS
Revision 1.1
June 07, 2010
by
Aloysius Indrayanto
(C) 2010 AnemoneSoft.com
This document is multi-licensed under the Creative Commons Attribution Share-Alike (CC-BY-SA) license version 3.0 and the GNU Free Documentation License (GNU FDL) version 1.3 or later.
JavaScript is the most widely-supported client-side scripting language on the internet. It works (with slight incompatibilities) in all major browsers, such as Internet Explorer, Firefox, Google Chrome, Apple Safari, and Opera. It was invented by Brendan Eich at Netscape (with Navigator 2.0) in 1996. It was approved as an international ISO (ISO/IEC 16262) standard in 1998. Features of JavaScript:
It was designed to create interactive HTML pages:
It can create, delete, and modify any HTML element;
It can react to events occurred on many of the HTML elements;
It can be used to validate data;
It can be used to store and retrieve cookies;
It can be used to create animation on the HTML page;
It was designed to be a lightweight programming language;
It supports object-oriented programming;
It can be embedded directly into the HTML pages or loaded as script files;
It is a client-side scripting language (the client's browser execute the script);
It is an interpreted language (although, some browsers may dynamically compile it in the background for better execution speed);
It is free to use by anyone without purchasing a license.
JavaScript is completely different with Java in both concept and design. Java is a much more complex programming language developed by Sun Microsystems.
While JavaScript is supported by all major browsers, some incompatibilities still exist. This incompatibilities would cause difficulties to write a script that will work in all those browsers. Therefore, Sam Stephenson invents Prototype.JS (http://www.prototypejs.org). It is a JavaScript framework that aims to ease development of dynamic web applications. It features an easy-to-use toolkit for class-driven development. The latest Prototype.JS (version 1.6.1) supports Internet Explorer 6.0+, Mozilla Firefox 1.5+, Google Chrome 1.0+, Apple Safari 2.04+, and Opera 9.25+. Prototype.JS also supports other browsers that share rendering engine with those major browsers, such as Camino, Konqueror, IceWeasel, Netscape 6+, SeaMonkey, etc. Prototype.JS is also one of the best free AJAX library in the internet.
AJAX is an acronym for Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. It allows the client (browser) to asynchronously exchange small amounts of data with the server in the background. Hence, the displayed web pages can be updated by changing only a small part of it. Traditional web pages that do not use AJAX will need to reload the entire page to update their contents.
A basic knowledge in programming using JavaScript will be needed to understand the topic discussed in this tutorial. A supported browser (Internet Explorer 6.0+, Mozilla Firefox 1.5+, Google Chrome 1.0+, Apple Safari 2.04+, or Opera 9.25+) will be also needed to run the code snippets.
A possible basic construct of a HTML page that utilizes Prototype.JS is shown in the code snippet below:
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' lang='en' xml:lang='en'>
<head>
<script type='text/javascript' src='prototype-c161.js'></script>
</head>
<body>
</body>
</html>
|
|
A possible basic construct of a HTML page that utilizes Prototype.JS. |
User JavaScript code can be put in any location in the page, even outside the scope of the <html></html> tag. For simplicity, in all the remaining sections, only the content of the <body></body> and <script></script> tags that will be shown in all code snippets.
The $() function is a shortcut for the document.getElementById() function of the Document Object Model (DOM). The $() function returns the element of which id is passed as the argument of the function call. Prototype.JS augments the returned element object with extra methods from Element.Methods to simplify many tasks, such as hiding/showing the element, getting its size, scrolling to the element, etc. If the element is a form, Prototype.JS will also augments the returned object with the utility methods from Form.Methods. If the element is a form field (input, select, or textarea, etc.), Prototype.JS will also augments the returned object with the utility methods from Form.Element.Methods. The code snippet below demonstrate the use of the $() function:
...
...
<body>
<div id='divOne' onclick='divOne_onClick()'>Click Me!</div>
</body>
...
...
<script type='text/javascript'>
function divOne_onClick()
{
$('divOne').innerHTML = 'Hooray!';
$('divOne').shown = true;
setTimeout(
function()
{
if($('divOne').shown) {
$('divOne').hide();
$('divOne').shown = false;
}
else {
$('divOne').show();
$('divOne').shown = true;
}
setTimeout(arguments.callee, 500);
},
500
);
}
</script>
|
|
tut01.html: Blinking text using the $() function. |
Explanation:
The onclick attribute can be set so that a particular function will be executed when the user click the corresponding HTML element.
All HTML container element objects, such as <div></div>, <span></span>, and <p></p> support a property named innerHTML. Setting this property has the effect of “rewriting” the HTML code contained inside the container element.
The function hide() and show() are from Prototype.JS; they are used to hide and show the corresponding element object.
The function setTimeout() takes two arguments, the function to be executed on timeout and the time delay (in milliseconds).
The special variable arguments.callee refers to the function currently being executed.
The $F() function returns the value of any form input control, such as text box, check box, radio button, and drop-down list. The function takes one argument that can be the element id or the element object itself. The code snippet below demonstrate the use of the $F() function:
...
...
<body>
<form id='formOne' onsubmit='return fromOne_onSubmit()'>
Enter your name:
<input id='txtName' type='text' value='John Doe'/>
<input type='submit' value='Submit'/>
</form>
</body>
...
...
<script type='text/javascript'>
function fromOne_onSubmit()
{
alert('Hello ' + $F('txtName') + '!');
return true;
}
</script>
|
|
tut02.html: Obtaining the value of an input control using the $F() function. |
Explanation:
The onsubmit attribute can be set so that a particular function will be executed when the user submit the form. Returning true from the function handler will cause the form to be submitted, while returning false will cancel the submission.
The function alert() can be used whenever a JavaScript program needs to pop up messages to the user.
Note that the $F() function cannot be used to set a new value for the input control. To set a new value for the input control in the above example, one can use:
$('txtName').value = '<new value>';
|
Prototype.JS augments standard JavaScript array with extra methods from Enumerable. Some of the methods are:
|
Method |
Parameters of the Iterator Function (iter_func) |
Description |
|
each(iter_func) |
value, index |
Calls the given iterator function for each element in the array in the first argument and the index of the element in the second argument. |
|
reject(iter_func) |
value, index |
Calls the iterator function for each element in the array and returns an array with all the elements that caused the iterator function to return a value that resolves to false. |
|
select(iter_func) |
value, index |
Calls the iterator function for each element in the array and returns an array with all the elements that caused the iterator function to return a value that resolves to true. |
|
include(object) |
N/A |
Tries to find the given object in the array. Returns true if the object is found, false otherwise. |
The code snippet below demonstrate the use of augmented array to process the values of an array using each of the methods described above:
<script type='text/javascript'>
var srcArray = [1, 2, 3];
// Pop up a message box containing a text ('1', '2', and '3') for each of the value
var result1 = srcArray.each(
function(item)
{
alert(item);
}
);
// Pop up a message box containing text '1,3'
var result1 = srcArray.reject(
function(value)
{
return value == 2;
}
);
alert(result1);
// Pop up a message box containing text '1,2'
var result2 = srcArray.select(
function(value)
{
return (value == 1) || (value == 2);
}
);
alert(result2);
// Pop up a message box containing text 'true'
alert(srcArray.include(1));
// Pop up a message box containing text 'false'
alert(srcArray.include(5));
</script>
|
|
tut03.html: Usage example of augmented array. |
Sometimes, an application will need to loop through a list of objects to build strings based on the object properties and some fixed formatting data. Prototype.JS provides a convenience class Template for this purpose. The code snippet below demonstrate this feature:
<script type='text/javascript'>
var person = [ { name:'Mr. A', age:35, position:'Manager' },
{ name:'Mr. B', age:30, position:'Developer' },
{ name:'Mr. C', age:30, position:'Graphic Designer' }
];
var itemFormat = new Template( '#{name} is #{age} years old and a #{position}' );
var formattedString = '';
person.each(
function(value)
{
formattedString += itemFormat.evaluate(value) + '\n';
}
);
alert(formattedString);
</script>
|
|
tut04.html: Usage example of string template. |
The code snippet below shows a possible basic construct to use the Ajax class from Prototype.JS to perform a simple AJAX request:
<script type='text/javascript'>
new Ajax.Request('<url>', {
method : 'get',
parameters : '<parameter list> + '&' + Math.random(),
onSuccess : function(transport) {
var result = transport.responseText;
},
onFailure : function(transport) {
alert('AJAX Error!');
}
});
</script>
|
|
A possible basic construct to perform a simple AJAX request. |
Explanation:
For simple requests, the method property is normally set to 'get'.
The parameters property must be set with URL-encoded values, for example 'name=john%20doe&age=30'. If the results of the AJAX requests are expected to be dynamic from time to time (even with the same parameters), it is recommended to add 'Math.random()' in the parameter list to prevent caching. Note that if the method is set to 'post' then the values need to be set in the postBody property (not parameters).
Upon a successful request, the callback function set to the parameter onSucess will be called. The result of the request will be put in the first parameter of the function. Respectively, on failed request, the callback function set to the parameter onFailure will be called.
The code snippet below demonstrate the use of the Ajax class to perform a request for a local file (note that, depends on the browser, request for a local file may or may not work):
...
...
<body>
<div id='divOne' onclick='divOne_onClick()'>Click Me!</div>
</body>
...
...
<script type='text/javascript'>
function divOne_onClick()
{
new Ajax.Request('tut05_ajax_data.txt', {
method : 'get',
onSuccess : function(transport) {
$('divOne').innerHTML = transport.responseText;
},
onFailure : function(transport) {
alert('AJAX Error!');
}
});
}
</script>
|
|
tut05.html: Simple AJAX request. |
<hr/> <b>Hello world from AJAX!</b> <hr/> |
|
tut05_ajax_data.txt: The content of the local file being requested. |
The code snippet below contains additional functions that are not part of Prototype.JS but can be used together with Prototype.JS in JavaScript application development:
<script type='text/javascript'>
// Check if the given text is a valid e-mail address
function isValidEmailAddress(str)
{
return(str.search(
/^[a-zA-Z]+([_\.-]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([\.-]?[a-zA-Z0-9]+)*(\.[a-zA-Z]{2,4})+$/
) != -1);
}
// Augment the JavaScript array by adding a method to compare arrays
Array.prototype.compare = function(cmp)
{
if(this.length != cmp.length) return false;
for(var i = 0; i < cmp.length; i++) {
if(this[i].compare) {
if(!this[i].compare(cmp[i])) return false;
}
if(this[i] !== cmp[i]) return false;
}
return true;
}
</script>
|
|
tut06.html: Additional Functions. |
Try to write your own test code for the above functions.
http://www.w3schools.com/js/js_intro.asp, June 01, 2010
http://www.howtocreate.co.uk/tutorials/javascript/introduction, June 01, 2010
http://www.sergiopereira.com/articles/prototype.js.html, June 01, 2010
http://www.w3schools.com/Ajax/ajax_intro.asp, June 01, 2010