Sei sulla pagina 1di 34

Javascript

Javascript is an increasingly important language since it runs inside the ubiquitous web browser. This page is a very quick overview for the Attention Deficit programmer. No extra fluff. 1. Adding Javascript To Web Pages How do we get JavaScript onto a web page? You can use several different methods of placing javascript in your pages. 1. You can directly add a script element inside the body of page. For example, to add the "last updated line" to your pages, In your page text, add the following:
<p>blah, blah, blah, blah, blah.</p> <script type="text/javascript" > <!-- Hiding from old browsers document.write("Last Updated:" + document.lastModified); document.close(); // --> </script> <p>yada, yada, yada.</p>

(Note: the first comment, "<--" hides the content of the script from browsers that don't understand javascript. The "// -->" finishes the comment. The "//" tells javascript that this is a comment so javascript doesn't try to interpret the "-->". If your audience has much older browsers, you should put this comments inside your javascript. If most of your audience has newer browsers, the comments can be omitted. For brevity, in most examples here the comments are not shown. ) The above code will look like this on Javascript enabled browsers:

Last Updated:01/22/2012 21:36:39

2. Javascript can also be placed inside the <head> element Functions and global variables typically reside inside the <head> element.
<head> <title>Default Test Page</title> <script type="text/javascript"> var myVar = ""; function timer(){setTimeout('restart()',10);} document.onload=timer(); </script> </head>

3. Javascript can be referenced from a separate file

Javascript may also a placed in a separate file on the server and referenced from an HTML page. (Don't use the shorthand ending "<script ... />" - some browsers do not understand the self-closing tag on the "script" element). These are typically placed in the <head> element.
<script type="text/javascript" SRC="myStuff.js"></script>

2. Some Language Basics 1. Comments Single line comments are made with "//", multiple line comment start with "/*" and end with "*/".
//I'm a single line comment /* I'm a multiline comment */ var i=0; //I'm half a comment

2. Global and Local Variables Variables defined outside of a function are global variables. These may be accessed from any function. They live only as long as the page. Local variables only live inside a function and should also be prefaced with "var".
var imAGlobalVar = 10; function foo() { var imALocalVar = 11; }

3. const For variables that don't change [sic], we can use the "const" key word.
const taxRate = 0.0825;

4. String manipulations Javascript has the standard compliment of string methods. Here are a few of the more interesting. Function replace(regExp,replacement) replaces a regular expression with a string. Modifiers g - replace all occurances (global) i - ignore case match(regExp) returns an array of matching strings Examples "ababAbab".replace(/a/,"c") ==> cbabAbab "ababAbab".replace(/a/g,"c") ==> cbcbAbcb "ababAbab".replace(/a/gi,"c") ==> cbcbcbcb "ababAbab".match(/a/) ==> a "ababAbab".match(/a/g) ==> a,a,a "ababAbab".match(/a/gi) ==> a,a,A,a

search(regExp) finds the first occurance of the regExp in a string, or null if not found Hints: \s is a space \b word boundary * zero or more . a character slice(start, [offset]) Similar to substring, except the second argument is an offset from the end of the string. If no second argument is given, the end of the string is assumed. split(delimiter) returns an array of strings split by the delimeter toLowerCase(),toUpperCase() returns a string with changed case

"ababAbab".search(/b/) ==> 1 "ababAbab".search(/ab/) ==> 0 "ababAbab ababAbab".search(/b\s/) ==> 7

"ababAbaba,".slice(3,-1) ==> bAbaba "ababAbaba,".slice(3) ==> bAbaba,

"Gamma;Helm;Johnson".split(";") ==> Gamma,Helm,Johnson "Gamma;Helm;Johnson".toUpperCase() ==> GAMMA;HELM;JOHNSON

5. Example of using Regular Expressions for syntax checking


6. ... 7. var re = new RegExp("^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$"); 8. var text = myWidget.value; 9. var OK = re.test(text); 10. if( ! OK ) { 11. alert("The extra parameters need some work.\r\n Should be something like: \"&a=1&c=4\""); 12. } 13.

3. Javascript Functions 1. Function Arguments Javascript functions are very flexible on the number of arguments. When you invoke the function you can supply the expected number of arguments or fewer, or more. The "document.write()" method writes text directly into the page being displayed.
<script type="text/javascript"><!-function movie(title, director) { document.write("<br />Movie:<br />title: "+title); document.write("<br />director: "+director); } movie("Aliens","Cameron"); movie("Fellowship of the Ring"); movie("Narni","Andrew Adamson","Disney","C.S. Lewis"); // --> </script>

This produces Movie: title: Aliens director: Cameron

Movie: title: Fellowship of the Ring director: undefined Movie: title: Narni director: Andrew Adamson If you do not supply all the arguments, javascript doesn't care. It just doesn't define those variables and moves on with its life. Likewise, if you supply too many variables, javascript won't hold it against you. You might ask, 'How do I access the exra variables passed in?'. The function has a built-in array "arguments" which allows you to access any extra arguments.
<script type="text/javascript"><!-function movie2(title, director) { document.write("<p><u>Movie:</u>"); document.write("<br />(Arguments passed in:"+arguments.length+")"); document.write("<br /><b>title:</b> "+title); if(arguments.length > 1) { document.write("<br /><b>director:</b> "+director); } if(arguments.length > 2) { document.write("<br /><b>Based on the book by:</b> "+arguments[2]); } document.write("</p>"); } movie2("Aliens","Cameron"); movie2("Fellowship of the Ring"); movie2("Narni","Andrew Adamson","C.S. Lewis"); // --> </script>

This produces Movie: (Arguments passed in:2) title: Aliens director: Cameron Movie: (Arguments passed in:1) title: Fellowship of the Ring Movie: (Arguments passed in:3) title: Narni director: Andrew Adamson Based on the book by: C.S. Lewis

2. Anonymous Function You can create anonymous functions when you really don't need the overhead of creating a name.
<form action="#"> <input type="button" value="Click Me" id="anonbutton" /> </form> <script type="text/javascript"> var anonbutton = document.getElementById("anonbutton"); anonbutton.onclick = function() { alert("anonymous function called."); } </script>

This produces 4. Javascript Objects To understand objects it helps to realize that JavaScript objects are really associative arrays at heart. You can add new fields and methods just by adding the name and value to the objects associative array. 1. Creating an object Objects can be created in many ways. One way is to create the object and add the fields directly.
<script type="text/javascript"> var myMovie = new Object(); myMovie.title = "Aliens"; myMovie.director = "James Cameron"; document.write("movie: title is \""+myMovie.title+"\""); </script>

This produces movie: title is "Aliens" To create an object you write a method with the name of your object and invoke the method with "new".
<script type="text/javascript"> function movie(title, director) { this.title = title; this.director = director; } var aliens = new movie("Aliens","Cameron"); document.write("aliens:"+aliens.toString()); </script>

This produces aliens:[object Object]

You can also use an abbreviated format for creating fields using a ":" to separate the name of the field from its value. This is equivalent to the above code using "this.".
<script type="text/javascript"> function movie(title, director) { title : title; director : director; } var aliens = new movie("Aliens","Cameron"); document.write("aliens:"+aliens.toString()); </script>

This produces aliens:[object Object] This is true, but not very satisfying. 2. Associating functions with objects. Let's now create a custom "toString()" method for our movie object. We can embed the function directly in the object like this.
<script type="text/javascript"> function movie(title, director) { this.title = title; this.director = director; this.toString = function movieToString() { return("title: "+this.title+" director: "+this.director); } } var narnia = new movie("Narni","Andrew Adamson"); document.write(narnia.toString()); </script>

This produces title: Narni director: Andrew Adamson Or we can use a previously defined function and assign it to a variable. Note that the name of the function is not followed by parenthesis, otherwise it would just execute the function and stuff the returned value into the variable.
<script type="text/javascript"> function movieToString() { return("title: "+this.title+" director: "+this.director); } function movie(title, director) { this.title = title; this.director = director; this.toString = movieToString; //assign function to this method pointer } var aliens = new movie("Aliens","Cameron"); document.write(aliens.toString()); </script>

This produces title: Aliens director: Cameron 3. Prototypes Objects have "prototypes" from which they may inherit fields and functions.
<script type="text/javascript"> <!-function movieToString() { return("title: "+this.title+" director: "+this.director); } function movie(title, director) { this.title = title; this.director = director || "unknown"; //if null assign to "unknown" this.toString = movieToString; //assign function to this method pointer } var officeSpace = new movie("OfficeSpace"); var narnia = new movie("Narnia","Andrew Adamson"); movie.prototype.isComedy = false; //add a field to the movie's prototype document.write(narnia.toString()); document.write("<br />Narnia a comedy? "+narnia.isComedy); officeSpace.isComedy = true; //override the default just for this object document.write("<br />Office Space a comedy? "+officeSpace.isComedy); //--> </script>

This produces title: Narnia director: Andrew Adamson Narnia a comedy? false Office Space a comedy? true 5. Javascript Flow of Control Javascript offers many ways to alter the flow of control. 1. if
2. <script type="text/javascript"><!-3. var balance = 400.0; 4. if(balance < 0.0) { 5. status = "bankrupt"; 6. } else if(balance < 100.0) { 7. status = "ok"; 8. } else { 9. status = "rich"; 10. } 11. document.write("customer is "+status); 12. //--> 13. </script> 14.

This produces customer is rich 15. What is Truth? "What is truth? Is mine the same as yours?" - obscure Roman governor To use control structures you need boolean operators. Unlike java and c#, javascript has a very lenient policy on what evaluates to true or false. object numbers string object property true any non-zero number any string with content exists is already defined false zero empty, "" does not exist is not defined

16. A loop example:


17. 18. 19. 20. 21. 22. function Timer() { for(i = 1; i <= 300; i++) { MoveIt(); } }

23. Exiting a loop When a "break" statement is encountered, we jump out of the loop.
<script type="text/javascript"><!-for(var i=0; i<100; i++) { document.write(i); if(i > 5) { break; } } //--> </script>

This produces 0123456 24. "continue" - kinda break The continue statement stops execution, but returns control back to the loop.
<script type="text/javascript"><!-for(var i=0; i<10; i++) { document.write("."); if(i > 5) { continue; } document.write(i); } //--> </script>

This produces .0.1.2.3.4.5.... 25. While Execution loops inside the while until its condition is false...
<script type="text/javascript"><!-var total = 1; while(total < 100) { document.write(total+","); total = total * 2; } //--> </script>

This produces 1,2,4,8,16,32,64, or until a break is hit


<script type="text/javascript"><!-var total = 1; while(true) { document.write(total+","); total = total * 2; if(total > 100) { break; } } //--> </script>

This produces 1,2,4,8,16,32,64, 26. for-in loop Javascript has a curious, but helpful structure the for-in loop. This loops over all the properties of an object.
<p id="testme">I am a test paragraph.</p> <script type="text/javascript"><!-var obj = document.getElementById("testme"); for(var j in obj) { document.write("<br />"+j+" is "+obj[j]); } //--> </script>

This produces I am a test paragraph.

querySelector is function querySelector() { [native code] } querySelectorAll is function querySelectorAll() { [native code] } scrollTop is 0 scrollLeft is 0 scrollHeight is 16 scrollWidth is 600 clientTop is 0 clientLeft is 0 clientHeight is 16 clientWidth is 600 firstElementChild is null lastElementChild is null previousElementSibling is null nextElementSibling is [object HTMLScriptElement] childElementCount is 0 children is [object HTMLCollection] classList is setCapture is function setCapture() { [native code] } getElementsByClassName is function getElementsByClassName() { [native code] } getClientRects is function getClientRects() { [native code] } getBoundingClientRect is function getBoundingClientRect() { [native code] } releaseCapture is function releaseCapture() { [native code] } mozMatchesSelector is function mozMatchesSelector() { [native code] } addEventListener is function addEventListener() { [native code] } removeEventListener is function removeEventListener() { [native code] } dispatchEvent is function dispatchEvent() { [native code] } style is [object CSSStyleDeclaration] contentEditable is inherit isContentEditable is false offsetParent is [object HTMLBodyElement] innerHTML is I am a test paragraph. offsetLeft is 277 offsetTop is 9467 offsetHeight is 16 offsetWidth is 600 scrollIntoView is function scrollIntoView() { [native code] } id is testme title is lang is dir is className is accessKey is accessKeyLabel is Alt+Shift+ blur is function blur() { [native code] } focus is function focus() { [native code] } click is function click() { [native code] } tagName is P removeAttributeNS is function removeAttributeNS() { [native code] } removeAttribute is function removeAttribute() { [native code] } getAttribute is function getAttribute() { [native code] } getElementsByTagName is function getElementsByTagName() { [native code] }

setAttribute is function setAttribute() { [native code] } getElementsByTagNameNS is function getElementsByTagNameNS() { [native code] } hasAttributeNS is function hasAttributeNS() { [native code] } setAttributeNS is function setAttributeNS() { [native code] } hasAttribute is function hasAttribute() { [native code] } getAttributeNS is function getAttributeNS() { [native code] } nodeName is P nodeValue is null nodeType is 1 parentNode is [object HTMLDivElement] parentElement is [object HTMLDivElement] childNodes is [object NodeList] firstChild is [object Text] lastChild is [object Text] previousSibling is [object Text] nextSibling is [object Text] attributes is [object NamedNodeMap] ownerDocument is [object HTMLDocument] namespaceURI is http://www.w3.org/1999/xhtml prefix is null localName is p baseURI is http://www.fincher.org/tips/Languages/javascript.shtml textContent is I am a test paragraph. setUserData is function setUserData() { [native code] } getUserData is function getUserData() { [native code] } insertBefore is function insertBefore() { [native code] } replaceChild is function replaceChild() { [native code] } removeChild is function removeChild() { [native code] } appendChild is function appendChild() { [native code] } hasChildNodes is function hasChildNodes() { [native code] } cloneNode is function cloneNode() { [native code] } normalize is function normalize() { [native code] } isSupported is function isSupported() { [native code] } hasAttributes is function hasAttributes() { [native code] } compareDocumentPosition is function compareDocumentPosition() { [native code] } isSameNode is function isSameNode() { [native code] } lookupPrefix is function lookupPrefix() { [native code] } isDefaultNamespace is function isDefaultNamespace() { [native code] } lookupNamespaceURI is function lookupNamespaceURI() { [native code] } isEqualNode is function isEqualNode() { [native code] } contains is function contains() { [native code] } getAttributeNode is function getAttributeNode() { [native code] } setAttributeNode is function setAttributeNode() { [native code] } removeAttributeNode is function removeAttributeNode() { [native code] } getAttributeNodeNS is function getAttributeNodeNS() { [native code] } setAttributeNodeNS is function setAttributeNodeNS() { [native code] } align is ELEMENT_NODE is 1 ATTRIBUTE_NODE is 2 TEXT_NODE is 3 CDATA_SECTION_NODE is 4

ENTITY_REFERENCE_NODE is 5 ENTITY_NODE is 6 PROCESSING_INSTRUCTION_NODE is 7 COMMENT_NODE is 8 DOCUMENT_NODE is 9 DOCUMENT_TYPE_NODE is 10 DOCUMENT_FRAGMENT_NODE is 11 NOTATION_NODE is 12 DOCUMENT_POSITION_DISCONNECTED is 1 DOCUMENT_POSITION_PRECEDING is 2 DOCUMENT_POSITION_FOLLOWING is 4 DOCUMENT_POSITION_CONTAINS is 8 DOCUMENT_POSITION_CONTAINED_BY is 16 DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC is 32 hidden is false tabIndex is -1 draggable is false insertAdjacentHTML is function insertAdjacentHTML() { [native code] } contextMenu is null spellcheck is false dataset is [object DOMStringMap] mozRequestFullScreen is function mozRequestFullScreen() { [native code] } onabort is null onblur is null oncanplay is null oncanplaythrough is null onchange is null onclick is null oncontextmenu is null ondblclick is null ondrag is null ondragend is null ondragenter is null ondragleave is null ondragover is null ondragstart is null ondrop is null ondurationchange is null onemptied is null onended is null onerror is null onfocus is null oninput is null oninvalid is null onkeydown is null onkeypress is null onkeyup is null onload is null onloadeddata is null onloadedmetadata is null onloadstart is null onmousedown is null onmousemove is null

onmouseout is null onmouseover is null onmouseup is null onmozfullscreenchange is null onpause is null onplay is null onplaying is null onprogress is null onratechange is null onreset is null onscroll is null onseeked is null onseeking is null onselect is null onshow is null onstalled is null onsubmit is null onsuspend is null ontimeupdate is null onvolumechange is null onwaiting is null oncopy is null oncut is null onpaste is null onbeforescriptexecute is null onafterscriptexecute is null 27. GOTOs considered harmful (mostly) OK, we shouldn't use GOTOs, but every once in a while [sic] they are handy. Javascript has labeled statements which can be used with break and continue.
<script type="text/javascript"><!-for(var i=0; i < 2; i++) { outerloop: for(var j=0; j < 10; j++) { if(j > 3) { break outerloop; } document.write(" "+i+j+", "); } } //--> </script>

This produces 00, 01, 02, 03, 10, 11, 12, 13, 28. switch Like most modern languages javascript has a switch statement. The expression in the switch can be a number or a string.
<script type="text/javascript"><!--

var flavor = "vanilla"; switch(flavor) { case "chocolate": document.write("I like chocolate too."); break; case "strawberry": document.write("Strawberry is for sissies."); break; case "vanilla": document.write("Vanilla is boring."); //no break statement so control will continue to the statement below default: document.write("Ice cream is cool."); } //--> </script>

This produces Vanilla is boring.Ice cream is cool. 29. Simulate a foreach loop (or jQuery's "$.each()" function) Many functional languages have a method on a collection that given a function will invoke that function on each member of the collection. We can simulate that like this:
myArray = new Array(1,2,3,4,5,6,7,8,9,10,11,12,16,20,32); for(i=0; i<myArray.length; i++) { val = myArray[i] // do something with "val" }

30. try-catch-finally Javascript's error handling is very similiar to java and c#.
<script type="text/javascript"><!-try { obj = null; null.to_s(); } catch (e) { document.write("Exception: "+e); } finally { document.write("<br />Bye."); } //--> </script>

This produces Exception: TypeError: null has no properties Bye. 31. throw

When throwing an exception you can create an Error object or just throw a string.
<script type="text/javascript"><!-var i = 12; try { if(i < 30) { throw "I was really expecting something over 30"; } } catch(e) { document.write("Exception: "+e); } //--> </script>

This produces Exception: I was really expecting something over 30 32. How to set a method to execute in the background later This is asynchronous, so it will let the main thread continue and execute its function in 2 seconds.
function timer(){ setTimeout('myMethod()',2000); }

33. To execute a method repeatedly This will execute 'myMethod' every two seconds.
var myId; ... myId = setInterval('myMethod()',2000);

To stop the method from repeating


clearInterval(myId);

6. Working with HTML Elements 1. Buttons The most basic and ancient use of buttons are the "submit" and "clear", which appear slightly before the Pleistocene period. After pressing the "GO!" button notice the name in the URL.
<form name="buttonsGalore" method="get"> Your Name: <input type="text" name="mytext" /> <br /> <input type="submit" value="GO!" /> <input type="reset" value="Clear All" /> </form>

Try It: Your Name:

Another useful approach is to set the "type" to "button" and use the "onclick" event.
function displayHero(button) { alert("Your hero is \""+button.value+"\"."); } </script> <form name="buttonsGalore" method="get"> <fieldset style="margin: 1em; text-align: center; padding: 1em;"> <legend>Select a Hero</legend> <input type="button" value="Agamemnon" onclick="displayHero(this)" /> <input type="button" value="Achilles" onclick="displayHero(this)" /> <input type="button" value="Hector" onclick="displayHero(this)" /> </fieldset> </form>

Try It: Select a Hero (Also notice I have tried to confuse you, the gentle reader, by springing the new "fieldset" element and its child, "legend". "Fieldset" provides a logical grouping of controls with a border; and the meaning of "legend" is left to the student as an exercise.) Note also the argument to the onclick method, "this", which is a pointer to the element that was invoked. Very handy. 2. Fun with "Select" lists 1. To remove an item from a list set it to null
2. mySelectObject.options[3] = null;

3. To truncate a list set its length to the maximum size you desire
4. mySelectObject.length = 2; 6. mySelectObject.length = 0;

5. To delete all options in a select object set the length to 0. 3. Accessing Elements To do something interesting with HTML elements, we must first be able to uniquely identify which element we want. In the example
<body> <form> <input type="button" id="useless" name="mybutton" value="doNothing" /> </form> </body>

We can use the "getElementById" method (which is generally preferred)


document.getElementById("useless").style.color = "red";

or we can use the older hierarchical navigation method,


document.forms[0].mybutton.style.color = "blue";

Notice that this uses the "name" attribute of the element to locate it. You can also use the "elements" array of the form and address the element by its name:
document.forms[0].elements["mybutton"].style.color = "red";

4. Example of Accessing Elements in a DOM.

5. <script type="text/javascript" > 6. function showStatus() { 7. var selectWidget = document.forms.beerForm.elements["beer"]; 8. var myValue = selectWidget.options[selectWidget.selectedIndex].value; 9. alert('You drank a \"'+ myValue +"\""); 10. return true; 11. } 12. </script> 13. 14. <form name="beerForm"> 15. <select name="beer"> 16. <option selected="selected">Select Beer</option> 17. <option>Heineken</option> 18. <option>Amstel Light</option> 19. <option>Corona</option> 20. <option>Corona Light</option> 21. <option>Tecate</option> 22. </select> 23. 24. <input type="button" name="submitbutton" value="Drink" 25. onclick="showStatus()" /> 26. </form> 27. 28. 29.

Try It: 30. To get the contents of an input box. Use the "value" property.
var myValue = window.document.getElementById("MyTextBox").value;

31. To determine the state of a checkbox


32. var checkedP = window.document.getElementById("myCheckBox").checked; <script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script>

33. To set the focus in an element


34. 35. 36. 37. 38. 39. 40. 41. 43. 45. 46. 47.

42. To put a "close window" link on a page.


<a href='javascript:window.close()' class='mainnav'> Close </a> //select all input tags function SelectAll() { var checkboxes = document.getElementsByTagName("input");

44. To set all checkboxes to true

48. 49.

for(i=0;i<checkboxes.length;i++) { if(checkboxes.item(i).attributes["type"].value == "checkbox") { 50. checkboxes.item(i).checked = true; 51. } 52. } 53. }

54. Selecting an element by id and swapping an image


55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. ... <script language="JavaScript" type="text/javascript" > function setBeerIcon() { var beerIcon = document.getElementById("beerIcon"); beerIcon.src = "images/"+getSelectValue("beer")+".jpg"; } </script> ... <img border="0" src="" id="brandIcon" alt="brand" />

<select name="beer" id="beer" onChange="setButton();setBeerIcon();"> 70. <option value="--Select--">Select beer</option> 71. <option value="heineken">heineken</option> 72. <option value="sol">sol</option> 73. <option value="amstellight">amstellight</option> 74. <option value="coronalight">coronalight</option> 75. <option value="coronaextra">coronaextra</option> 76. <option value=""></option> 77. </select> 78. 79.

80. To find the selected radio button immediately using the 'this' variable.
81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. <script> function favAnimal(button) { alert('You like '+button.value+'s.'); } </script> <input type="radio" name="marsupial" value="kangaroo" onchange="favAnimal(this)">Kangaroo <br /><input type="radio" name="marsupial" value="Opossum" onchange="favAnimal(this)">Opossum <br /><input type="radio" name="marsupial" value="Tasmanian Tiger" 92. onchange="favAnimal(this)">Tasmanian Tiger

Try it here: Kangaroo Opossum Tasmanian Tiger 93. To find radio button selection when a form is submitted
94. 95. 96. 97. 98. <script type="text/javascript"> function findButton() { var myForm = document.forms.animalForm; var i; for(i=0;i<myForm.marsupial.length; i++) {

99. if(myForm.marsupial[i].checked) { 100. break; 101. } 102. } 103. alert("You selected \""+myForm.marsupial[i].value+"\"."); 104. } 105. </script> 106. <form name="animalForm"> 107. <input type="radio" name="marsupial" value="kangaroo" />Kangaroo 108. <br /><input type="radio" name="marsupial" value="Opossum" />Opossum 109. <br /><input type="radio" name="marsupial" value="Tasmanian Tiger" />Tasmanian Tiger 110. <br /> 111. <input type="button" name="GO" value="GO" onclick="findButton()" /> 112. </form> 113.

Try it here: Kangaroo Opossum Tasmanian Tiger 114.


115.

To disable an HTML object

document.getElementById("myObject").disabled = true;

7. Our friend, the schizophrenic anchor tag Really the anchor tag, <a>, has two distinct personalities: one with the 'href' attribute and one without. With 'href' it is a powerful linking machine, without the 'href' its a trivial marker to find your way into the middle of a web page. 1. Simple 'href' usage will whisk the user away to the location when clicked
2. <a href="http://www.fincher.org/History/World.shtml">History is fun!</a>

Try it:History is fun! 3. Relative links You can omit the "http" only if link is relative to your current page, for example:
<a href="../../History/World.shtml">History is relatively fun!</a>

Try it:History is relatively fun! 4. The Pseudo-URL href To have an element invoke a javascript on selection, instead of going to a new URL:
<script type="text/javascript"> function pseudoHitMe() { alert("Ouch!");

} </script> <a href="javascript:pseudoHitMe()">hit me</a>

Try It: hit me 5. The anchor tag as a bookmark This is the Sybil part, when the anchor tag has no 'href' attribute, it is used as a bookmark.
<a name="bookmark" />

Try it:Go to bookmark! This will place this section at the top of your browser window. 8. Working with Dynamic HTML Elements Writing content to the screen with "document.write()" only works when a page is flowing into the browser. Once the page is loaded you cannot use "document.write()". Instead you need to change the element dynamically. 1. Dynamic HTML Elements
2. <script type="text/javascript"> 3. function showCard() { 4. var message = document.getElementById("CCN").value; 5. var element = document.getElementById("mycreditcardnumber"); 6. element.textContent = message; //for Firefox 7. element.innerHTML = message; //for IE (why can't we all just get along?) 8. return true; 9. } 10. </script> 11. <form name="dynamic" method="get"> 12. <span>Enter Your Credit Card Number:</span> 13. <input type="text" id="CCN" name="CCN" value="CCN" /> 14. <input type="button" value="submit" onclick="showCard()" /> 15. </form> 16. 17. <p>Verify your Credit Card Number: 18. <span id="mycreditcardnumber">0000-00-0000-00 </span> 19. </p> 20.

This produces Enter Your Credit Card Number:

Verify your Credit Card Number: 0000-00-0000-00 21. Adding new elements dynamically.
22. 23. 24. 25. 26. 27. 28. <script type="text/javascript"> function addItem() { var myitem = document.getElementById("ItemToAdd").value; var mylistItems = document.getElementById("mylist"); var newP = document.createElement("li"); var textNode = document.createTextNode(myitem); newP.appendChild(textNode);

29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40.

document.getElementById("mylist").appendChild(newP); return false; } </script> <form onsubmit="return addItem()" action="#"> <span>Grocery Items:</span> <input type="text" id="ItemToAdd" value="Milk" /> <input type="button" value="Add" onclick="addItem()" /> </form> <span>Grocery List:</span> <ol id="mylist"></ol>

This produces Grocery Items: Grocery List: 41. Example using search engines Click on the first item going to fincher.org from this search. Notice the welcome box and highlighting of searched text? A good example of using javascript to manipulate the DOM. 42. Cheating with ".innerText" This non-standard, though quite handy property can be used to set the contents of an element.
var myStatus = document.getElementById("mystatus"); myStatus.innerHTML = "<b>Howdy!</b>";

43. Precaching images This example should prefetch the image - works in most browsers, but not all that I tested:
var home = new Image(100,100); home.src = "images/HomeImage.jpg";

9. Working with Forms 1. You can access forms in at least four ways:
2. 3. 4. 5. document.forms[0] //if its the first form on a page document.myformname document.forms["myformname"] document.forms.myformname

Here's an example of using all four


<form name="cupid" action="#"> <input type="text" value="valentine" /> </form> <script type="text/javascript"><!-document.write("<br />name is "+document.forms[0].name)

document.write("<br />name is "+document.cupid.name) document.write("<br />name is "+document.forms["cupid"].name) document.write("<br />name is "+document.forms.cupid.name) --> </script>

This produces

name is name is cupid name is cupid name is cupid 6. You can dynamically add an "onclick" event to a button.
7. <form name="form2" action="#"> 8. <input type="submit" name="NEXT" value="Next " /><br /> 9. </form> 10. 11. <script type="text/javascript" ><!-12. function validate() { 13. alert("validated."); 14. document.forms["form2"].style.background="red" 15. 16. return false; 17. } 18. document.forms["form2"].elements["NEXT"].onclick=validate; 19. //--> </script>

This produces

20. Example of counting the number of checks in a form


21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. <form name="form3" action="#"> <div>Who are your favorite browncoats? apply to you: Please select all that

<input type="checkbox" name="Zoe" />Zoe <input type="checkbox" name="Mal" />Mal <input type="checkbox" name="Inara" />Inara <input type="checkbox" name="Kaylee" /> Kaylee <input type="checkbox" name="River" />River <input type="checkbox" name="Simon" /> Simon </div> <input type="submit" name="NEXT" value="GO! " /> </form> <script type="text/javascript" ><!-//returns how many checkboxes in the form are checked function howManyChecks(form) { var selections = 0; for (var i=0; i<form.length; i++) { var theElement = form.elements[i]; if(theElement.type == "checkbox") {

41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59.

} } return selections

if(theElement.checked == true) { selections++ }

} function validate() { var num = howManyChecks(document.forms["form3"]) if( num == 0) { alert("Please make a selection."); } else { alert("Number of favorite characters: "+num) } return false; } document.forms["form3"].elements["NEXT"].onclick=validate; //--> </script>

This produces Who are your favorite browncoats? Please select all that apply to you: Mal Inara Kaylee River Simon Zoe

10. Communicating with the User 1. To have the status line update when the mouse goes over a link (The support of the status line is sporadic).
2. <a href="javascript.shtml" 3. onmouseover="window.status='Hi There!';return true" 4. onmouseout="window.status='';return true">Look at the Status bar</a>

Look at the Status bar as your cursor goes over the link. 5. To create a popup warning box try it: 7. To create a confirmation box
8. confirm("Do you really want to launch the missile?"); 6. alert('Warning: Please enter an integer between 0 and 100.');

try it: 9. To create an input box


10. prompt("What is your temperature?");

try it: 11. To open a window with no toolbar, but with the location object.
12. 13. 14. window.open("http://www.fincher.org/Misc/Pennies","Pennies ","resizable=yes,status=yes,toolbar=yes,location=yes,menubar=yes,s crollbars=yes,width=800,height=400");

try it:

11. Cookies! 1. Setting a cookie with the contents of a textbox Values stored in cookies may not have semicolons, commas, or spaces. You should use the handy "escape()" function to encode the values, and "unescape()" to retrieve them.
//Sets cookie of current value for myTextBox function TextBoxOnchange() { var myBox = window.document.getElementById(myTextBox"); document.cookie = "myTextBox="+ escape(myBox.value) + getExpirationString(); } //return a string like ";expires=Thu, 5 Jan 2006 16:07:52 UTC" function getExpirationString() { var exp = new Date(); var threemonths = exp.getTime()+(120*24*60*60*1000); exp.setTime(threemonths); return ";expires="+exp.toGMTString(); }

(This is called from the event handler in the HTML).


<input name="myTextBox" type="text" id="myTextBox" onchange="javascript:TextBoxOnchange()" />

Try It: Enter some jibberish:

2. Getting values from cookies to set widgets


3. function getCookieData(labelName) { 4. //from Danny Goodman 5. var labelLen = labelName.length; 6. // read cookie property only once for speed 7. var cookieData = document.cookie; 8. var cLen = cookieData.length; 9. var i = 0; 10. var cEnd; 11. while (i < cLen) { 12. var j = i + labelLen; 13. if (cookieData.substring(i,j) == labelName) { 14. cEnd = cookieData.indexOf(";",j); 15. if (cEnd == -1) { 16. cEnd = cookieData.length; 17. } 18. return unescape(cookieData.substring(j+1, cEnd)); 19. } 20. i++; 21. } 22. return ""; 23. } 24. 25. //init() is called from the body tag onload function. 26. function init() { 27. setValueFromCookie("brand"); 28. setValueFromCookie("market");

29. 30. 31. 32. 33. 34.

setValueFromCookie("measure");

function setValueFromCookie(widget) { if( getCookieData(widget) != "") { document.getElementById(widget).value = getCookieData(widget); 35. } 36. } 37. 38. //if you name your cookies the widget ID, you can use the following helper function 39. function setCookie(widget) { 40. document.cookie = widget + "=" + 41. escape(document.getElementById(widget).value) + getExpirationString(); 42. } 43. 44.

12. Sites 1. JavaScript from the w3.org. 2. DOM Viewer - A most wonderful tool for viewing the DOM. It's easy, simple, and incredibly helpful. 3. Javascript reference sites: for snippets of code: javascriptsource.com 13. Event Handlers 1. Events You can add an event handler in the HTML definition of the element like this,
<script type="text/javascript"><!-function hitme() { alert("I've been hit!"); } // --> </script> <input type="button" id="hitme" name="hitme" value="hit me" onclick="hitme()" />

This produces Or, interestingly enough you can just assign the event's name on the object directly with a reference to the method you want to assign.
<input type="button" id="hitme2" name="hitme2" value="hit me2"/> <script type="text/javascript"><!-function hitme2() { alert("I've been hit too!"); } document.getElementById("hitme2").onclick = hitme2; // --> </script>

This produces You can also use an anonymous method like this:
<form> <input type="button" id="hitme3" name="hitme3" value="hit me3"/> <script type="text/javascript"><!--

document.getElementById("hitme3").onclick = function () { alert("I've been hit three!"); } // --> </script> </form>

This produces You can also use the the W3C addEventListener() method, but it does not work in IE yet:
<form> <input type="button" id="hitme4" name="hitme4" value="hit me4"/> <span>(Is W3C standard, but does not yet work in IE)</span> <script type="text/javascript"><!-function hitme4() { alert("I've been hit four!"); } if(document.getElementById("hitme4").addEventListener) { document.getElementById("hitme4").addEventListener("click", hitme4, false); } // --> </script> </form>

This produces (Is W3C standard, but does not yet work in IE) To remove the event listener:
<script type="text/javascript"><!-document.getElementById("hitme4").removeEventListener("click", hitme4, false); // --> </script>

2. Key Events "onkeydown", "onkeypress", "onkeyup" events are supported both in ie and standards-based browsers.
<script type="text/javascript"> function setStatus(name,evt) { evt = (evt) ? evt : ((event) ? event : null); /* ie or standard? */ var charCode = evt.charCode; var status = document.getElementById("keyteststatus"); var text = name +": "+evt.keyCode; status.innerHTML = text; status.textContent = text; } </script> <form> <input type="text" name="keytest" size="1" value="" onkeyup="setStatus('keyup',event)" onkeydown="setStatus('keydown',event)" /> <p id="keyteststatus">status</p> </form>

Try It:

status 3. Execute a function on window completing its loading When this page finishes loading it will execute "MyCoolInitFunc()".
<script type="text/javascript" > window.onload = MyCoolInitFunc </script>

But what if you have multiple methods to load? You could create jumbo method to call all the other methods, or use Simon Willison's elegant method:
// Simon Willison's page load manager method. // http://simon.incutio.com/archive/2004/05/26/addLoadEvent function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } }

14. Using the "style" object. 1. Changing style on an element Between CSS and javascript is a weird symmetry. CSS style rules are layed on top of the DOM. The CSS property names like "font-weight" are transliterated into "myElement.style.fontWeight". The class of an element can be swapped out. For example:
document.getElementById("myText").style.color = "green"; document.getElementById("myText").style.fontSize = "20"; -ordocument.getElementById("myText").className = "regular";

2. To load a style sheet dynamically


3. 4. 5. 6. var el = document.createElement('link'); el.rel = 'stylesheet'; el.type = 'text/css'; el.href = 'http://www.Example.com/...' + 'styles.css'; document.body.appendChild(el);

7. To make elements invisible

Change the "visibility" attribute of the style object associated with your element. Remember that a hidden element still takes up space, use "display" to make the space disappear as well.
if ( x == y) { myElement.style.visibility = 'visible'; } else { myElement.style.visibility = 'hidden'; }

8. To set the cursor to wait. In theory, we should cache the current state of the cursor and then put it back to its original state.
document.body.style.cursor = 'wait'; //do something interesting and time consuming document.body.style.cursor = 'auto';

9. Using style to create motion ... 15. Miscellaneous 1. To reload the current page
2. window.location.reload(true);

3. To force a page to redirect to another page

4. <script language="JavaScript" type="text/javascript" ><!-5. location.href="http://newhost/newpath/newfile.html"; 6. //--></script>

7. To load a script dynamically Note you get an "unterminated string literal" if you don't chop up the ending script tag.
document.write('<script src=\'http://www.fincher.org/Html5Slides/slides.js\'></'+'script>' );

16. Sites 1. JavaScript from the w3.org. 2. DOM Viewer - A most wonderful tool for viewing the DOM. It's easy, simple, and incredibly helpful. 3. Javascript reference sites: for snippets of code: javascriptsource.com 17. Javascript Math, Numbers, and Dates

Evaluate Javascript Expression


enter expression: Output:

1. How to convert a string to a number

You can use the parseInt() and parseFloat() methods. Notice that extra letters following a valid number are ignored, which is kinda wierd but convenient at times.
parseInt("100") ==> 100 parseFloat("98.6") ==> 98.6 parseFloat("98.6 is a common temperature.") ==> 98.6 parseInt("aa") ==> Nan //Not a Number parseInt("aa",16) ==> 170 //you can supply a radix or base

2. How to convert numbers to strings You can prepend the number with an empty string
var mystring = ""+myinteger;

or
var mystring = myinteger.toString();

You can specify a base for the conversion like hex,


var myinteger = 14; var mystring = myinteger.toString(16);

mystring will be "e". convert an integer to its ASCII character. "c" will be 'A'
var c = String.fromCharCode(65); //"c" will be 'A'

3. How to format decimal numbers

4. var number = 3.14159; 5. var formattedNumber = number.toFixed(2);

6. How to format integers by adding commas

7. function numberWithCommas(x) { 8. return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ","); 9. }

10. Testing for bad numbers the global method, "isNaN()" can tell if a number has gone bad.
var temperature = parseFloat(myTemperatureWidget.value); if(!isNaN(temperature)) { alert("Please enter a valid temperature."); }

11. Math Constants and Functions The Math object contains useful constants such as Math.PI, Math.E Math also has a zillion helpful functions.

Math.abs(value); //absolute value Math.max(value1, value2); //find the largest Math.random() //generate a decimal number between 0 and 1 Math.floor(Math.random()*101) //generate a decimal number between 0 and 100 Math.cos(x) //takes the cosine of x in radians, also sin(), tan(), asin() etc... Math.random() //pseudo-random number from 0 to 1 Math.PI //3.14159... Math.pow(a,b) // a to the power b

12. The Date object Time inside a date object is stored as milliseconds since Jan 1, 1970.
new Date(06,01,02) // produces "Fri Feb 02 1906 00:00:00 GMT-0600 (Central Standard Time)" new Date(06,01,02).toLocaleString() February 02, 1906 00:00:00" // produces "Friday,

new Date(06,01,02) - new Date(06,01,01) // produces "86400000"

18. Arrays 1. Creating Arrays

2. <script type="text/javascript"> 3. var days = new Array(); 4. days[0] = "Sunday" 5. days[1] = "Monday" 6. days[2] = "Tuesday" 7. days[3] = "Wednesday" 8. days[4] = "Thursday" 9. days[5] = "Friday" 10. days[6] = "Saturday" 11. 12. document.write("first day is "+days[0]) 13. </script> 14.

This produces first day is Sunday A more compact way of creating an array is the literal notation called JSON(similiar in function to xml):
<script type="text/javascript"><!-var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"]; document.write("first day is "+days[0]) //--> </script>

This produces first day is Sunday 15. Deleting an entry The "delete" operator removes an array element, but oddly does not change the size of the array.
<script type="text/javascript"><!-var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"]; document.write("Number of days:"+days.length); delete days[4]; document.write("<br />Number of days:"+days.length); //--> </script>

This produces Number of days:7 Number of days:7 16. Using strings as array indexes Javascript does not have a true hashtable object, but through its wierdness, you can use the array as a hashtable.
<script type="text/javascript"><!-var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"]; for(var i=0; i < days.length; i++) { days[days[i]] = days[i]; } document.write("days[\"Monday\"]:"+days["Monday"]); //--> </script>

This produces days["Monday"]:Monday 17. Using "join()" to create a string from an array "join" concatenates the array elements with a specified seperator between them.
<script type="text/javascript"> var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"]; document.write("days:"+days.join(",")); </script>

This produces days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday 18. Array as a stack The pop() and push() functions turn a harmless array into a stack
<script type="text/javascript"> var numbers = ["one", "two", "three", "four"]; numbers.push("five"); numbers.push("six"); document.write(numbers.pop()); document.write(numbers.pop()); document.write(numbers.pop()); </script>

This produces sixfivefour 19. shift and unshift These function use elements from the front >
<script type="text/javascript"> var numbers = ["one", "two", "three", "four"]; numbers.unshift("zero"); document.write(" "+numbers.shift()); document.write(" "+numbers.shift()); document.write(" "+numbers.shift()); </script>

This produces zero one two shift, unshift, push, and pop may be used on the same array. Queues are easily implemented using combinations. 20. Other array functions reverse() - reverses the order of the elements slice() - extracts part of an array sort() - sorts splice() - removes items from an array 19. Predefined Functions

Javascript provides many "free floating" utility functions, not tied to an object. 1. decodeURI(), encodeURI() Many characters cannot be sent in a URL, but must be converted to their hex encoding. These functions are used to convert an entire URI (a superset of URL) to and from a format that can be sent via a URI.
<script type="text/javascript"><!-var uri = "http://www.google.com/search?q=sonofusion Taleyarkhan" document.write("Original uri: "+uri); document.write("<br />encoded: "+encodeURI(uri)); //--> </script>

This produces Original uri: http://www.google.com/search?q=sonofusion Taleyarkhan encoded: http://www.google.com/search?q=sonofusion%20Taleyarkhan Notice the space has been replaced with it's hex value, "%20". 2. unescape(), escape() These are similar to the decodeURI() and encodeURI(), but escape() is used for only portions of a URI.
<script type="text/javascript"><!-var myvalue = "Sir Walter Scott"; document.write("Original myvalue: "+myvalue); document.write("<br />escaped: "+escape(myvalue)); document.write("<br />uri part: \"&author="+escape(myvalue)+"\""); //--> </script>

This produces Original myvalue: Sir Walter Scott escaped: Sir%20Walter%20Scott uri part: "&author=Sir%20Walter%20Scott" If you use escape() for the whole URI... well bad things happen.
<script type="text/javascript"><!-var uri = "http://www.google.com/search?q=sonofusion Taleyarkhan" document.write("Original uri: "+uri); document.write("<br />escaped: "+escape(uri)); //--> </script>

This produces

Original uri: http://www.google.com/search?q=sonofusion Taleyarkhan escaped: http%3A//www.google.com/search%3Fq%3Dsonofusion %20Taleyarkhan 3. eval() The eval() method is incredibly powerful allowing you to execute snippets of code during execution.
<script type="text/javascript"><!-var USA_Texas_Austin = "521,289"; document.write("Population is "+eval("USA_"+"Texas_"+"Austin")); //--> </script>

This produces Population is 521,289 20. To execute javascript directly in the address bar in firefox:
javascript:alert("test");void(0);

Potrebbero piacerti anche