Week 3: Javascript and the Document Object Model (DOM)

What is Javascript?

Javascript has historically been maligned by "real" programmers as a "fake" language, often for reasons that are no longer applicable. Since its original publication Javascript, has developed into a complex and versatile language and has been used to drive many of the most impressive web applications on the internet (GMail, Google Maps, the new Hotmail, etc.). Javascript must be used within the context of a web browser (or something built to interpret Javascript code like a web browser), but, the web browser has, of late, become one of the most popular platforms for new programs, and so this does not impose any significant limitation for our purposes.

When one goes to a webpage which uses Javascript, the source code for the program is downloaded to the user's computer. The user's machine is then responsible for interpreting and processing this code. This means that one should write Javascript code with the understanding that it may be run on a machine significantly older and slower that one's one. Also, because of security issues involved in running an external program on a personal machine, Javascript, does not allow you to write or open files (that is, you cannot save any work performed in a program written solely in Javascript). Javascript does, however, interface very nicely with other languages like PHP, which can write files. We will be looking at PHP next week.

Where does Javascript go?

You can place Javascript code in the HTML document itself or in a separate file (probably the most common professional option). If you place it in the HTML document, the code is enclosed in a <SCRIPT> tag with the attribute "language='Javascript'".

<head>
<SCRIPT language='Javascript' >
// The code on this line will be Javascript
</script>
</head>

If you want to include the javascript in a separate file, include a "src" attribute in the script tag which points to the script file.

<head>
<script type="text/javascript" src="myScriptFile.js"> </script>
</head>

The ALERT

One of the most useful commands in writing Javascript is the "alert" command, which causes the page to open a new window containg a message (a window not usually blocked by pop-up blockers). You will probably remove it from your final drafts, but it is indispensible as a debugging tool.

The syntax for the command is as follows:

alert("So much depends upon a red wheelbarrow");

In the above example, the Javascript will display two alert messages, one right after the other. Notice that I ended the line with a semi-colon; Like CSS, all commands in Javascript terminate with a semi-colon.

Variables

If you've done any programming at all, you are familiar with the concept of variables. Variables are like the style attributes in CSS. They are named entities that store a value. In a lot of programming languages, the variables have types. For instance, an integer (whole number) is stored in a different sort of variable than a float (a number with a decimal point), and both are different from a String (a series of letters and numbers). This means that it is easier to make mistakes (there is nothing on the coding side that will keep you from trying to substract 42 from Kittens), but you can code a little more quickly.

Variables are created by typing "var variableName" and set by typing "variableName = variableValue". You can also create and set a variable at the same time as shown below.

var myName="Doug";
var myAge = 28;
alert(myName);
alert(myAge);

In the above example, the variable myName is created and set to "Doug." The variable my age is created and set to 28. I then have Javascript alert me of the value of both variables. I did not put quotation marks around the value 28 because it is a number. I also left quotation marks out of the alert statements because I wanted the value of myName rather than the word "myName" to be printed in the alert box.

You can also perform arthimetic on variables. For instance:

var firstName= "Doug";
var lastName = "Reside";
var birthYear = 1978;
var currentYear = 2007;
var age = currentYear - birthYear;
var fullName = firstName+" "+lastName;
var errorCode = firstName-currentYear;
alert(age);
alert(fullName);
alert(errorCode);
alert(age++);
Note what happens. When I add words (in this case Doug and Reside with a space in the middle), Javascript concanenates the Strings. When I subtract two numbers, I get the difference. If I try to subtract anything from a String, however, I get an error. The last statement uses the "increment" symbol ++. When a variable containing a number is followed by two plus signs, it is increased by one. If it is followed by two minus signs (e.g. age--), it is decreased by one.

IF Statements

A common structure in programming is the IF statement. The IF statement marks a fork in the path of a program. The truth of a statement is evaluated, and the result determines which path the program takes.

Consider the following:

var cost = 100;
var budget = 50;
if (cost<=budget){
alert("Buy it.");
}
else {
alert("Save more money.");
}
alert("That's your answer!");
In the above example, cost is set to 100 and budget is set to 50. The program then checks to see if cost is less than or equal to budget. If it is, the user is alerted to ("Buy it"), otherwise the user is told to "Save more money."

In either case, the user is finally told, "That's your answer." Also note that the "else" statement is actually unnecessary. I could simply end after I closed the "if" statement with the curly bracket.

The statement after "if" always evaluates to a special type of variable called a Boolean (after boolean logic). A Boolean variable has only two values, "true" and "false". "True" and "false" are also reserved words in Javascript, so you even write something like this:

if (true) { alert("true"); }

Most of the time, though, you will be writing a statement which compares two things. The symbols for comparison are as follows:

< is less than
> is greater than
== equals (note that it is TWO equal signs for comparison. One equal sign is used for assigning value)
!= does not equal
<= is less than or equal to
>= is greater than or equal to
&& AND
|| OR
! NOT

Note also that the logical statement which the if statement evaluates is enclosed in parenthesis. You always need at least one pair of parentheses, but you can have more. For instance:

if ((cost<=budget)||(credit=="good")){ alert("Buy it."); }
The evaluated statement above reads, in English, "the cost is less than or equal to budget, or the value of credit is "good."

You can also allow for more than two scenarios using an "else if" statement as follows:

if ((cost<=budget)||(credit=="good")){
alert("Buy it.");
}
else if (!(credit=="bad"))
{
alert("Be nice to creditors, then try.");
}
else{
alert("Save more money.");
}

Loops

Another common structure in programming is the loop. There are many types of loops, but the most common are "WHILE" and "FOR" loops. WHILE loops instruct the program to do something until some condition is met. FOR loops tell the program to do something to every one of a set of something. Javascript's syntax for loops is based on that used in Java (which is, in turn, based on C). The syntax can be confusing and highly symbolic, but once you get the hang of it it can be written very quickly.

Consider the following examples

for (var counter=0;counter<5;counter++){
alert(counter);
}
counter = 0;
name="Sherlock Holmes";
while (name!="Doug"){

if (counter==2){
name="Doug";
}

alert (name+" "+counter); counter++
}
In the above example, the first loop, a FOR loop, begins by creating a variable called counter and intially setting it to 0. The computer is then instructed to do everything in the curly brackets over and over again as long as counter is less than 5. However, each time the program goes through the code in the curly bracket, the variable counter will be increased by 1 (remember, a variable which contains a number, when followed by two plus signs, is increased by one).

In the second loop, the program will continute to execute the code in the curly brackets as long as the variable name does not equal "Doug" (at the beginning of the loop, name is set to "Sherlock Holmes"). Within the loop, the variable counter is checked to see if it equals 2. If it does, name is set to "Doug." In any case, counter is incremented by one at the conclusion of each lap through the loop.

Functions

You will eventually want to separate sections of code into chunks known as "functions." Functions are named block of code which are not run until they are called from within the program. Functions often have input variables which are set to initial value. These input variables are listed in parentheses after the function name. Consider the following:

function sayGoodnight(name){
alert("Goodnight "+name);
}
sayGoodnight("moon.");
sayGoodnight("mouse");
The above code creates a function named "sayGoodnight" with an input variable "name." When the function is called it will alert the phrase "Goodnight " followed by the value of "name." We then call the function twice. Once setting the input variable to "moon." and once to "mouse." Note that our old friend the "alert" command is, itself, a function. It take an input value, the value of which it prints in the alert box.

Functions also return a value. The function will evaluate as this value if used in a logical statement or if a variable is set to equal a function. By default the value is "null," but you can return something different with the "return" command.

Consider the following:

function square(base){
square = base*base;
return square;
} answer = square(2); alert(answer);
This function takes an input value, base, and multiplies it by itself (the mathematical definition of a square). The result is then returned. In the example, the function square is called with an input value of 2 and the result is stored in the variable "answer".

The Document Object Model

Ok, now comes the fun part. Javascript functions can also be called by user actions on the page (clicks, double clicks, mouse overs, etc.). These actions are called EVENTS, and they must be captured by the page itself. The traps for events are placed in the attributes of tags. For instance, let's create a page that throws an alert after the page loads:

<HTML>
<HEAD>
<SCRIPT>
function tickle(){ alert("he he he!"); } </SCRIPT>
</HEAD>
<BODY>
<div onclick="tickle()">
Elmo</div>
</BODY>
</HTML>
There is a relatively complete list on events at w3schools here:
http://www.w3schools.com/html/html_eventattributes.asp

Javascript can actually create HTML elements, and HTML elements can execute Javascript functions. Consider the following example:

<HTML>
<HEAD>
<style type="text/css">
.message{ background-color: cyan; } </style>
<SCRIPT language="Javascript">
function createPage(){
var pageContent = document.getElementById("pageContent");
var pageMessage = document.createElement("div");
pageMessage.setAttribute("id","pageMessage");
pageMessage.setAttribute("class","message");
pageMessage.setAttribute("onclick","clicked(this)");
pageMessage.style.color="red"; var pageText = document.createTextNode("This is a new page");
pageMessage.appendChild(pageText);
pageContent.appendChild(pageMessage);
}
function clicked(anElement){ anElement.style.color="red"; alert("clicked!"); } </script>
</HEAD>
<BODY onload="createPage()">
<div id="pageContent">
</div>
</BODY>
</HTML>

The first line (document.getElementbyId) in the function "createPage()" above gets the element with the attribute "pageContent" which we created in the BODY of the HTML.
The second line "createElement", creates a DIV element in the current page. It is not, however, attached to the page yet, so anything we put in it won't show up.
The next three lines define the attributes of the new element (in this case "id", "class", and "onclick"). Note that the function associated with "onclick" takes an input value of "this" which is a reserved word which refers to the element associated with the event.
A new text element (or node) is then defined and attached (via appendChild) as a child to pageMessage, which is, in turn, attached as a child to pageContent.

The onclick event calls the function clicked which changes the text color of an element to red. Note that the syntax for changing the CSS values of a particular element is

VARIABLENAME.style.CSSATTRIBUTE = "NEW CSS VALUE";

ASSIGNMENT FOR NEXT WEEK

Take a short text and encode it HTML. Use the <SUP> tag to create super-script footnote makers (like this1). Create a div element with id "footnote" and give it the CSS attribute of "display: none". Give the "sup" tag an onClick event which causes the div element's style to change to "display: block;" and give this div a text child with an explanatory note. Allow the footnote div to be closed (made invisible) and use the removeChild() function to get rid of the current footnote so you can display another. If you're up for a real challenge, tag the text in TEI at first, and then use an XSLT to transform it into an HTML document with an external Javascript file.

to be displayed with the text of the footnote.