Seminar 2

Introduction to JavaScript

© M. Firebaugh

I. Topics:

II. What Defines a Language?

III. JavaScript Syntax Summary

An Excellent Tool for Editing and Verifying JavaScript Commands is the Netscape JavaScript Console

  1. Choose Open "Location in Navigator"
  2. Type javascript: into query box

1. JavaScript is an interpreted language (like Basic or LISP) for embedding in HTML documents.

2. The syntax ("rules of the language") closely resembles that of C++.

3. JavaScript is case sensitive (unlike HTML)

4. JavaScript ignores white space (like HTML)

5. JavaScript recognizes (and gets confused by) hard returns (i.e., all commands must be on one "logical line")

6. All punctuation symbols ( { [ " ' ... ' " ] } ) must come in pairs and close properly

7. The backslash, "\" serves as the Escape Key to ignore characters following

8. JavaScript statements are separated by the semicolon symbol, ";" 9. JavaScript scripts are a series of statements of the form:

command  (attributes);


window.alert ("You are entering the strange JavaScript World.");

10. Comments are of two forms:

//This is a comment up to the end-of-line


/*Comments may also be enclosed between "/*. . . .*/" compound symbols.  */


11. Command Blocks are enclosed in "{ . . . }", e.g.

{document writeln  ("Greetings  &{userName};!"); document
 writeln  ("Select a manu option:");}


12. Functions may be defined as a series of statements, e.g.

function Greeting  (userName,dayPart) {
document.writeln("Greetings "+ userName + "!<br>");
document.writeln( "Have a good " + dayPart + ".<br>")}


13. JavaScript recognized a number of built-in events:


14. JavaScript provides a number of methods for handling events

15. JavaScript supports standard C++ arithmetic and logical operators

IV. JavaScript Nomenclature

Nomenclature (Naming convention) involves three components:

JavaScript reserves 60 "Key words"

abstract false interface super
break final long switch
byte finally native synchronized
case float new this
catch for null throw
char goto package throws
class if private transient
const implements protected true
continue import public try
default in return void
do instanceof short while
double int static with
extends var function boolean
debugger delete else typeof
enum export comment  label

These reserved words are classified as follows:

These are reserved for programming commands and NOT available for use as variable or function names.

Object naming conventions

Here we require the Document Object Model (DOM) for an understanding of naming conventions. For example, a partial Netscape 4.0 DOM would look like:  ("controlWindow")
document.write("Come on in.  The water is fine!")


V. JavaScript Input/Output

Three principle modes of output are

Alert Boxes

The script to do this in an HTML document is:

<script language="JavaScript1.2"><!--
alert("Hi, there)
// -->

Let's see what the following JavaScript code will do:

<script language="JavaScript1.2"><!--
alert("Hi, there,direct from the head")
// -->
<body  onLoad="alert('This is an Alert Box fired by onLoad event')">
<script language="JavaScript1.2"><!--
alert("Hi, there, now from the body!")
// -->

Head, body, and event-driven Alert boxes


This method acts on the document object to print an in-line message.

Consider the output produced by the following code:

<title>Welcome to Adobe GoLive 4</title>
<script language="JavaScript1.2"><!--
document.write("This is output produced by document.write in the head.")
// -->
<script language="JavaScript1.2"><!--
document.write("This is output produced by document.write in the body.") 
// -->

document.write messages

Status bar output

This output mode seems to be used primarily with the anchor link tag and mouseOver and mouseOut events. Consider the code:

<h1>Demonstration of output via the Status Bar</h1>		
<a href="
firebaugh.www/firebaugh.html" onMouseOver="window.status=
'M.Firebaugh Home Page';return true"
onMouseout="window.status='Return to Seminar 2';return
true">Go to Firebaugh Home Page</a>	

The interesting results are shown in:

Status Bar Output

JavaScript Input

Two modes of JavaScript input include:

Prompts for Input

The general syntax for the Prompt Command is:

var  variable_name = prompt('Message on the box","Default Reply")

Example 1: The script

<script language="JavaScript1.2"><!--
/* This is an example of a prompt. */
var userName=prompt("Write your name in this box","Name here.");
document.write("Hello "+userName+". Welcome to my page!");
// -->


Prompt Greetings

Example 2: Prompts can input numerical as well as string information. Consider the script:

var hourWage=prompt("Please enter your Hourly Wage:","Dollars/Hour");
document.write("Your annual income is $"+2000*hourWage+".");

which produces:

Annual Salary Calculator

Forms for Input

Forms are a great way to collect data, and JavaScript is ideal for form verification. Consider the code:

<script language="JavaScript1.2">
	function writeReport()		
	alert("Employee " + document.myform.yourName.value + 
	" earns $" + 2000*document.myform.yourWage.value + ".00 per year.")


	<form name="myform">
	<H1>Employee Salary Computer</H1><br>
	<p>Your Name:  <input type="text" name="yourName" size="35" 
	value="FirstName LastName"></p><br>
	<p>Your Wage:  <input type="text" name="yourWage" size="35" 
	value="Your Hourly Wage Here"></p><br>
	<p><input type="reset"> <input type="button" value="
	Then Click Here" onClick="writeReport()">

Let's see what this produces:

Salary Calculator Form

VI. JavaScript Variables and Expressions

1. JavaScript data types include

2. JavaScript supports variables, with names starting with letters or the (_)

var x,y,z
var home_town
var myAddress

3. JavaScript support standard programming operators and expressions, e.g. the "verbs" of the language

fred = 85
fred  <  100
fred =  fred  +  2
if  (fred  >  80  &&  fred  <  90)  { window.alert  ("You have a B average.")}

 The comparison operators include

Symbol Description
== Equals
!= Does not equal
> Is greater than
>= Is greater than or equal to
< Is less than
<= Is less than or equal to

4. JavaScript data types are readily tested, compared, and interconverted

3 + 3                    // result = 6
3 + "3"                  // result = "33"
3 + 3 + "3"              // result = "63"
(3 + 3 + "3").length     // result = 2
parseInt("63")           // result = 63
parseInt("63.6667")      // result = 63
("" + 2500)              // result = "2500"
('' + 2500).length       // result = 4
typeof (3 + 3 + "3")     // result = string
typeof (3 + 3 + 3)       // result = number
typeof (3 > 9)           // result = boolean
10 == 10                 // result = true
10 == 10.0               // result = true
"fred" == "Fred"         // result = false
"fred" < "Fred"          // result = false
"Fran" == "Fred"         // result = true
isNaN(53406)             // result = false
isNaN("WI")              // result = true

Notice how "strings tend to win"

VII. JavaScript Control Structures

The Dutch computer scientist, Edsger Dijkstra, has shown that the three essential control structures are:

Iteration (looping) Structures

Repeat (for) loop

The syntax is

for ([initial expression];[condition];[update expression]) {


for (var i = minValue; i <= maxValue; i++){

The while loop

The syntax is:

while (condition) {


var i = 0
while (i <= 100) {
   tab[i] =  i * i

The do-while Loop

The syntax is:

do {
}  while (condition)


var i = 0
do {
   tab[i] =  i * i
} while (i <= 100)

Decision (branching) Structures

if Decisions

The syntax for simple if statements is:

if (condition) {


if (score < 50) {
   courseGrade = "F"

if...else Decisions

The syntax for if...else statements is:

if (condition) {
} else  {


if (score < 50) {
   document.write("You fail")
} else  {
   document.write("You pass")  

switch/case Decisions

The syntax for switch/case statements is:

switch (expression) {
  case label1:
  case label2:

VIII. JavaScript Object Properties

JavaScript provides functions for evaluating many of the objects of interest to Web Page Designers. Among these objects are the Math Object, the Date Object, the History Object, the Document Object, and the Navigator Object.

The Math Object

Classic HTML has virtually no math capabilities (only <SUP> and <SUB> tags). Consider the following JavaScripts:

pi=Math.PI          // Returns   3.141592653589793
root2=Math.SQRT2    // Returns   1.4142135623730951
big=Math.max(45,56,23,43,15)     // Returns   56
rtp=Math.pow(5,4)   // Returns  625
die=Math.round(Math.random()*6)  // Returns   5,0,6,3,6,2,4
betterDie=Math.round(Math.random()*6+.5)     // Returns   5,1,6,3,6,2,4

The Date Object

There is a single Date object with several associated methods. Calling it produces:

now=new Date()       // Returns   Tue Aug 22 19:22:41 GMT-0700 (2000 

The associated methods produce:

now.getFullYear()    // Returns   2000
now.getMonth()       // Returns   7
now.getDay()         // Returns   2
now.getHours()       // Returns   19
now.getMinutes()     // Returns   22
now.getSeconds()     // Returns   41

Note: getMonth returns 0-11 for January-December, so must increment by 1.

Note: getDay returns 0-6 for Sunday-Saturday, so must increment by 1.

The History Object

The History Object allows us to navigate forward and backward through the Web Pages of our current session. Consider the script:

		<input type="button" value="BACKUP " onclick="history.go(-1)"> 
		<input type="button" value="FORWARD" onclick="history.go(1)">

This produces:

History Navigator

The Document Object

The Document Object supports the method, write(), and the properties: alinkColor, bgColor, fgColor,linkColor,lastModified,location,referrer, title, and vlinkColor.

<body bgColor=yellow fgColor=red>
	<H1>Document Property Report</H1>
	<script language="JavaScript1.2">
		document.write("<BR>Background color = " + document.bgColor)
		document.write("<BR>Foreground color = " + document.fgColor)
		document.write("<BR>Active Link color = " + document.linkColor)
		document.write("<BR>The URL for page = " + document.location)
		document.write("<BR>Document modified on = " + document.lastModified)


Document Properties Report

The Navigator Object

The code:

<h1>Browser Report</h1>
<script language="JavaScript1.2"><!--
  document.write("You are using " + navigator.appName + ".<BR>")
  document.write("It is version " + navigator.appVersion + ".<BR>")
  document.write("Its code name is " + navigator.appCodeName + ".<BR>")
  document.write("It sends the header " + navigator.userAgent + ".<BR>")
// -->


Browser Report

IX. JavaScript Examples

Example 1: JavaScript to modify a document's properties

The following code:

<title>Function Backgound Color Change
<script  language=javascript>
function changecolor(newcolor){   
    window.document.bgColor = newcolor;

<body bgcolor=white link=#888888 vlink=#888888><h2>
<a  href="javascript:changecolor('black');"> 
Change Background to Black</a></h2>
<h2><a  href="javascript:changecolor('white');"> 
Change Background to White</a></h2>
<h2><a  href="javascript:changecolor('yellow');">
Change Background to Yellow</a></h2>
<h2><a  href="javascript:changecolor('magenta');">
Change Background to Magenta</a></h2>


Change Background Color 

Example 2: Simple Rollover using Links

The code:

<a href="next.html" onMouseout="document.arrow.src='blueArrow.GIF'" 
<img height="78" width="201" src="blueArrow.GIF" border=0 name="arrow"></a>


Arrow Rollover

Example 3: Building Slideshows

The code:

<script language="javascript" type="TEXT/JAVASCRIPT"><!--
myPix = new Array("images/Tetons1.jpg","images/Tetons2.jpg","images/Tetons3.jpg",
thisPic = 0
imgCt = myPix.length - 1
function processPrevious() {
	if (document.images && thisPic > 0) {
function processNext(){
	if (document.images && thisPic < imgCt){
// -->
<body bgcolor="white">
<h1><font color="#0000ee">The Tetons in Winter</font> 
<img src="images/Tetons1.jpg" name="myPicture"></h1>
<p><a href="javascript:processPrevious()">&lt;&lt; Previous</a> <a href="javascript:processNext()">Next &gt;&gt;</a></center>


Teton Slideshow

Example 4: onMouseover Slideshow 

Air show

Plane 1

Plane 2

Plane 3

Plane 4

Plane 5

This example was borrowed from Website Abstraction, a great source of free JavaScripts

Example 5: onMouseover Rollover  

Firebaugh Home Page



Dynamic HTML The Definitive Reference by Danny Goodman, O'Reilly & Associates, Sebastopol, CA (1998)

JavaScript for the World Wide Web (Third Ed.) by Tom Negrino and Dori Smith, Peachpit Press, Berkeley, CA (1998)

JavaScript Bible (Third Ed.) by Danny Goodman, IDG Books, Foster City, CA (1998)

JavaScript The Definitive Guide (Third Ed.) by David Flanagan, O'Reilly & Associates, Sebastopol, CA (1998)

JavaScript Goodies by Joe Burns & Andree Growney, Que Earthweb Press, Indianapolis, IN (1999)

JavaScript Application Cookbook by Jerry Bradenbaugh, O'Reilly & Associates, Sebastopol, CA (1999)

Web Sites URLs

Cross Browser Events for Dynamic HTML by James Robertson

The Minimalist Approach to Dynamic HTML by James Robertson