How to create and test Javascript

Create your file in Expression Web, and load it up in any web browser to test. 

You can use Intellisense, provided a) you're editing an HTML file (doesn't seem to work in .js files), and b) Intellisense can figure out what members exist in the object you're referring to.  It's easily confused, and since Javascript variables don't have types, there may not be enough information for Intellisense to know.  Still, it works for some things quite well.

In every file, put the line 'use strict' .  It gives you better error checking, supposedly increased security and performance, and warns you if you're using something to be deprecated.  In my experience so far, mostly it warns you if you forget to put "var" before your first use of a variable.

Note:  in the examples below I put scripts directly into the HTML, so you can see it all in one place.  Usually I'd load a .js file.

How to print something into an HTML file

<script> <!-- this goes in the body -->
document.write ('<p>Hello, ');
document.write ('World! </p>');
</script>

Test

I'd use this primarily for debugging

How to debug using the Console Window

...use Chrome.  Details.  (You should go to that page before reading further -- it is worth it.)

How to reference an element of an HTML document by id (and change it)

 <p id="id1">If you see this message, something ain't workin'.</p>
<script>
 document.getElementById ('id1').innerHTML = 'If you see this message, things are good!'; 
 document.getElementById ('id2').innerHTML 
        = 'But this line won\'t have any effect and shouldn\'t show up.';
</script>
<p id="id2">Note that the Javascript call must FOLLOW the element to have an effect.</p>

Test

Note that the browser reads the lines in order, so Javascript code doesn't affect subsequent HTML lines.  So if you want to do something to an HTML line, be sure your Javascript call to do that happens later.

This example also shows how to alter an attribute of an element:  element.attribute = ...;  How did I know innerHTML was valid?  More on that below.

For more, see Ullman, p. 340.

...by class

<p class="special">S1</p> <p>T1</p> <p class="special">S2</p>
<script>
 'use strict' //We always do this

 document.write("<p>Here's what's marked 'special' (should be S1S2): <p>");
  var specials = document.getElementsByClassName ('special'); //Get 'em
 for (var i = 0, count = specials.length; i < count; ++i)    //Loop 'em
   document.write(specials[i].innerHTML);                    //Print each one
</script>

Test

Note that this function returns an array, since there can be multiple things with the same class.  OK, I lied:  it returns a NodeList.  But since you can index that just as you can an array, close enough.

For more, see Ullman, p. 340.

...by tag name

document.getElementByTagName (tagName) returns a NodeList of all elements in the HTML document that have that tag.

 <h2>Table of Contents</h2>
<ol id="toc"></ol>                                         <!-- This will be filled in by the script, with headings -->
                                                           <!-- Here are the headings -->
<h3>When to use PHP</h3><p>When you want to construct a web page</p>
<h3>When to use Javascript</h3><p>When you want to alter and thereby enhance a web page</p>
<h3>When to use Java</h3><p>When you want your web pages to load very very slowly</p>

<script>
 'use strict' //We always do this

 var headings = document.getElementsByTagName ('h3');       //Get all headings
 var entriesForTOC = '';                                    //A string to hold them in <li> format
 for (var i = 0, count = headings.length; i < count; ++i)   //Loop 'em
  entriesForTOC += ('<li>'+headings[i].innerHTML+'</li>\n');// Collect 'em in a string

 document.getElementById ('toc').innerHTML = entriesForTOC; //Now put it at the top, as TOC
</script>

Test

For more, see Ullman, p. 340.

...by shortcut (skip this if you like)

You can reference a particular image (say) by index (document.images[0]) or by name (document.images['imgName']) , provided the image has the "name" field, which we rarely use, set.

 <p>Initially you should have links to Yahoo!, Google, and CS@LC, but then CS@LC takes over them all...</p>
<p>Go into the Google Chrome Javascript console and put a breakpoint in the code (as specified) to watch it happen.</p>
<p><a href="http://www.yahoo.com" name="Yahoo">   Yahoo!</a>
<p><a href="http://www.google.com" name="Google"> Google</a>
<p><a href="http://cs.lynchburg.edu" name="CS@LC">CS@LC </a>
<script>
  'use strict' //We always do this

  //PUT A BREAKPOINT ON THE NEXT LINE
  document.links['Yahoo'].href= document.links['Google'].href= document.links['CS@LC'].href;
  document.links[0].innerHTML = document.links[1].innerHTML  = document.links[2].innerHTML;
  //See how you can index the links array with either an int index, or the name field (if defined; see links above)
</script>

Test

For more, see Ullman, p. 337.

How to reference an attribute of an HTML element

Generally, append the HTML attribute to the element:  document.images[0].src; document.getElementsByTag('td')[0].width.  (There are two exceptions:  since for and class are reserved words in Javascript, you'd say myElement.className not myElement.class, and myLabel.forName not myLabel.for.  But those aren't commonly used anyway.)

To update styles, append style.field.  For example, to turn an element's background_color red, type
theElement.style.backgroundColor= "#FF0000"  	//note it's turned to camelCase where you have 
                      				//_ in the identifier -- go figure
						//FF0000 is hexadecimal for red

To get to the text contained in the tag, use innerHTML (not textContent or innerText), as in

theElement.innerHTML += '!!!!' //Append !!!! to the text

I read that you shouldn't use innerHTML for tables; p. 343 says so -- apparently once again it's an IE incompatibility.  Do it anyway if you like, just to get things working.

 <p>This blue line says: small checkerboard ahead</p> <!-- to be colored by Javascript below it -->
<table border="1" width="100px">
  <tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
  <tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
  <tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
</table>
<script>
  'use strict'

  var BLACK = "#000000"
  
  var ROWS = document.getElementsByTagName('tr').length //count rows in table
  for (var y = 0; y < ROWS; ++y)                        //for each row
  {
    var row = document.getElementsByTagName('tr')[y]    //extract row
    var CLMS = row.getElementsByTagName('td').length    //how long is it?
    for (var x = 0; x < CLMS; ++x)                      //for each clm in the row
    {
      var clm = row.getElementsByTagName('td')[x]       //extract clm
      if (y % 2 == x % 2)                               //and on alternate squares only
        clm.style.backgroundColor=BLACK                 //set the bkgd color to BLACK
    }
  }

  document.getElementsByTagName('p')[0].style.color='blue' 
</script>

Test

See Ullman, p. 342.

How do I set a response to an event?

This code does that, and also shows how to identify the target of the event:  the thing that the mouse is over, or is clicking on, etc.  Important events inlcude mousedown, mouseup, click, mouseover, keydown, keypress, copy, cut, paste.  For a complete list click here.

 <p>You're currently waving your mouse pointer over some "<span id="whatItIs">??</span>" tag.</p>
<script>
 'use strict'

 function addEvent (obj, type, fn) //This function will be buried in a .js file somewhere
 //and not edited -- you can just use it
 {
  //Taken from p. 276, Ullman, Modern Javascript: Development and Design
  if (obj && obj.addEventListener) obj.addEventListener (type, fn, false); //normal browsers
  else if (obj && obj.attachEvent) obj.attachEvent ('on'+type, fn); //IE
 }

 addEvent (document.body, 'mouseover', identifyElement);

 function identifyElement (e)
 {
  if (typeof e == 'undefined') e = window.event //we always do this in event handler, to make IE work
  var target = e.target || e.srcElement; //Another IE hack, so we can get the element the event relates to

  document.getElementById('whatItIs').innerHTML = target.nodeName
 } 
</script>
<!-- ...rest of body... -->

Test