Prototype – Overview ”; Previous Next 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. 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> <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. Print Page Previous Next Advertisements ”;
Category: prototype
Prototype – Basic Object
Prototype – Basic Object ”; Previous Next 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 like inspect or clone. If you are one who wishes to create their own objects like 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. clone() Clones the passed object using shallow copy (copies all the original”s properties to the result). 2. extend() Copies all properties from the source to the destination object. 3. inspect() Returns the debug-oriented string representation of the object. 4. isArray () Returns true if obj is an array, false otherwise. 5. isElement() Returns true if obj is a DOM node of type 1, false otherwise. 6. isFunction() Returns true if obj is of type function, false otherwise. 7. isHash() Returns true if obj is an instance of the Hash class, false otherwise. 8. isNumber() Returns true if obj is of type number, false otherwise. 9. isString() Returns true if obj is of type string, false otherwise. 10. isUndefined() Returns true if obj is of type undefined, false otherwise. 11. keys() Treats any object as a Hash and fetches the list of its property names. 12. toHTML() Returns the return value of obj”s toHTML method if it exists, else runs obj through String.interpret. 13. toJSON() Returns a JSON string. 14. toQueryString() Turns an object into its URL-encoded query string representation. 15. values() Treats any object as a Hash and fetches the list of its property values. Print Page Previous Next Advertisements ”;
Prototype – Number Processing ”; Previous Next 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. Here is the list of all the functions with examples dealing with Numbers. 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. Print Page Previous Next Advertisements ”;
Prototype – Element Object
Prototype – Element Object ”; Previous Next 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
Prototype – JSON Support
Prototype and JSON Tutorial ”; Previous Next Introduction to JSON JSON (JavaScript Object Notation) is a lightweight 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. Number.toJSON() Returns a JSON string for the given Number. 2. String.toJSON() Returns a JSON string for the given String. 3. Array.toJSON() Returns a JSON string for the given Array. 4. Hash.toJSON() Returns a JSON string for the given Hash. 5. Date.toJSON() Converts the date into a JSON string (following the ISO format used by JSON). 6. Object.toJSON() 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 = { initialize: 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 String.evalJSON 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 String.evalJSON 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: ”application/json”}, onSuccess: function(transport) { var json = transport.responseText.evalJSON(true); } }); Print Page Previous Next Advertisements ”;
Prototype – Event Handling
Prototype – Event Handling ”; Previous Next 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 compatibility 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 list 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 ”click” and associated call back. Event.observe(document, ”click”, respondToClick); // Callback function to handle the event. function respondToClick(event) { var element = event.element(); alert(“Tag Name : ” + element.tagName ); } </script> </head> <body> <p id = “note”> Click on any part to see the result.</p> <p id = “para”>This is paragraph</p> <div id = “division”>This is divsion.</div> </body> </html> Output Here is a complete list of all the methods related to Event. The functions you”re most likely 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. element() Returns the DOM element on which the event occurred. 2. extend() Extends the event with all of the methods contained in Event.Methods. 3. findElement() Returns the first DOM element with a given tag name, upwards from the one on which the event occurred. 4. isLeftClick() Determines whether a button-related mouse event was about the “left” (primary, actually) button. 5. observe() Registers an event handler on a DOM element. 6. pointerX() Returns the absolute horizontal position for a mouse event. 7. pointerY() Returns the absolute vertical position for a mouse event. 8. stop() Stops the event”s propagation and prevents its default action from being triggered eventually. 9. stopObserving() Unregisters an event handler. 10. unloadCache() Unregisters all event handlers registered through observe. Automatically wired for you. Not available since 1.6. Print Page Previous Next Advertisements ”;