Prototype - Overview
What is Prototype ?
Prototype is a JavaScript Framework that aims to ease the development of dynamic web applications. Prototype was developed by Sam Stephenson.Prototype is a JavaScript library, which enables you to manipulate DOM in a very easy and fun way that is also safe (cross-browser).
Scriptaculous and other libraries, 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 application 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 library −- Go to the download page (http://prototypejs.org/download/) to grab the latest version in a convenient package.
- Now, put prototype.js file in a directory of your website, e.g. /javascript.
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> <div id = "firstDiv"> <p>This is first paragraph</p> </div> <div id = "secondDiv"> <p>This is another paragraph</p> </div> <input type = "button" value = "Test $()" onclick = "test();"/> </body> </html>
Output
Why This Tutorial?
A very good documentation for Prototype Framework is available at prototypejs.org then why should one refer to this tutorial!The answer is that we have put all the most commonly used functionalities 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 like a reference manual.
Prototype - Useful Features
Let's now look at what Prototype can do specifically for us to develop a Dynamic Web Application.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 compatibility 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 utilities 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 handling.Ajax Utilities
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 line.
Prototype - Utility Methods
The Prototype library comes with lot of predefined objects and utility 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. | $A() Converts the single argument it receives into an Array object. |
4. | $F() Returns the value of a form control. This is a convenience alias of Form.Element.getValue. |
5. | $H() Converts objects into enumerable Hash objects that resemble associative arrays. |
6. | $R() Creates a new ObjectRange object. |
7. | $w() Splits a string into an Array, treating all whitespace as delimiters. |
8. | Try.these 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 utility functions for manipulating elements in the DOM.Here is the list of all the utility 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. | absolutize() Turns element into an absolutely-positioned element without changing its position in the page layout. |
2. | addClassName() Adds the given CSS class name to the element's class names. |
3. | addMethods() Makes it possible to mix in your own methods to the Element object, which you can later use as methods of extended elements. |
4. | adjacent() Finds all siblings of the current element that match the given selector(s). |
5. | ancestors() Collects all of element's ancestors and returns them as an array of extended elements. |
6. | childElements() 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. | cleanWhitespace() Removes all of element's text nodes, which contain only whitespace. Returns element. |
9. | clonePosition() Clones the position and/or dimensions of source onto element as defined by the optional argument options. |
10. | cumulativeOffset() Returns the offsets of element from the top left corner of the document. |
11. | cumulativeScrollOffset() Calculates the cumulative scroll offset of an element in nested scrolling containers. |
12. | descendantOf() Checks if the element is a descendant of ancestor. |
13. | descendants() Collects all of element's descendants and returns them as an array of extended elements. |
14. | down() 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. | empty() Tests whether element is empty (i.e., contains only whitespace). |
16. | extend() Extends element with all of the methods contained in Element.Methods and Element.Methods.Simulated. |
17. | fire() Fires a custom event with the current element as its target. |
18. | firstDescendant() Returns the first child that is an element. This is opposed to firstChild DOM property, which will return any node. |
19. | getDimensions() 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. | getHeight() Finds and returns the computed height of element. |
23. | getOffsetParent() Returns element's closest positioned ancestor. If none is found, the body element is returned. |
24. | getStyle() Returns the given CSS property value of element. Property can be specified in either of its CSS or camelized form. |
25. | getWidth() Finds and returns the computed width of element. |
26. | hasClassName() Checks whether element has the given CSS className. |
27. | hide() Hides and returns element. |
28. | identify() 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. | insert() Inserts content before, after, at the top of, or at the bottom of element. |
31. | inspect() Returns the debug-oriented string representation of element. |
32. | makeClipping() Simulates the poorly supported CSS clip property by setting element's overflow value to 'hidden'. Returns element. |
33. | makePositioned() 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. | match() Checks if element matches the given CSS selector. |
35. | next() Returns element's following sibling that matches the given cssRule. |
36. | nextSiblings() Collects all of element's next siblings and returns them as an array of extended elements. |
37. | observe() Registers an event handler on element and returns element. |
38. | positionedOffset() Returns element's offset relative to its closest positioned ancestor. |
39. | previous () Returns element's previous sibling that matches the given cssRule. |
40. | previousSiblings() Collects all of element's previous siblings and returns them as an array of extended elements. |
41. | readAttribute() Returns the value of element's attribute or null if attribute has not been specified. |
42. | recursivelyCollect() Recursively collects elements whose relationship is specified by property. |
43. | relativize() Turns element into an relatively-positioned element without changing its position in the page layout. |
44. | remove () Completely removes element from the document and returns it. |
45. | removeClassName() Removes element's CSS className and returns element. |
46. | replace () Replaces element by the content of the html argument and returns the removed element. |
47. | scrollTo () Scrolls the window so that element appears at the top of the viewport. Returns element. |
48. | select() Takes an arbitrary number of CSS selectors (strings) and returns an array of extended descendants of element that match any of them. |
49. | setOpacity() Sets the visual opacity of an element while working around inconsistencies in various browsers. |
50. | setStyle() Modifies element's CSS style properties. |
51. | show() Displays and returns element. |
52. | siblings() Collects all of element's siblings and returns them as an array of extended elements. |
53. | stopObserving() Unregisters handler and returns element. |
54. | toggle() Toggles the visibility of element. |
55. | toggleClassName() Toggles element's CSS className and returns element. |
56. | undoClipping() Sets element's CSS overflow property back to the value it had before Element.makeClipping() was applied. Returns element. |
57. | undoPositioned() Sets element back to the state it was before Element.makePositioned was applied to it. Returns element. |
58. | up() Returns element's first ancestor that matches the given cssRule. |
59. | update() Replaces the content of element with the provided newContent argument and returns element. |
60. | viewportOffset() Returns the X/Y coordinates of element relative to the viewport. |
61. | visible() Returns a Boolean indicating whether or not element is visible. |
62. | wrap() Wraps an element inside another, then returns the wrapper. |
63. | writeAttribute() 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 compatibility, through Number#succ.
- Ruby-like numerical loops with Number#times.
- Simple utility methods such as Number#toColorPart and Number#toPaddedString.
Prototype Number Method
NOTE − Make sure you have the prototype.js version of 1.6.S.No. | Method & Description |
---|---|
1. | abs() Returns the absolute value of the number. |
2. | ceil() Returns the smallest integer greater than or equal to the number. |
3. | floor() Returns the largest integer less than or equal to the number. |
4. | round() Rounds the number to the nearest integer. |
5. | succ() Returns the successor of the current Number, as defined by current + 1. Used to make numbers compatible with ObjectRange. |
6. | times() Encapsulates a regular [0..n] loop, Ruby-style. |
7. | toColorPart() 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. | toJSON() Returns a JSON string. |
9. | toPaddedString() 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 list of all the functions with examples dealing with String.
Prototype String Methods
NOTE − Make sure you have the prototype.js version of 1.6.S.No. | Method & Description |
---|---|
1. | blank() Checks if the string is 'blank', meaning either empty or containing only whitespace. |
2. | camelize() Converts a string separated by dashes into a camelCase equivalent. For instance, 'foo-bar' would be converted to 'fooBar'. |
3. | capitalize() Capitalizes the first letter of a string and downcases all the others. |
4. | dasherize() Replaces every instance of the underscore character ("_") by a dash ("-"). |
5. | empty() Checks if the string is empty. |
6. | endsWith() Checks if the string ends with substring. |
7. | escapeHTML() Converts HTML special characters to their entity equivalents. |
8. | evalJSON() Evaluates the JSON in the string and returns the resulting object. |
9. | evalScripts() Evaluates the content of any script block present in the string. Returns an array containing the value returned by each script. |
10. | extractScripts() Extracts the content of any script block present in the string and returns them as an array of strings. |
11. | gsub() 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. | include() Checks if the string contains a substring. |
13. | inspect() Returns a debug-oriented version of the string. |
14. | interpolate() Treats the string as a Template and fills it with object's properties. |
15. | isJSON() Checks if the string is valid JSON by the use of regular expressions. This security method is called internally. |
16. | parseQuery() Parses a URI-like query string and returns an object composed of parameter/value pairs. |
17. | scan() Allows iterating over every occurrence of the given pattern. |
18. | startsWith() Checks if the string starts with substring. |
19. | strip() Strips all the leading and trailing whitespace from a string. |
20. | stripScripts() Strips a string of anything that looks like an HTML script block. |
21. | stripTags() Strips a string of any HTML tag. |
22. | sub() 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. | succ() Used internally by ObjectRange. Converts the last character of the string to the following character in the Unicode alphabet. |
24. | times() Concatenates the string count times. |
25. | toArray() Splits the string character-by-character and returns an array with the result. |
26. | toJSON() Returns a JSON string. |
27. | toQueryParams() Parses a URI-like query string and returns an object composed of parameter/value pairs. |
28. | truncate() Truncates a string to the given length and appends a suffix to it (indicating that it is only an excerpt). |
29. | underscore() Converts a camelized string into a series of words separated by an underscore ("_"). |
30. | unescapeHTML() Strips tags and converts the entity forms of special HTML characters to their normal form. |
31. | unfilterJSON () Strips comment delimiters around Ajax JSON or JavaScript responses. This security method is called internally. |
No comments:
Post a Comment