Learning JavaScript by Example

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. For detailed documentation see https://developer.mozilla.org/en/JavaScript.

This page shows only how to use raw JavaScript. Many of the functions shown here can be done more simply with libraries like jQuery.

  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>
          document.write("Last Updated:" + 
                  document.lastModified);
                  document.close();
      </script>
      <p>yada, yada, yada.</p>
      

      The tendency now is to put your javascript at the end of the page when possible so your content will load quickly for the user.

      The above code will look like this on Javascript enabled browsers:


      
      
    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>
              var myTitle = "My Cool Title";
              function triple(a){return a+a+a;}
      </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 src="myStuff.js"></script>
      

      If you don't have to have the JavaScript loaded immediately, use the "async" attribute. The page loading will not wait for the js file to download before continuing.

       
        <script async src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
      
  2. Running JavaScript interactively

    Visit http://jsbin.com/ for an easy online way to enter JavaScript code, or if you prefer to download a local environment try http://jsdb.org/

  3. 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; //comment can be at the end of a line
      
    2. Global and Local Variables

      "var" declares a variable. The variable's type is inferred from it's assignment, ("var i=5", i is an integer)

      Variables defined outside of a function are global variables. These may be accessed from any function. When JavaScript is running in a web page, variables live only as long as the page and live in the global context of "window".

      name = "Katniss";
      alert(window.name); //shows "Katniss"
      

      Local variables only live inside a function. If you forget to preface with "var", the variable becomes a global. Always use "var".

      var imAGlobalVar = 10;
      
      function foo() {
         var imALocalVar = 11;  //local variable
         imAGlobalVar2 = 12;    //global variable, not good practice
      }
      
    3. const

      For variables that don't change (is that an oxymoron?), we use the "const" key word.

      const taxRate = 0.0825;
      
    4. Null and Undefined

      "null" represents the intentional absence of an object. You can explicitly set an object to 'this object has no value' with 'null'. It evaluates to false in a boolean expression.

      "undefined" represents an unassigned value. The value has not even been set to "null". It also evaluates to false. "undefined" is often used to test if a property exists on an object.

      Here's an example. Note the method "write()" is not an intrinsic JavaScript function, but something we define.

        function write(message) { document.getElementById('output').innerHTML += message + '<br>';
      }
       //write(IDontExist); //runtime exception
      write(typeof IDontExist); //undefined
      var apple;
      write(apple); //undefined
      apple = null;
      write(apple); //null
      apple = "red";
      write(apple); //red
      write(apple.variety); //undefined
      

      See this code at jsbin.com: JS Bin

    5. Equality

      "We hold these truths to be self-evident, that all men are created equal". But what is equality? JavaScript has two definitions.

      "==" does type coercion. (5 == "5") is true.

      "===" compares, but does not do coercion. (5 === "5") is false. You should usually use "===" for comparisons.

      Primitives are equal if their values are equal.

      Objects are not equal if their contents are the same - only if the object is compared to itself is it equal.

    6. String manipulations

      Javascript has the standard compliment of string methods. Here are a few of the more interesting.

      FunctionExamples
      replace(regExp,replacement)
      replaces a regular expression with a string.
      Modifiers
      g - 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 found
      Hints:
      \s is a space
      \b word boundary
      * zero or more
      . a character
      "ababAbab".search(/b/) ==> 1
      "ababAbab".search(/ab/) ==> 0
      "ababAbab ababAbab".search(/b\s/) ==> 7
      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
    7. Example of using Regular Expressions for syntax checking
      ...
      var re = new RegExp("^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$");
      var text = myWidget.value;
      var OK = re.test(text);
      if( ! OK ) {
          alert("The extra parameters need some work.\r\n  Should be something like: \"&a=1&c=4\"");
      }
       
      
  4. Javascript Functions
    1. Basics

      functions are dervived from "object", so they are real objects. Here is the typical declaration:

      function triple(a) {
        return a*3;
      }
      

      You can also assign the function directly to a name:

      var triple = function (a) {
        return a*3;
      }
      

      Or even create an anonymous function and invoke it immediately, by surrounding it with parentheses and passing the arguments directly after declaration:

      (function (a) {
        return a*3;
      })(7)
      

      No overloading of methods.

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

      If you do not supply all the arguments, javascript doesn't care. It just sets those missing variables to "undefined" 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?'.
      Each function has a built-in object that acts like an array, "arguments", which allows you to access any extra arguments.

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

      Primitive values are passed by value, and objects are passed by reference.

      JavaScript supports Closure, so nested methods can access all the variables in the context in which it was invoked.

      Recursion is also supported so functions may call themselves (cue factorial demo).

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

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

      To create an object you write a method with the name of your object and invoke the method with "new".

      <script>
      function movie(title, director) {
         this.title = title;
         this.director = director;
         }
      var aliens = new movie("Aliens","Cameron");
      document.write("aliens:"+aliens.toString());
      </script>
      
      

      This produces

      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>
      function movie(title, director) {
         title : title;
         director : director;
         }
      var aliens = new movie("Aliens","Cameron");
      document.write("aliens:"+aliens.toString());
      </script>
      
      

      This produces

      This is true, but not very satisfying, since it tells us nothing about the object.

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

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

    3. Prototypes

      Objects have "prototypes" from which they may inherit fields and functions.

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

  6. Javascript Flow of Control

    Javascript offers many ways to alter the flow of control.

    But first, a little note: "{" and "}" group statements together so they can act as a unit. Unlike Java and C#, braces do not provide variable scoping.

    1. if
      <script>
      var balance = 400.0;
      if(balance < 0.0) {
         status = "bankrupt";
      } else if(balance < 100.0) {
         status = "ok";
      } else {
         status = "rich";
         }
      document.write("customer is "+status);
      </script>
      
      

      This produces

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

      objecttruefalse
      numbersany non-zero numberzero
      stringany string with contentempty, ""
      objectexistsdoes not exist
      propertyis already definedis not defined
    3. A loop example:
      function Timer() {
      for(i = 1; i <= 300; i++) {
         MoveIt();
         }
      
      }
      
    4. Exiting a loop

      When a "break" statement is encountered, we jump out of the loop.

      <script>
      for(var i=0; i<100; i++) {
         document.write(i);
         if(i > 5) { break; }
      }
      </script>
      
      

      This produces

    5. "continue" - kinda break

      The continue statement stops execution, but returns control back to the loop.

      <script>
      for(var i=0; i<10; i++) {
         document.write(".");
         if(i > 5) { continue; }
         document.write(i);
      }
      </script>
      
      

      This produces

    6. While

      Execution loops inside the while until its condition is false...

      <script>
      var total = 1;
      while(total < 100) {
         document.write(total+",");
         total = total * 2;
      }
      </script>
      
      

      This produces

      or until a break is hit

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

      This produces

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

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

    9. switch

      Like most modern languages javascript has a switch statement. The expression in the switch can be a number or a string.

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

    10. 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"
          }
      
    11. try-catch-finally

      Javascript's error handling is very similiar to java and c#.

      <script>
      try {
         obj = null;
         null.to_s();
      } catch (e) {
         document.write("Exception: "+e);
      } finally {
         document.write("<br />Bye.");
      }
      </script>
      
      

      This produces

    12. throw

      When throwing an exception you can create an Error object or just throw a string.

      <script>
      var i = 12;
      try {
      if(i < 30) {
        throw "I was really expecting something over 30";
      }
      } catch(e) {
         document.write("Exception: "+e);
      }
      </script>
      
      

      This produces

    13. 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);
      }
      
    14. 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);
      
  7. 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
        mySelectObject.options[3] = null;
        
      2. To truncate a list set its length to the maximum size you desire
        mySelectObject.length = 2;
        
      3. To delete all options in a select object set the length to 0.
        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.
      <script>
      function showStatus() {
       var selectWidget = document.forms.beerForm.elements["beer"];
       var myValue = selectWidget.options[selectWidget.selectedIndex].value;
        alert('You drank a \"'+ myValue +"\"");
        return true;
      }
      </script>
      
      <form name="beerForm">
      <select name="beer">
         <option selected="selected">Select Beer</option>
         <option>Heineken</option>
         <option>Amstel Light</option>
         <option>Corona</option>
         <option>Corona Light</option>
         <option>Tecate</option>
      </select>
      
      <input type="button" name="submitbutton" value="Drink"  
              onclick="showStatus()" />
      </form>
      
      
      
      

      Try It:

    5. To get the contents of an input box.

      Use the "value" property.

      var myValue = window.document.getElementById("MyTextBox").value;
      
    6. To determine the state of a checkbox
      var checkedP = window.document.getElementById("myCheckBox").checked;
      
    7. To set the focus in an element
      <script>
      function setFocus() {
      if(focusElement != null) {
         document.forms[0].elements["myelementname"].focus();
        }
      }
      </script>
      
      
    8. To put a "close window" link on a page.
      <a href='javascript:window.close()' class='mainnav'> Close </a>
      
    9. To set all checkboxes to true
      //select all input tags
      function SelectAll() {
         var checkboxes = document.getElementsByTagName("input");
         for(i=0;i<checkboxes.length;i++) {
            if(checkboxes.item(i).attributes["type"].value == "checkbox") {
               checkboxes.item(i).checked = true;
            }
         }
      }
      
    10. Selecting an element by id and swapping an image
      
      ...
      <script>
      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();">
      <option  value="--Select--">Select beer</option>
         <option value="heineken">heineken</option>
         <option value="sol">sol</option>
         <option value="amstellight">amstellight</option>
         <option value="coronalight">coronalight</option>
         <option value="coronaextra">coronaextra</option>
         <option value=""></option>
      </select>
      
      
      
    11. To find the selected radio button immediately using the 'this' variable.
      
      <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"
              onchange="favAnimal(this)">Tasmanian Tiger
      </script>
      
      

      Try it here:

      Kangaroo
      Opossum
      Tasmanian Tiger
    12. To find radio button selection when a form is submitted
      <script>
      function findButton() {
      var myForm = document.forms.animalForm;
      var i;
      for(i=0;i<myForm.marsupial.length; i++) {
         if(myForm.marsupial[i].checked) {
            break;
         }
      }
      alert("You selected \""+myForm.marsupial[i].value+"\".");
      }
      </script>
      <form name="animalForm">
      <input type="radio" name="marsupial" value="kangaroo" />Kangaroo
      <br /><input type="radio" name="marsupial" value="Opossum" />Opossum
      <br /><input type="radio" name="marsupial" value="Tasmanian Tiger" />Tasmanian Tiger
      <br />
      <input type="button" name="GO" value="GO" onclick="findButton()" />
      </form>
      
      

      Try it here:

      Kangaroo
      Opossum
      Tasmanian Tiger
    13. To disable an HTML object
         document.getElementById("myObject").disabled = true;
      
  8. 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
      <a href="http://www.fincher.org/History/World.shtml">History is fun!</a>
      

      Try it:History is fun!

    2. 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!

    3. The Pseudo-URL href

      To have an element invoke a javascript on selection, instead of going to a new URL:

      <script>
      function pseudoHitMe() {
        alert("Ouch!");
      }
      </script>
      <a href="javascript:pseudoHitMe()">hit me</a>
      
      Try It: hit me
    4. 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.

  9. 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
      <script>
      function showCard() {
       var message = document.getElementById("CCN").value;
       var element = document.getElementById("mycreditcardnumber");
        element.textContent  = message; //for Firefox
        element.innerHTML  = message; //for IE (why can't we all just get along?)
        return true;
      }
      </script>
      <form name="dynamic" method="get">
      <span>Enter Your Credit Card Number:</span>
      <input type="text" id="CCN" name="CCN" value="CCN" />
      <input type="button" value="submit" onclick="showCard()" />
      </form>
      
      <p>Verify your Credit Card Number: 
        <span id="mycreditcardnumber">0000-00-0000-00 </span>
      </p>
      
      

      This produces

      Enter Your Credit Card Number:

      Verify your Credit Card Number: 0000-00-0000-00

    2. Adding new elements dynamically.
      <script>
      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);
       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:
      1. 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.

      2. 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>";
        
      3. 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";
        
    3. Working with Forms
      1. You can access forms in at least four ways:

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

      2. You can dynamically add an "onclick" event to a button.
        <form name="form2" action="#">
        <input type="submit" name="NEXT" value="Next " /><br />
        </form>
        
        <script>
        function validate() {
           alert("validated.");
           document.forms["form2"].style.background="red"
        
           return false;
        }
        document.forms["form2"].elements["NEXT"].onclick=validate;
        </script>
        

        This produces


      3. Example of counting the number of checks in a form
        <form name="form3" action="#">
        
        <div>Who are your favorite browncoats?  Please select all that apply to you:
        
        <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>
        //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") {
                      if(theElement.checked == true) {
                         selections++
                      }
                  }
              }
           return 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: Zoe Mal Inara Kaylee River Simon
    4. 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).
        <a href="javascript.shtml" 
              onmouseover="window.status='Hi There!';return true" 
              onmouseout="window.status='';return true">Look at the Status bar</a>
        
        Look at the Status bar as your cursor goes over the link.
      2. To create a popup warning box
        alert('Warning: Please enter an integer between 0 and 100.');
        

        try it:

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

        try it:

      4. To create an input box
        prompt("What is your temperature?");
        

        try it:

      5. To open a window specifying certain decorations:
        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");
        

        try it:

      6. A better way to open a window:

        This works even with JavaScript turned off. The "this.href" portion grabs the "href" value and pops open the window there. The "return false" tells the browser not to redirect the main browser window to the href. But popups are often problematic - the browser may block popups unless the user says OK, or like Opera may push the popup to a background tab instead of a new window.

        <a href='http://www.fincher.org/Misc/Pennies'
        onclick='window.open(this.href,"Pennies",
        "resizable=yes,status=yes,toolbar=yes,location=yes,menubar=yes,"+
        "scrollbars=yes,width=800,height=800"); return false;'>Pennies</a>
        

        This produces

    5. 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
        function getCookieData(labelName) {
                //from Danny Goodman
                var labelLen = labelName.length;
                // read cookie property only once for speed
                var cookieData = document.cookie;
                var cLen = cookieData.length;
                var i = 0;
                var cEnd;
                while (i < cLen) {
                        var j = i + labelLen;
                        if (cookieData.substring(i,j) == labelName) {
                                cEnd = cookieData.indexOf(";",j);
                                if (cEnd == -1) {
                                        cEnd = cookieData.length;
                                }
                                return unescape(cookieData.substring(j+1, cEnd));
                        }
                        i++;
                }
                return "";
        }
        
        //init() is called from the body tag onload function.
        function init() {
           setValueFromCookie("brand");
           setValueFromCookie("market");
           setValueFromCookie("measure");
        }
        
        function setValueFromCookie(widget) {
          if( getCookieData(widget) != "") {
              document.getElementById(widget).value  = getCookieData(widget);
           }
        }
        
        //if you name your cookies the widget ID, you can use the following helper function
        function setCookie(widget) {
           document.cookie = widget + "=" +
           escape(document.getElementById(widget).value) + getExpirationString();
        }
        
        
        
    6. 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
    7. Event Handlers
      1. Events

        You can add an event handler in the HTML definition of the element like this,

        <script>
        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>
        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>
        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>
        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>
        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>
        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>
           window.onload = MyCoolInitFunc
        </script>
        
    8. 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 dynamically

          var el = document.createElement('link');
          el.rel = 'stylesheet';
          el.type = 'text/css';
          el.href = 'http://www.Example.com/...' + 'styles.css';
          document.body.appendChild(el);
      3. 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';
           }
        
      4. 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'; 
        
      5. Using style to create motion ...
    9. Miscellaneous
      1. To reload the current page
        window.location.reload(true);
        
      2. To force a page to redirect to another page
        <script>
        location.href="http://newhost/newpath/newfile.html";
        </script>
        
      3. 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>');
        
      4. Gather all the name-value pairs from the URL

        //from http://snipplr.com/view/799/get-url-variables/
        function getUrlVars() {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        }
        
      5. To show all the name-value pairs from the URL in an HTML table

        Using the function above

        <h1>Show URL Name-Value Pairs in HTML Table</h1>
        <table id="namevalues">
            <tr><th>Name</th><th>Value</th></tr>
        </table>
        <script>
            var nameValuesHash = getUrlVars();
            var table = document.getElementById("namevalues");
            for (var i = 0; i < nameValuesHash.length; i++) {
                var row = table.insertRow(i + 1);
                row.insertCell(0).innerHTML = nameValuesHash[i];
                row.insertCell(1).innerHTML = nameValuesHash[nameValuesHash[i]];
            }
        </script>
        
        Try it here http://www.fincher.org/tips/Languages/ShowPassedInVariables.shtml?element=Ruthenium&atomicNumber=44&atomicWeight=101.07
    10. 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
    11. 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
        var number = 3.14159;
        var formattedNumber = number.toFixed(2);
        
      4. How to format integers by adding commas
        function numberWithCommas(x) {
            return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
        }
        
      5. 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.");
        }
        
      6. 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
      7. 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)"
                            // note the month is zero based
        
        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", difference in milliseconds
        
        new Date() //today's date
        

        Datejs is a library from Datejs.com that adds more functionality, e.g., Date.today().add(7).days()

    12. Arrays
      1. Creating Arrays
        <script>
        var days = new Array();
        days[0] = "Sunday"
        days[1] = "Monday"
        days[2] = "Tuesday"
        days[3] = "Wednesday"
        days[4] = "Thursday"
        days[5] = "Friday"
        days[6] = "Saturday"
        
        document.write("first day is "+days[0])
        </script>
        
        

        This produces

        A more compact way of creating an array is the literal notation called JSON(similiar in purpose to xml):

        <script>
        var days = ["Sunday","Monday","Tuesday","Wednesday",
           "Thursday","Friday","Saturday"];
        
        document.write("first day is "+days[0])
        </script>
        
        

        This produces

      2. Deleting an entry

        The "delete" operator removes an array element, but oddly does not change the size of the array.

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

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

      4. Using "join()" to create a string from an array

        "join" concatenates the array elements with a specified seperator between them.

        <script>
        var days = ["Sunday","Monday","Tuesday","Wednesday",
           "Thursday","Friday","Saturday"];
        document.write("days:"+days.join(","));
        </script>
        
        

        This produces

      5. Array as a stack

        The pop() and push() functions turn a harmless array into a stack

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

      6. shift and unshift

        These function use elements from the front >

        <script>
        var numbers = ["one", "two", "three", "four"];
        numbers.unshift("zero");
        document.write(" "+numbers.shift());
        document.write(" "+numbers.shift());
        document.write(" "+numbers.shift());
        </script>
        
        

        This produces

        shift, unshift, push, and pop may be used on the same array. Queues are easily implemented using combinations.

      7. Other array functions

        reverse() - reverses the order of the elements

        slice() - extracts part of an array

        sort() - sorts

        splice() - removes items from an array

    13. JavaScript object Notation (JSON) objects

      These are simply string literals. The best way to parse JSON is with the library json2.js.

      JSON.parse(json);
      JSON.stringify(json);
      

      Or, you can use the "eval" function, although it's slower and less secure.

      $(function() {
        function write(message) { document.getElementById('output').innerHTML += message + '<br>';
      }
        var library = '{ books: [ {title: "The Giver",author: "Lowery"}]}';
      
        write(library);
        eval("var myLibrary = "+library);
        write(myLibrary.books[0].title);  
      });
      

      jsbin.com/iZofEh/1/

    14. 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>
        var uri = "http://www.google.com/search?q=sonofusion Taleyarkhan"
        document.write("Original uri: "+uri);
        document.write("<br />encoded: "+encodeURI(uri));
        </script>
        
        

        This produces

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

        If you use escape() for the whole URI... well bad things happen.

        <script>
        var uri = "http://www.google.com/search?q=sonofusion Taleyarkhan"
        document.write("Original uri: "+uri);
        document.write("<br />escaped: "+escape(uri));
        </script>
        
        

        This produces

      3. eval()

        The eval() method is incredibly powerful allowing you to execute snippets of code during execution.

        <script>
        var USA_Texas_Austin = "521,289";
        document.write("Population is "+eval("USA_"+"Texas_"+"Austin"));
        </script>
        
        

        This produces

    15. To execute javascript directly in the address bar in firefox:

      javascript:alert("test");void(0);
      
    16. How to have a form call a javascript function

      <script>
      function saveInfo() {
        localStorage.setItem("name",$("#name").val());
      }
      </script>
      <form id=register onSubmit="return saveInfo()">
        <label for="name">Name:</label>
        <input type=text name=name id=name>
        <input type=submit value=save>
      </form>
      
      
    17. Speeding up your web pages

      Check out a Firebug plugin, YSlow and see Yahoo's Guide at http://developer.yahoo.com/performance/rules.html.

    18. QUnit - a JavaScript Unit test framework

      QUnit, a part of jQuery helps in unit testing.

    19. debugging tools list from pcwdld.