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.



1. Introduction

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:

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.

2. Requirements

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.

3. Start Using Prototype.JS

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.

3.1 The $() Function

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:

3.2 The $F() Function

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:

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>';

4. Some Simple but Useful Features of Prototype.JS

4.1. Augmented Array

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.

4.2. String Template

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.

5. Performing Simple AJAX Requests

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:

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.

6. Additional Functions

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.



References



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