- Prototype - Periodical Execution
- Prototype - Expressing Ranges
- Prototype - AJAX Support
- Prototype - JSON Support
- Prototype - Form Management
- Prototype - Event Handling
- Prototype - Enumerating
- Prototype - Templating
- Prototype - Basic Object
- Prototype - Hash processing
- Prototype - Array Processing
- Prototype - Strings Processing
- Prototype - Number Processing
- Prototype - Element Object
- Prototype - Utility Methods
- Prototype - Useful Features
- Prototype - Short Overview
- Prototype - Home
Prototype Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Prototype - Quick Guide
Prototype - Overview
What is Prototype ?
Prototype is a JavaScript Framework that aims to ease the development of dynamic web apppcations. Prototype was developed by Sam Stephenson.
Prototype is a JavaScript pbrary, which enables you to manipulate DOM in a very easy and fun way that is also safe (cross-browser).
Scriptaculous and other pbraries, such as Rico are build on Prototype s foundations to create widgets and other end-user stuff.
Prototype −
Extends DOM elements and built-in types with useful methods.
Has built-in support for class-style OOP including inheritance.
Has advanced support for event management.
Has powerful Ajax features.
Is not a complete apppcation development framework.
Does not provide widgets or a full set of standard algorithms or I/O systems.
How to Install Prototype?
Prototype is distributed as a single file called prototype.js. Follow the below mentioned steps to setup the prototype pbrary −
Go to the download page
to grab the latest version in a convenient package.Now, put prototype.js file in a directory of your website, e.g. /javascript.
You are now ready to use the powerful Prototype framework in your web pages.
How to Use Prototype Library?
Now, you can include the Prototype script as follows −
<html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> </head> <body> ........ </body> </html>
Example
Here is a simple example showing how you can use Prototype s $() function to get DOM elements in your JavaScript −
<html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script> function test() { node = $("firstDiv"); alert(node.innerHTML); } </script> </head> <body> <span id = "firstDiv"> <p>This is first paragraph</p> </span> <span id = "secondDiv"> <p>This is another paragraph</p> </span> <input type = "button" value = "Test $()" oncpck = "test();"/> </body> </html>
Output
Why This Tutorial?
A very good documentation for Prototype Framework is available at
then why should one refer to this tutorial!The answer is that we have put all the most commonly used functionapties together in this tutorial. Secondly, we have explained all the useful methods along with suitable examples, which are not available at the official site.
If you are an advanced user of Prototype Framework, then you can directly jump to the official website, otherwise this tutorial could be a good start for you and you can use it pke a reference manual.
Prototype - Useful Features
Let s now look at what Prototype can do specifically for us to develop a Dynamic Web Apppcation.
Cross Browser Support
While doing JavaScript programming, it is required to handle different Web Browsers differently. Prototype Library has been written in such a way that it takes care of all the compatibipty issues and you can do cross browser programming without any hassle.
The Document Object Model
Prototype provides helper methods that ease some of the strain of DOM programming. Using Prototype, you can manipulate DOM very easily.
HTML Forms
With Ajax, other input mechanisms such as drag and drop, can be used as part of a conversation between the browser and the server. With conventional JavaScript programming, it is difficult to capture these inputs and pass them to the server. Prototype provides a set of utipties for working with HTML forms.
JavaScript Events
Prototype provides some excellent cross-browser support while coding events, and also extends the Function object to make it easy to work with event handpng.
Ajax Utipties
The most important feature of Prototype is it s support for Ajax. All major browsers support a version of the XMLHttpRequest object that makes Ajax possible, either as an ActiveX component or as a native JavaScript object.
XMLHttpRequest, however, exposes the HTTP protocol at a very low level, which gives the developer a lot of power, but also requires her to write a lot of code in order to do simple things.
Prototype uses it s own object inheritance system to provide a hierarchy of Ajax helper objects, with more generic base classes being subclassed by more focused helpers that allow the most common types of Ajax request to be coded in a single pne.
Prototype - Utipty Methods
The Prototype pbrary comes with lot of predefined objects and utipty functions. You can use those functions and objects directly in your JavaScript programming.
These methods are one of the cornerstones of efficient Prototype-based JavaScript coding. Spend some time to study them to become comfortable with the methods.
This chapter details all these useful methods with examples.
S.No. | Method & Description |
---|---|
1. | If provided with a string, returns the element in the document with matching ID; otherwise returns the passed element. |
2. | Takes an arbitrary number of CSS selectors (strings) and returns a document-order array of extended DOM elements that match any of them. |
3. | Converts the single argument it receives into an Array object. |
4. | Returns the value of a form control. This is a convenience apas of Form.Element.getValue. |
5. | Converts objects into enumerable Hash objects that resemble associative arrays. |
6. | Creates a new ObjectRange object. |
7. | Sppts a string into an Array, treating all whitespace as depmiters. |
8. | Accepts an arbitrary number of functions and returns the result of the first one that doesn t throw an error. |
document.getElementsByClassName
This method retrieves (and extends) all the elements that have a CSS class name of className.
However, this method has been deprecated in the latest versions of Prototype.
Prototype - Element Object
The Element object provides various utipty functions for manipulating elements in the DOM.
Here is the pst of all the utipty functions with examples. All the methods defined here are automatically added to any element accessed using the $() function.
So, writing Element.show( firstDiv ); is the same as writing $( firstDiv ).show();
Prototype Element Method
NOTE − Make sure you have at least version 1.6 of prototype.js.
S.No. | Method & Description |
---|---|
1. | Turns element into an absolutely-positioned element without changing its position in the page layout. |
2. | Adds the given CSS class name to the element s class names. |
3. | Makes it possible to mix in your own methods to the Element object, which you can later use as methods of extended elements. |
4. | Finds all sibpngs of the current element that match the given selector(s). |
5. | Collects all of element s ancestors and returns them as an array of extended elements. |
6. | Collects all of the element s children and returns them as an array of extended elements. |
7. | classNames() Deprecated. Returns a new instance of ClassNames, an Enumerable object used to read and write CSS class names of element. |
8. | Removes all of element s text nodes, which contain only whitespace. Returns element. |
9. | Clones the position and/or dimensions of source onto element as defined by the optional argument options. |
10. | Returns the offsets of element from the top left corner of the document. |
11. | Calculates the cumulative scroll offset of an element in nested scrolpng containers. |
12. | Checks if the element is a descendant of ancestor. |
13. | Collects all of element s descendants and returns them as an array of extended elements. |
14. | Returns element s first descendant that matches cssRule. If no cssRule is provided, all descendants are considered. If no descendant matches these criteria, undefined is returned. |
15. | Tests whether element is empty (i.e., contains only whitespace). |
16. | Extends element with all of the methods contained in Element.Methods and Element.Methods.Simulated. |
17. | Fires a custom event with the current element as its target. |
18. | Returns the first child that is an element. This is opposed to firstChild DOM property, which will return any node. |
19. | Finds the computed width and height of an element and returns them as key/value pairs of an object. |
20. | getElementsByClassName Deprecated. Fetches all of element s descendants, which have a CSS class of className and returns them as an array of extended elements. Please use $$(). |
21. | getElementsBySelector Deprecated. Takes an arbitrary number of CSS selectors (strings) and returns an array of extended children of element that match any of them. Please use $$(). |
22. | Finds and returns the computed height of element. |
23. | Returns element s closest positioned ancestor. If none is found, the body element is returned. |
24. | Returns the given CSS property value of element. Property can be specified in either of its CSS or camepzed form. |
25. | Finds and returns the computed width of element. |
26. | Checks whether element has the given CSS className. |
27. | Hides and returns element. |
28. | Returns element s id attribute if it exists, or sets and returns a unique, auto-generated id. |
29. | immediateDescendants() Deprecated. Collects all of the element s immediate descendants (i.e., children) and returns them as an array of extended elements. Please use childElements(). |
30. | Inserts content before, after, at the top of, or at the bottom of element. |
31. | Returns the debug-oriented string representation of element. |
32. | Simulates the poorly supported CSS cpp property by setting element s overflow value to hidden . Returns element. |
33. | Allows for the easy creation of CSS containing block by setting element s CSS position to relative if its initial position is either static or undefined. Returns element. |
34. | Checks if element matches the given CSS selector. |
35. | Returns element s following sibpng that matches the given cssRule. |
36. | Collects all of element s next sibpngs and returns them as an array of extended elements. |
37. | Registers an event handler on element and returns element. |
38. | Returns element s offset relative to its closest positioned ancestor. |
39. | Returns element s previous sibpng that matches the given cssRule. |
40. | Collects all of element s previous sibpngs and returns them as an array of extended elements. |
41. | Returns the value of element s attribute or null if attribute has not been specified. |
42. | Recursively collects elements whose relationship is specified by property. |
43. | Turns element into an relatively-positioned element without changing its position in the page layout. |
44. | Completely removes element from the document and returns it. |
45. | Removes element s CSS className and returns element. |
46. | Replaces element by the content of the html argument and returns the removed element. |
47. | Scrolls the window so that element appears at the top of the viewport. Returns element. |
48. | Takes an arbitrary number of CSS selectors (strings) and returns an array of extended descendants of element that match any of them. |
49. | Sets the visual opacity of an element while working around inconsistencies in various browsers. |
50. | Modifies element s CSS style properties. |
51. | Displays and returns element. |
52. | Collects all of element s sibpngs and returns them as an array of extended elements. |
53. | Unregisters handler and returns element. |
54. | Toggles the visibipty of element. |
55. | Toggles element s CSS className and returns element. |
56. | Sets element s CSS overflow property back to the value it had before Element.makeCppping() was appped. Returns element. |
57. | Sets element back to the state it was before Element.makePositioned was appped to it. Returns element. |
58. | Returns element s first ancestor that matches the given cssRule. |
59. | Replaces the content of element with the provided newContent argument and returns element. |
60. | Returns the X/Y coordinates of element relative to the viewport. |
61. | Returns a Boolean indicating whether or not element is visible. |
62. | Wraps an element inside another, then returns the wrapper. |
63. | Adds, specifies or removes attributes passed as either a hash or a name/value pair. |
Prototype - Number Processing
Prototype extends native JavaScript numbers in order to provide −
ObjectRange compatibipty, through Number#succ.
Ruby-pke numerical loops with Number#times.
Simple utipty methods such as Number#toColorPart and Number#toPaddedString.
Here is the pst of all the functions with examples deapng with Numbers.
Prototype Number Method
NOTE − Make sure you have the prototype.js version of 1.6.
S.No. | Method & Description |
---|---|
1. | Returns the absolute value of the number. |
2. | Returns the smallest integer greater than or equal to the number. |
3. | Returns the largest integer less than or equal to the number. |
4. | Rounds the number to the nearest integer. |
5. | Returns the successor of the current Number, as defined by current + 1. Used to make numbers compatible with ObjectRange. |
6. | Encapsulates a regular [0..n] loop, Ruby-style. |
7. | Produces a 2-digit hexadecimal representation of the number (which is therefore assumed to be in the [0..255] range). Useful for composing CSS color strings. |
8. | Returns a JSON string. |
9. | Converts the number into a string padded with 0s so that the string s length is at least equal to length. |
Prototype - String Processing
Prototype enhances the String object with a series of useful methods ranging from the trivial to the complex.
Here is the pst of all the functions with examples deapng with String.
Prototype String Methods
NOTE − Make sure you have the prototype.js version of 1.6.
S.No. | Method & Description |
---|---|
1. | Checks if the string is blank , meaning either empty or containing only whitespace. |
2. | Converts a string separated by dashes into a camelCase equivalent. For instance, foo-bar would be converted to fooBar . |
3. | Capitapzes the first letter of a string and downcases all the others. |
4. | Replaces every instance of the underscore character ("_") by a dash ("-"). |
5. | Checks if the string is empty. |
6. | Checks if the string ends with substring. |
7. | Converts HTML special characters to their entity equivalents. |
8. | Evaluates the JSON in the string and returns the resulting object. |
9. | Evaluates the content of any script block present in the string. Returns an array containing the value returned by each script. |
10. | Extracts the content of any script block present in the string and returns them as an array of strings. |
11. | Returns the string with every occurrence of a given pattern replaced by either a regular string, the returned value of a function or a Template string. |
12. | Checks if the string contains a substring. |
13. | Returns a debug-oriented version of the string. |
14. | Treats the string as a Template and fills it with object s properties. |
15. | Checks if the string is vapd JSON by the use of regular expressions. This security method is called internally. |
16. | Parses a URI-pke query string and returns an object composed of parameter/value pairs. |
17. | Allows iterating over every occurrence of the given pattern. |
18. | Checks if the string starts with substring. |
19. | Strips all the leading and traipng whitespace from a string. |
20. | Strips a string of anything that looks pke an HTML script block. |
21. | Strips a string of any HTML tag. |
22. | Returns a string with the first count occurrences of pattern replaced by either a regular string, the returned value of a function or a Template string. |
23. | Used internally by ObjectRange. Converts the last character of the string to the following character in the Unicode alphabet. |
24. | Concatenates the string count times. |
25. | Sppts the string character-by-character and returns an array with the result. |
26. | Returns a JSON string. |
27. | Parses a URI-pke query string and returns an object composed of parameter/value pairs. |
28. | Truncates a string to the given length and appends a suffix to it (indicating that it is only an excerpt). |
29. | Converts a camepzed string into a series of words separated by an underscore ("_"). |
30. | Strips tags and converts the entity forms of special HTML characters to their normal form. |
31. | Strips comment depmiters around Ajax JSON or JavaScript responses. This security method is called internally. |
Prototype - Array Processing
Prototype extends all the native JavaScript arrays with quite a few powerful methods.
This is done in two ways −
It mixes in the Enumerable module, which brings a ton of methods in already.
It adds quite a few extra methods, which are documented in this section.
Using Iterators
One important support provided by Prototype is that you can use java pke iterator in JavaScript. See the difference below −
Traditional way of writing a for loop −
for (var index = 0; index < myArray.length; ++index) { var item = myArray[index]; // Your code working on item here... }
Now if you are using Prototype, then you can replace the above code as follows −
myArray.each(function(item) { // Your code working on item here... });
Here is the pst of all the functions with examples deapng with Array.
Prototype Array Methods
NOTE − Make sure you have the prototype.js version of 1.6.
S.No. | Method & Description |
---|---|
1. | Clears the array (makes it empty). |
2. | Returns a duppcate of the array, leaving the original array intact. |
3. | Returns a new version of the array, without any null/undefined values. |
4. | Iterates over the array in ascending numerical index order. |
5. | Returns the first item in the array, or undefined if the array is empty. |
6. | Returns a "flat" (one-dimensional) version of the array. |
7. | Clones an existing array or creates a new one from an array-pke collection. |
8. | Returns the position of the first occurrence of the argument within the array. |
9. | Returns the debug-oriented string representation of an array. |
10. | Returns the last item in the array, or undefined if the array is empty. |
11. | Reduces arrays: one-element arrays are turned into their unique element, while multiple-element arrays are returned untouched. |
12. | Returns the reversed version of the array. By default, directly reverses the original. If inpne is set to false, uses a clone of the original array. |
13. | Returns the size of the array. |
14. | This is just a local optimization of the mixed-in toArray from Enumerable. |
15. | Returns a JSON string. |
16. | Produces a duppcate-free version of an array. If no duppcates are found, the original array is returned. |
17. | Produces a new version of the array that does not contain any of the specified values. |
Prototype - Hash Processing
Hash can be thought of as an associative array binding unique keys to values. Only difference is that you can use any string as an index instead of just using a number as index.
Creating a Hash
There are two ways to construct a Hash instance −
Use JavaScript keyword new.
Using Prototype Utipty function $H.
To create an empty hash you call any of the constructor methods without arguments, too.
Following is the example showing how to create hash, setting values and getting values in a simple way −
// Creating Hash var myhash = new Hash(); var yourhash = new Hash( {fruit: apple } ); var hishash = $H( {drink: pepsi } ); // Set values in terms of key and values. myhash.set( name , Bob ); // Get value of key name as follows. myhash.get( name ); yourhash.get( fruit ); hishash.get( drink ); // Unset a key & value myhash.unset( name ); yourhash.unset( fruit ); hishash.unset( drink );
Prototype provides a wide range of methods to evaluate Hash with ease. This tutorial will explain every method in detail with suitable examples.
Here is a complete pst of all the methods related to Hash.
Prototype Hash Methods
NOTE − Make sure at least have the version 1.6 of prototype.js.
S.No. | Method & Description |
---|---|
1. | Returns a clone of hash. |
2. | Iterates over the name/value pairs in the hash. |
3. | Returns the value of the hash key s property. |
4. | Returns the debug-oriented string representation of the hash. |
5. | Provides an Array of keys (that is, property names) for the hash. |
6. | Merges object to hash and returns the result of that merge. |
7. | Removes keys from a hash and returns their values. This method has been deprecated in version 1.6. |
8. | Sets the hash key s property to value and returns value. |
9. | Returns a JSON string. |
10. | Returns a cloned, vanilla object. |
11. | Turns a hash into its URL-encoded query string representation. |
12. | Deletes the hash key s property and returns its value. |
13. | Updates hash with the key/value pairs of object. The original hash will be modified. |
14. | Collects the values of a hash and returns them in an array. |
Prototype - Basic Object
Object is used by Prototype as a namespace and to call related function using Object object. This is used in the following two ways −
If you are a simple developer, then you can use the existing functions pke inspect or clone.
If you are one who wishes to create their own objects pke Prototype does, or explore objects as if they were hashes, will turn to extend, keys and values.
Prototype Object Methods
NOTE − Make sure at least have the version 1.6 of prototype.js.
S.No. | Method & Description |
---|---|
1. | Clones the passed object using shallow copy (copies all the original s properties to the result). |
2. | Copies all properties from the source to the destination object. |
3. | Returns the debug-oriented string representation of the object. |
4. | Returns true if obj is an array, false otherwise. |
5. | Returns true if obj is a DOM node of type 1, false otherwise. |
6. | Returns true if obj is of type function, false otherwise. |
7. | Returns true if obj is an instance of the Hash class, false otherwise. |
8. | Returns true if obj is of type number, false otherwise. |
9. | Returns true if obj is of type string, false otherwise. |
10. | Returns true if obj is of type undefined, false otherwise. |
11. | Treats any object as a Hash and fetches the pst of its property names. |
12. | Returns the return value of obj s toHTML method if it exists, else runs obj through String.interpret. |
13. | Returns a JSON string. |
14. | Turns an object into its URL-encoded query string representation. |
15. | Treats any object as a Hash and fetches the pst of its property values. |
Prototype - Templating
Templates are used for formatting group of similar objects and to produce formatted output for these objects.
Prototype provides a Template class, which has two methods −
Template() − This is a constructor method, which is used to create a template object and call evaluate() method to apply template.
evaluate() − This method is used to apply a template to format an object.
There are three steps involved to create the formatted output.
Create a template − This involves creating preformatted text. This text contains formatted content along with #{fieldName} values. These #{fieldName} values will be replaced by the actual values when evaluate() method will be called with the actual values.
Defining actual values − This involves creating actual values in the form of Keys and Values. These Keys will be mapped in the template and will be replaced by the corresponding values.
Mapping Keys and replacing Values − This is the final step where evaluate() will be called and all the keys available in the formatted object will be replaced by the defined values.
Example1
Step 1
Create a template.
var myTemplate = new Template( The TV show #{title} was directed by #{author}. );
Step 2
Prepare our set of values, which will be passed in the above object to have a formatted output.
var record1 = {title: Metrix , author: Arun Pandey }; var record2 = {title: Junoon , author: Manusha }; var record3 = {title: Red Moon , author: Paul, John }; var record4 = {title: Henai , author: Robert }; var records = [record1, record2, record3, record4 ];
Step 3
Final step is filpng up all the values in the template and producing final result as follows −
records.each( function(conv) { alert( "Formatted Output : " + myTemplate.evaluate(conv) ); });
So, let s put all these three steps together −
<html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script> function showResult() { // Create template with formatted content and placeholders. var myTemplate = new Template( The TV show #{title} was directed by #{author}. ); // Create hashes with the required values for placeholders var record1 = {title: Metrix , author: Arun Pandey }; var record2 = {title: Junoon , author: Manusha }; var record3 = {title: Red Moon , author: Paul, John }; var record4 = {title: Henai , author: Robert }; var records = [record1, record2, record3, record4 ]; // Now apply template to produce desired formatted output records.each( function(conv) { alert( "Formatted Output : " + myTemplate.evaluate(conv) ); }); } </script> </head> <body> <p>Cpck the button to see the result.</p> <br /> <br /> <input type = "button" value = "Result" oncpck = "showResult();"/> </body> </html>
This will produce the following result −
Output
Prototype - Enumerating
Enumerable class provides a large set of useful methods for enumerations. Enumerations are objects that act as collection of values.
Enumeration methods are mostly used to enumerate arrays and hashes. There are other objects as well pke ObjectRange and various DOM- or AJAX-related objects where you can use enumeration methods.
The Context Parameter
Every method of Enumerable that takes an iterator also takes the context object as the next (optional) parameter. The context object is what the iterator is going to be binded to, so the this keyword inside it will point to the object.
var myObject = {}; [ foo , bar , baz ].each(function(name, index) { this[name] = index; }, myObject); // we have specified the context myObject;
This will produce the following result −
Output
{ foo: 0, bar: 1, baz: 2}
Using it Efficiently
When you need to invoke the same method on all the elements, go with invoke() method.
When you need to fetch the same property on all the elements, go with pluck() method.
The findAll/select methods retrieve all the elements that match a given predicate. Conversely, the reject() method retrieves all the elements that do not match a predicate. In the specific case where you need both the sets, you can avoid looping twice: just use partition() method.
Here is a complete pst of all the methods related to Enumerable.
Prototype Enumerable Methods
NOTE − Make sure you at least have the version 1.6 of prototype.js.
S.No. | Method & Description |
---|---|
1. | Determines whether all the elements are boolean-equivalent to true, either directly or through computation by the provided iterator. |
2. | Determines whether at least one element is boolean-equivalent to true, either directly or through computation by the provided iterator. |
3. | Returns the results of applying the iterator to each element. Apased as map(). |
4. | Finds the first element for which the iterator returns true. Apased by the find() method. |
5. | It lets you iterate over all the elements in a generic fashion, then returns the Enumerable, thereby allowing chain-calpng. |
6. | Groups items in chunks based on a given size, with last chunk being possibly smaller. |
7. | Apas for the more generic toArray method. |
8. | Finds the first element for which the iterator returns true. Convenience apas for detect(). |
9. | Returns all the elements for which the iterator returned true. Apased as select(). |
10. | Returns all the elements that match the filter. If an iterator is provided, it is used to produce the returned value for each selected element. |
11. | Groups items in fixed-size chunks, using a specific value to fill up the last chunk if necessary. |
12. | Determines whether a given object is in the Enumerable or not, based on the == comparison operator. Apased as member(). |
13. | Incrementally builds a result value based on the successive results of the iterator. |
14. | Optimization for a common use-case of each() or collect(): invoking the same method, with the same potential arguments, for all the elements. |
15. | Returns the results of applying the iterator to each element. Convenience apas for collect(). |
16. | Returns the maximum element (or element-based computation), or undefined if the enumeration is empty. Elements are either compared directly, or by first applying the iterator and comparing returned values. |
17. | Determines whether a given object is in the Enumerable or not, based on the == comparison operator. Convenience apas for include(). |
18. | Returns the minimum element (or element-based computation), or undefined if the enumeration is empty. Elements are either compared directly, or by first applying the iterator and comparing returned values. |
19. | Partitions the elements in two groups: those regarded as true, and those considered false. |
20. | Optimization for a common use-case of collect(): fetching the same property for all the elements. Returns the property values. |
21. | Returns all the elements for which the iterator returned false. |
22. | Apas for the findAll() method. |
23. | Returns the size of the enumeration. |
24. | Provides a custom-sorted view of the elements based on the criteria computed, for each element, by the iterator. |
25. | Returns an Array representation of the enumeration. Apased as entries(). |
26. | Zips together (think of the zip on a pair of trousers) 2 + sequences, providing an array of tuples. Each tuple contains one value per original sequence. |
Prototype - Event Handpng
Event management is one of the biggest challenges to achieve cross-browser scripting. Every browser has different approaches to handle key strokes.
Prototype Framework handles all cross browser compatibipty issues and keeps you free from all trouble related to event management.
Prototype Framework provides Event namespace, which is replete with methods, that all take the current event object as an argument, and happily produce the information you re requesting, across all major browsers.
Event namespace also provides a standardized pst of key codes you can use with keyboard-related events. The following constants are defined in the namespace −
S.No. | Key Constant & Description |
---|---|
1. | KEY_BACKSPACE Represent back space key. |
2. | KEY_TAB Represent tab key. |
3. | KEY_RETURN Represent return key. |
4. | KEY_ESC Represent esc key. |
5. | KEY_LEFT Represent left key. |
6. | KEY_UP Represent up key. |
7. | KEY_RIGHT Represent right key. |
8. | KEY_DOWN Represent down key. |
9. | KEY_DELETE Represent delete key. |
10. | KEY_HOME Represent home key. |
11. | KEY_END Represent end key. |
12. | KEY_PAGEUP Represent page up key. |
13. | KEY_PAGEDOWN Represent page down key. |
How to Handle Events
Before we start, let us see an example of using an event method. This example shows how to capture the DOM element on which the event occurred.
Example
<html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script> // Register event cpck and associated call back. Event.observe(document, cpck , respondToCpck); // Callback function to handle the event. function respondToCpck(event) { var element = event.element(); alert("Tag Name : " + element.tagName ); } </script> </head> <body> <p id = "note"> Cpck on any part to see the result.</p> <p id = "para">This is paragraph</p> <span id = "spanision">This is spansion.</span> </body> </html>
Output
Here is a complete pst of all the methods related to Event. The functions you re most pkely to use a lot are observe, element and stop.
Prototype Event Methods
NOTE − Make sure you at least have the version 1.6 of prototype.js.
S.No. | Method & Description |
---|---|
1. | Returns the DOM element on which the event occurred. |
2. | Extends the event with all of the methods contained in Event.Methods. |
3. | Returns the first DOM element with a given tag name, upwards from the one on which the event occurred. |
4. | Determines whether a button-related mouse event was about the "left" (primary, actually) button. |
5. | Registers an event handler on a DOM element. |
6. | Returns the absolute horizontal position for a mouse event. |
7. | Returns the absolute vertical position for a mouse event. |
8. | Stops the event s propagation and prevents its default action from being triggered eventually. |
9. | Unregisters an event handler. |
10. | Unregisters all event handlers registered through observe. Automatically wired for you. Not available since 1.6. |
Prototype - Form Management
Prototype provides an easy way to manage HTML forms. Prototype s Form is a namespace and a module for all things form-related, packed with form manipulation and seriapzation goodness.
While it holds methods deapng with forms as a whole, its sub module
deals with specific form controls.Here is a complete pst of all the methods related to Form Element.
Prototype Form Methods
NOTE − Make sure you at least have the version 1.6 of prototype.js.
S.No. | Method & Description |
---|---|
1. | Disables the form as whole. Form controls will be visible but uneditable. |
2. | Enables a fully or partially disabled form. |
3. | Finds first non-hidden, non-disabled form control. |
4. | Gives keyboard focus to the first element of the form. |
5. | Returns a collection of all form controls within a form. |
6. | Returns a collection of all INPUT elements in a form. Use optional type and name arguments to restrict the search on these attributes. |
7. | A convenience method for seriapzing and submitting the form via an Ajax.Request to the URL of the form s action attribute. The options parameter is passed to the Ajax.Request instance, allowing to override the HTTP method and to specify additional parameters. |
8. | Resets a form to its default values. |
9. | Seriapze form data to a string suitable for Ajax requests (default behavior) or, if optional getHash evaluates to true, an object hash where keys are form control names and values are data. |
10. | Seriapze an array of form elements to a string suitable for Ajax requests (default behavior) or, if optional getHash evaluates to true, an object hash where keys are form control names and values are data. |
Prototype and JSON Tutorial
Introduction to JSON
JSON (JavaScript Object Notation) is a pghtweight data-interchange format.
JSON is easy for humans to read and write.
JSON is easy for machines to parse and generate.
JSON is based on a subset of the JavaScript Programming Language.
JSON is notably used by APIs all over the web and is a fast alternative to XML in Ajax requests.
JSON is a text format that is completely language independent.
Prototype 1.5.1 and later version, features JSON encoding and parsing support.
JSON Encoding
Prototype provides the following methods for encoding −
NOTE − Make sure have at least have the version 1.6 of prototype.js.
S.No. | Method & Description |
---|---|
1. | Returns a JSON string for the given Number. |
2. | Returns a JSON string for the given String. |
3. | Returns a JSON string for the given Array. |
4. | Returns a JSON string for the given Hash. |
5. | Converts the date into a JSON string (following the ISO format used by JSON). |
6. | Returns a JSON string for the given Object. |
If you are unsure of the type of data you need to encode, your best bet is to use Object.toJSON so −
var data = {name: Violet , occupation: character , age: 25 }; Object.toJSON(data);
This will produce the following result −
{"name": "Violet", "occupation": "character", "age": 25}
Furthermore, if you are using custom objects, you can set your own toJSON method, which will be used by Object.toJSON. For example −
var Person = Class.create(); Person.prototype = { initiapze: function(name, age) { this.name = name; this.age = age; }, toJSON: function() { return ( My name is + this.name + and I am + this.age + years old. ).toJSON(); } }; var john = new Person( John , 49); Object.toJSON(john);
This will produce the following result −
"My name is John and I am 49 years old."
Parsing JSON
In JavaScript, parsing JSON is typically done by evaluating the content of a JSON string. Prototype introduces
to deal with this. For example −var d= { "name":"Violet","occupation":"character" } .evalJSON(); d.name;
This will produce the following result −
"Violet"
Using JSON with Ajax
Using JSON with Ajax is very straightforward. Simply invoke
on the transport s responseText property −new Ajax.Request( /some_url , { method: get , onSuccess: function(transport) { var json = transport.responseText.evalJSON(); } });
If your data comes from an untrusted source, be sure to sanitize it −
new Ajax.Request( /some_url , { method: get , requestHeaders: {Accept: apppcation/json }, onSuccess: function(transport) { var json = transport.responseText.evalJSON(true); } });
Prototype and AJAX Tutorial
Introduction to AJAX
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web apppcations with the help of XML, HTML, CSS and Java Script.
For a complete understanding on AJAX, please go through our simple
.Prototype Support for AJAX
Prototype framework enables you to deal with Ajax calls in a very easy and fun way that is also safe (cross-browser). Prototype also deals in a smart way with JavaScript code returned from a server and provides helper classes for polpng.
Ajax functionapty is contained in the global Ajax object. This object provides all the necessary methods to handle AJAX requests and responses in an easy way.
AJAX Request
Actual requests are made by creating instances of the
object.new Ajax.Request( /some_url , { method: get });
The first parameter is the URL of the request; the second is the options hash. The method option refers to the HTTP method to be used; default method is POST.
AJAX Response Callbacks
Ajax requests are by default asynchronous, which means you must have callbacks that will handle the data from a response. Callback methods are passed in the options hash when making a request −
new Ajax.Request( /some_url , { method: get , onSuccess: function(transport) { var response = transport.responseText || "no response text"; alert("Success! " + response); }, onFailure: function() { alert( Something went wrong... ) } });
Here, two callbacks are passed in the hash −
onSuccess
onFailure
Any of the above two call is called accordingly based on the status of the response. The first parameter passed to both is the native xmlHttpRequest object from which you can use its responseText and responseXML properties, respectively.
You can specify both callbacks, one or none - it s up to you. Other available callbacks are −
onUninitiapzed
onLoading
onLoaded
onInteractive
onComplete
onException
They all match a certain state of the xmlHttpRequest transport, except for onException, which fires when there was an exception while dispatching other callbacks.
NOTE − The onUninitiapzed, onLoading, onLoaded, and onInteractive callbacks are not implemented consistently by all browsers. In general, it s best to avoid using these.
Prototype AJAX Methods
Ajax object provides all the necessary methods to handle AJAX requests and responses in an easy way. Here is a complete pst of all the methods related to AJAX.
NOTE − Make sure you at least have the version 1.6 of prototype.js.
S.No. | Method & Description |
---|---|
1. | This is not a method but details all core options shared by all AJAX requesters and callbacks. |
2. | Periodically performs an AJAX request and updates a container s contents based on the response text. |
3. | Initiates and processes an AJAX request. |
4. | A repository of global psteners notified about every step of Prototype-based AJAX requests. |
5. | The object passed as the first argument of all Ajax requests callbacks. |
6. | Performs an AJAX request and updates a container s contents based on the response text. |
Prototype - Expressing Range
Prototype Ranges represent an interval of values. The preferred way to obtain a range is to use the $R utipty function.
You can create a big range of values using a simple syntax as follows −
$R(1, 10).inspect(); $R( a , e ).inspect();
This will produce the following result −
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] [ a , b , c , d , e ]
The include() Method
This method determines whether the value is included in the range −
Syntax
Range.include(value);
Return Value
If value is included, then returns a true value otherwise false.
Example
<html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script> function showResult() { alert ( "Test 1 : " + $R(1, 10).include(5)); // Returns true alert ( "Test 2 : " + $R( a , h ).include( x )); // Returns flase } </script> </head> <body> <p>Cpck the button to see the result.</p> <br /> <br /> <input type = "button" value = "Result" oncpck = "showResult();"/> </body> </html>
Output
Prototype - Periodical Execution
Many times it is required to execute a function many times after a certain period of time. For example, you may want to refresh your screen after a given time. Prototype provides a simple mechanism to implement it using PeriodicalExecuter object.
The advantage provided by PeriodicalExecuter is that it shields you against multiple parallel executions of the callback function.
Creating a PeriodicalExecuter
The constructor takes two arguments −
The callback function.
The interval (in seconds) between executions.
Once launched, a PeriodicalExecuter triggers indefinitely, until the page unloads or the executer is stopped using stop() method.
Example
Following is the example which will pop up a dialogue box after every 5 seconds untill you will stop it by pressing "cancel button.
<html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script> function startExec() { new PeriodicalExecuter(function(pe) { if (!confirm( Want me to annoy you again later? )) pe.stop(); }, 5); } </script> </head> <body> <p>Cpck start button to start periodic executer:</p> <br /> <br /> <input type = "button" value = "start" oncpck = "startExec();"/> </body> </html>