41
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

Javascript Tutorial for Beginners

Embed Size (px)

DESCRIPTION

A simple javascript tutorial for beginners with examples.

Citation preview

Page 1: Javascript Tutorial for Beginners

JavascriptJavascript 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

Page 2: Javascript Tutorial for Beginners

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 multilinecomment*/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 Examples

replace(regExp,replacement)replaces a regular expression with a string.Modifiersg - replace all occurances (global)i - ignore case

"ababAbab".replace(/a/,"c") ==> cbabAbab

"ababAbab".replace(/a/g,"c") ==> cbcbAbcb "ababAbab".replace(/a/gi,"c") ==> cbcbcbcb

match(regExp)returns an array of matching strings

"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 foundHints:\s is a space

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

Page 3: Javascript Tutorial for Beginners

\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.

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

split(delimiter)returns an array of strings split by the delimeter

"Gamma;Helm;Johnson".split(";") ==> Gamma,Helm,Johnson

toLowerCase(),toUpperCase()returns a string with changed case

"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: Aliensdirector: CameronMovie:title: Fellowship of the Ringdirector: undefinedMovie:title: Narnidirector: Andrew Adamson

Page 4: Javascript Tutorial for Beginners

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: Aliensdirector: Cameron

Movie:(Arguments passed in:1)title: Fellowship of the Ring

Movie:(Arguments passed in:3)title: Narnidirector: Andrew AdamsonBased 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" />

Page 5: Javascript Tutorial for Beginners

</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;

Page 6: Javascript Tutorial for Beginners

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

Page 7: Javascript Tutorial for Beginners

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 prototypedocument.write(narnia.toString());document.write("<br />Narnia a comedy? "+narnia.isComedy);officeSpace.isComedy = true; //override the default just for this objectdocument.write("<br />Office Space a comedy? "+officeSpace.isComedy);//--></script>

This produces

title: Narnia director: Andrew AdamsonNarnia a comedy? falseOffice 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

Page 8: Javascript Tutorial for Beginners

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 true false

numbers any non-zero number zero

string any string with content empty, ""

object exists does not exist

property is already defined is not defined

16. A loop example: 17. function Timer() {18. for(i = 1; i <= 300; i++) {19. MoveIt();20. }21.22. }

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;

Page 9: Javascript Tutorial for Beginners

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 0scrollLeft is 0scrollHeight is 16scrollWidth is 600clientTop is 0clientLeft is 0

Page 10: Javascript Tutorial for Beginners

clientHeight is 16clientWidth is 600firstElementChild is nulllastElementChild is nullpreviousElementSibling is nullnextElementSibling is [object HTMLScriptElement]childElementCount is 0children 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 inheritisContentEditable is falseoffsetParent is [object HTMLBodyElement]innerHTML is I am a test paragraph.offsetLeft is 277offsetTop is 9467offsetHeight is 16offsetWidth is 600scrollIntoView is function scrollIntoView() { [native code] }id is testmetitle 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 PremoveAttributeNS 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 PnodeValue is null

Page 11: Javascript Tutorial for Beginners

nodeType is 1parentNode 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/xhtmlprefix is nulllocalName is pbaseURI is http://www.fincher.org/tips/Languages/javascript.shtmltextContent 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 1ATTRIBUTE_NODE is 2TEXT_NODE is 3CDATA_SECTION_NODE is 4ENTITY_REFERENCE_NODE is 5ENTITY_NODE is 6PROCESSING_INSTRUCTION_NODE is 7COMMENT_NODE is 8DOCUMENT_NODE is 9DOCUMENT_TYPE_NODE is 10DOCUMENT_FRAGMENT_NODE is 11NOTATION_NODE is 12DOCUMENT_POSITION_DISCONNECTED is 1

Page 12: Javascript Tutorial for Beginners

DOCUMENT_POSITION_PRECEDING is 2DOCUMENT_POSITION_FOLLOWING is 4DOCUMENT_POSITION_CONTAINS is 8DOCUMENT_POSITION_CONTAINED_BY is 16DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC is 32hidden is falsetabIndex is -1draggable is falseinsertAdjacentHTML is function insertAdjacentHTML() { [native code] }contextMenu is nullspellcheck is falsedataset is [object DOMStringMap]mozRequestFullScreen is function mozRequestFullScreen() { [native code] }onabort is nullonblur is nulloncanplay is nulloncanplaythrough is nullonchange is nullonclick is nulloncontextmenu is nullondblclick is nullondrag is nullondragend is nullondragenter is nullondragleave is nullondragover is nullondragstart is nullondrop is nullondurationchange is nullonemptied is nullonended is nullonerror is nullonfocus is nulloninput is nulloninvalid is nullonkeydown is nullonkeypress is nullonkeyup is nullonload is nullonloadeddata is nullonloadedmetadata is nullonloadstart is nullonmousedown is nullonmousemove is nullonmouseout is nullonmouseover is nullonmouseup is nullonmozfullscreenchange is nullonpause is nullonplay is nullonplaying is nullonprogress is nullonratechange is null

Page 13: Javascript Tutorial for Beginners

onreset is nullonscroll is nullonseeked is nullonseeking is nullonselect is nullonshow is nullonstalled is nullonsubmit is nullonsuspend is nullontimeupdate is nullonvolumechange is nullonwaiting is nulloncopy is nulloncut is nullonpaste is nullonbeforescriptexecute is nullonafterscriptexecute 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.");

Page 14: Javascript Tutorial for Beginners

//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 propertiesBye.

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);}

Page 15: Javascript Tutorial for Beginners

//--></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>

Page 16: Javascript Tutorial for Beginners

<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;

5. To delete all options in a select object set the length to 0. 6. mySelectObject.length = 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() {

Page 17: Javascript Tutorial for Beginners

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;

33. To set the focus in an element 34. <script>35. function setFocus() {36. if(focusElement != null) {37. document.forms[0].elements["myelementname"].focus();38. }39. }40. </script>41.

42. To put a "close window" link on a page. 43. <a href='javascript:window.close()' class='mainnav'> Close </a>

44. To set all checkboxes to true 45. //select all input tags46. function SelectAll() {47. var checkboxes = document.getElementsByTagName("input");48. for(i=0;i<checkboxes.length;i++) {49. 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. <script language="JavaScript" type="text/javascript" >58. function setBeerIcon() {

Page 18: Javascript Tutorial for Beginners

59.60. var beerIcon = document.getElementById("beerIcon");61. beerIcon.src = "images/"+getSelectValue("beer")+".jpg";62. }63. </script>64.65. ...66.67. <img border="0" src="" id="brandIcon" alt="brand" />68.69. <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. <script>83. function favAnimal(button) {84. alert('You like '+button.value+'s.');85. }86. </script>87. <input type="radio" name="marsupial" value="kangaroo" 88. onchange="favAnimal(this)">Kangaroo89. <br /><input type="radio" name="marsupial" value="Opossum" 90. onchange="favAnimal(this)">Opossum91. <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. <script type="text/javascript">95. function findButton() {96. var myForm = document.forms.animalForm;97. var i;98. 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"

/>Kangaroo108. <br /><input type="radio" name="marsupial"

value="Opossum" />Opossum

Page 19: Javascript Tutorial for Beginners

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. To disable an HTML object 115. 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.

Page 20: Javascript Tutorial for Beginners

<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 Firefox7. 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. <script type="text/javascript">23. function addItem() {24. var myitem = document.getElementById("ItemToAdd").value;25. var mylistItems = document.getElementById("mylist");26. var newP = document.createElement("li");27. var textNode = document.createTextNode(myitem);28. newP.appendChild(textNode);29. document.getElementById("mylist").appendChild(newP);30. return false;31. }32. </script>33. <form onsubmit="return addItem()" action="#">34. <span>Grocery Items:</span>35. <input type="text" id="ItemToAdd" value="Milk" />36. <input type="button" value="Add" onclick="addItem()" />37. </form>38. <span>Grocery List:</span> 39. <ol id="mylist"></ol>40.

Page 21: Javascript Tutorial for Beginners

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. document.forms[0] //if its the first form on a page3. document.myformname4. document.forms["myformname"]5. 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

Page 22: Javascript Tutorial for Beginners

name is name is cupidname is cupidname 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. <form name="form3" action="#">22.23. <div>Who are your favorite browncoats? Please select all that

apply to you:24.25. <input type="checkbox" name="Zoe" />Zoe 26. <input type="checkbox" name="Mal" />Mal 27. <input type="checkbox" name="Inara" />Inara28. <input type="checkbox" name="Kaylee" /> Kaylee 29. <input type="checkbox" name="River" />River 30. <input type="checkbox" name="Simon" /> Simon31. </div>32. <input type="submit" name="NEXT" value="GO! " />33. </form>34. <script type="text/javascript" ><!--35. //returns how many checkboxes in the form are checked36. function howManyChecks(form) {37. var selections = 0;38. for (var i=0; i<form.length; i++) {39. var theElement = form.elements[i];40. if(theElement.type == "checkbox") {41. if(theElement.checked == true) {42. selections++43. }44. }45. }46. return selections47. }48. function validate() {49. var num = howManyChecks(document.forms["form3"])50. if( num == 0) {51. alert("Please make a selection.");52. } else {53. alert("Number of favorite characters: "+num)54. }

Page 23: Javascript Tutorial for Beginners

55. return false;56. }57. document.forms["form3"].elements["NEXT"].onclick=validate;58. //-->59. </script>

This produces

Who are your favorite browncoats? Please select all that apply to you: Zoe

Mal Inara Kaylee River Simon

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 6. alert('Warning: Please enter an integer between 0 and 100.');

try it:

7. To create a confirmation box 8. confirm("Do you really want to launch the missile?");

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.

window.open("http://www.fincher.org/Misc/Pennies","Pennies","resizable=yes,status=yes,toolbar=yes,location=yes,menubar=yes,scrollbars=yes,width=800,height=400");

14.

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 myTextBoxfunction TextBoxOnchange() { var myBox = window.document.getElementById(myTextBox");

Page 24: Javascript Tutorial for Beginners

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 Goodman5. var labelLen = labelName.length;6. // read cookie property only once for speed7. 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. setValueFromCookie("measure");30. }31.32. function setValueFromCookie(widget) {33. if( getCookieData(widget) != "") {34. document.getElementById(widget).value =

getCookieData(widget);35. }36. }37.

Page 25: Javascript Tutorial for Beginners

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

Page 26: Javascript Tutorial for Beginners

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

Page 27: Javascript Tutorial for Beginners

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/addLoadEventfunction 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";-or-document.getElementById("myText").className = "regular";

2. To load a style sheet dynamically3. var el = document.createElement('link');4. el.rel = 'stylesheet';5. el.type = 'text/css';6. 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.

Page 28: Javascript Tutorial for Beginners

document.body.style.cursor = 'wait'; //do something interesting and time consumingdocument.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;

Page 29: Javascript Tutorial for Beginners

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)"

Page 30: Javascript Tutorial for Beginners

new Date(06,01,02).toLocaleString() // produces "Friday, February 02, 1906 00:00:00"

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

Page 31: Javascript Tutorial for Beginners

Number of days:7Number 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

Page 32: Javascript Tutorial for Beginners

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 Taleyarkhanencoded: http://www.google.com/search?q=sonofusion%20Taleyarkhan

Notice the space has been replaced with it's hex value, "%20".

2. unescape(), escape()

Page 33: Javascript Tutorial for Beginners

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 Scottescaped: Sir%20Walter%20Scotturi 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 Taleyarkhanescaped: 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);