240 likes | 428 Vues
Javascript Prototype. Chapters 10 JavaScript Tutorial at http://www.w3schools.com/js/ Prototype tutorial at http://prototypejs.org / Or http://api.prototypejs.org/. Problems with JavaScript . JavaScript is a powerful language, but it has many flaws : the DOM can be clunky to use
E N D
Javascript Prototype Chapters 10 JavaScript Tutorial at http://www.w3schools.com/js/ Prototype tutorial at http://prototypejs.org/ Or http://api.prototypejs.org/
Problems with JavaScript • JavaScript is a powerful language, but it has many flaws: • the DOM can be clunky to use • the same code doesn't always work the same way in every browser • code that works great in Firefox, Safari, ... will fail in IE and vice versa • many developers work around these problems with hacks (checking if browser is IE, etc.) • Many groups have created standard libraries of functionality to extend JavaScript to more easily walk the DOM, respond to events, and handle browser compatibility. • Jquery • Dojo • Scriptaculuous • Prototype • We prefer Prototype: syntax closest to JavaScript and holds solid alliances with web development community.
Prototype framework • Prototype library is implemented in a large .jsfile. • you must link to Prototype in your web page. • Download the Prototype from http://prototypejs.org/ • Save it in prototype.js file in your system and link to it in your pages • If you save it in a folder different than that of your web page, you have to provide the path • you can link to it directly from • the Prototype JavaScript library adds many useful features to JavaScript: • many useful extensions to the DOM • added methods to String, Array, Date, Number, Object • improves event-driven programming • many cross-browser compatibility fixes • makes Ajax programming easier (seen later) <script src="prototype.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js" type="text/javascript"></script>
The Prototype $ function $("id") • returns the DOM object representing the element with the given id • short for document.getElementById("id") • document.getElementById returns the DOM object for an element with a given id • often used to write more concise DOM code: $("footer").innerHTML = $("username").value.toUpperCase();
PrototypeArraymethods var a = [3, 5, 6, 1, 20]; a.without(3); // [5, 6, 1, 20] [3, 5, 6, 1, 20].without(20, 6); // [3, 5, 1] nums = [3, 5, 6, 1, 20]; nums.reverse(false); // nums is [3, 5, 6, 1, 20] but returns [20, 1, 6, 5, 3] nums.reverse(); // nums is [20, 1, 6, 5, 3] a.indexOf(1) //returns 3
PrototypeNumbermethods Math.abs(-5); //-> 5 ; (-5).abs() ; //-> 5 Math.ceil(4.1); //-> 5 (4.1).ceil(); //-> 5 (-4.1).ceil() ; //-> -4 Math.floor(4.6); //-> 4 (4.6).floor(); //-> 4 (-4.1).floor(); //-> -5 (4.5).round(); //-> 5 (4.49).round(); //-> 4 (-4.5).round(); //-> -4 128.toColorPart(); // -> '70‘ 10.toColorPart(); // -> '0a'
PrototypeString methods • blank(): Check if the string is blank, meaning either empty or containing only whitespace • endsWith(): Checks if the string ends with substring • times(count): Concatenates the string count times • include(substring): Check if the string contains a substring. • truncate(length), truncate(length, suffix ): Truncates a string to the given length and appends a suffix to it (indicating that it is only an excerpt). • strip() Strips all leading and trailing whitespace from a string. • toArray() Splits the string character-by-character and returns an array with the result. • truncate(30, '...’): Truncates a string to the given length and appends a suffix to it (indicating that it is only an excerpt). var s = "echo "; s = s.times(3); //"echo echoecho "; s = s.strip() ; //"echo echoecho"; if (s.endsWith("ho") && s.include("ec"){ s=s.truncate(10); //"echo ec..."; } var a = s.toArray(); //["e", "c", "h", "o", " ", "e", "c", ". ", ". ", ". "]
Prototype's DOM elementmethods categories: CSS classes, DOM tree traversal/manipulation, events, styles
Prototype's DOM tree traversal methods <body> <div id="father"> <div id="kid"> </div> </div> </body> $('kid').ancestors();//-> [div#father, body, html] //keep in mind that the `body` and `html` elements // will also be included! document.getElementsByTagName('html')[0].ancestors(); // -> [] • up (index) : returns element’s first ancestor (or the index’thancesto)r
Prototype's DOM tree traversal methods <ul> <li id="golden-delicious">Golden Delicious</li> <li id="mutsu">Mutsu</li> <li id="mcintosh“ class="yummy" >McIntosh</li> <li id="ida-red">Ida Red</li> </ul> $('mutsu').siblings(); // -> [li#golden-delicious, li#mcintosh, li#ida-red] $('golden-delicious').next('.yummy'); // -> li#mcintosh
Prototype's DOM tree traversal methods // alter siblings of "main" that do not contain "Sun" var sibs = $("main").siblings(); for (vari = 0; i < sibs.length; i++) { if (sibs[i].innerHTML.indexOf("Sun") < 0) { sibs[i].innerHTML += " Sunshine"; } }
Prototype's methods for selecting DOM elements • Prototype adds methods to the document object (and all DOM element objects) for selecting groups of elements: <ul id="fruits"> <li id="apples">apples <ul> <li id="golden-delicious">Golden Delicious</li> <li id="mutsu" class="yummy">Mutsu</li> <li id="mcintosh" class="yummy">McIntosh</li> <li id="ida-red">Ida Red</li> </ul> </li> <li id="exotic" class="yummy">exotic fruits <ul> <li id="kiwi">kiwi</li> <li id="granadilla">granadilla</li> </ul> </li> </ul> $('fruits').getElementsByClassName('yummy'); // -> [li#mutsu, li#mcintosh, li#exotic]
The $$ function vararrayName = $$("CSS selector"); • $$ returns an array of DOM elements that match the given CSS selector • like $ but returns an array instead of a single DOM object • a shorthand for document.select and for document.getElementsByTagName • useful for applying an operation each one of a set of elements $$('div'); //-> all DIVs in the document. Same as // document.getElementsByTagName('div')! $$('#contents'); // -> same as $('contents'), only it returns an array anyway (even though IDs must be unique within a document). $$('li.faux'); // -> all LI elements with class 'faux‘ $$('#navbar a', '#sidebar a'); // -> all links within the elements of ID "navbar" or "sidebar"
The $$ function and each element // hide all "announcement" paragraphs in the "news" section var paragraphs = $$("div#newsp.announcement"); for (vari = 0; i < paragraphs.length; i++) { paragraphs[i].hide(); } • often instead of getting the results of $$ and looping over them, you call each on the list of results and pass a function to call on each element that was matched • can pass your own function (which takes each matching element as a parameter) or one of the existing Prototype Element methods • Each is very useful but in this course we favor the classic approach of fetching elements and looping over them. // hide all "announcement" paragraphs in the "news" section $$("div#newsp.announcement").each(function(e) { e.hide();}); // hide all "announcement" paragraphs in the "news" section $$("div#newsp.announcement").each(Element.hide);
The $$ function versus select • select takes an arbitrary number of CSS selectors (strings) and returns an array of extended descendants of element that match any of them. • This method is very similar to $$() but can be used within the context of one element, rather than the whole document. <ul id="fruits"> <li id="apples"> <h3 title="yummy!">Apples</h3> <ul id="list-of-apples"> <li id="golden-delicious" title="yummy!" >Golden Delicious</li> <li id="mutsu" title="yummy!">Mutsu</li> <li id="mcintosh">McIntosh</li> <li id="ida-red">Ida Red</li> </ul> <p id="saying">An apple a day keeps the doctor away.</p> </li> </ul> $('apples').select('[title="yummy!"]'); // -> [h3, li#golden-delicious, li#mutsu] $('apples').select( 'p#saying', 'li[title="yummy!"]'); // -> [li#golden-delicious, li#mutsu, p#saying]
Common $$ issues • many students forget to write . or # in front of a class or id // get all buttons with a class of "control" vargameButtons = $$("control"); vargameButtons = $$(".control"); • $$ returns an array, not a single element; must loop over the results // set all buttons with a class of "control" to have red text $$(".control").style.color = "red"; vargameButtons = $$(".control"); for (vari = 0; i < gameButtons.length; i++) { gameButtons[i].style.color = "red"; } • Q: Can I still select a group of elements using $$ even if my CSS file doesn't have any style rule for that same group? • (A: Yes!)
Removing a node from the page • each DOM object has a removeChild method to remove its children from the page • Prototype adds a remove method for a node to remove itself • Completely removes element from the document and returns it. // Before: <ul> <li id="golden-delicious">Golden Delicious</li> <li id="mutsu">Mutsu</li> <li id="mcintosh">McIntosh</li> <li id="ida-red">Ida Red</li> </ul> $('mutsu').remove(); // -> HTMLElement (and removes li#mutsu) // After: <ul> <li id="golden-delicious">Golden Delicious</li> <li id="mcintosh">McIntosh</li> <li id="ida-red">Ida Red</li> </ul>
Removing a node from the page • What does this code do? function slideClick() { var bullets = document.getElementsByTagName("li"); for (vari = 0; i < bullets.length; i++) { if (bullets[i].innerHTML.indexOf("children") >= 0) { bullets[i].remove(); } } }
Problems with reading/changing styles HTML <button id="clickme">CLICK ME</button> window.onload = function() { $("clickme").onclick = biggerFont; }; function biggerFont() { var size = parseInt($("clickme").style.fontSize); //?? May work // but may not size += 4; $("clickMe").style.fontSize = size + "pt"; } • styleproperty lets you set any CSS style for an element • problem: you cannot (usually) read existing styles with it • if you try to read an element's styles using .style.propertyName, it will often return an empty string) JS
Accessing styles in Prototype • getStylefunction added to DOM object allows accessing existing styles <button id="clickme">CLICK ME</button> window.onload = function() { $("clickme").onclick = biggerFont; }; function biggerFont() { varsize = parseInt($("clickme").getStyle("font-size")); $("clickme").style.fontSize = (size + 4) + "pt"; } • the below example computes e.g. "20pt" + 4+ "pt" , and would evaluate to "20pt4pt“ varsize = $("clickme").getStyle("font-size"); // bad! $("clickme").style.fontSize = (size + 4) + "pt";
Setting CSS classes in Prototype • addClassName, removeClassName, hasClassName, classNamesmanipulate CSS classes • similar to existing className DOM property, but don't have to manually split by spaces <div id="mutsu" class="apple fruit food"></div> $('mutsu').hasClassName('fruit'); // -> true $('mutsu').hasClassName('vegetable'); // -> false $('mutsu').addClassName('vegetable') $('mutsu').className// -> 'apple fruit food vegetable' $('mutsu').classNames() // -> ['apple', 'fruit', 'food', 'vegetable'] function highlightField() { // turn text yellow and make it bigger if (!$("text").hasClassName("invalid")) { $("text").addClassName("highlight"); } }
Prototype form shortcuts- the $F function • $F function returns the value of a form control with the given id • $F("controlID") var name = $F("id"); // equivalent to $("id").getValue();
Prototype form methods • Prototype adds the following methods to form controls' DOM objects: if ($F("username").length < 4) { $("username").clear(); $("login").disable(); }