JavaScript

What it is…

A Scripting language


somewhat stripped down
designed to run as part of another application
'quick and easy'

Object Oriented


Thinks of the browser, page, and page elements as a series of objects.
Objects can contain other objects
Most commands are based on manipulating these objects

Designed for use on web pages


Client side program downloaded to user's machine
Embedded within HTML of document
Runs on the CLIENT's machine, not the server
Relatively Safe… Does not allow file access, other dangerous features

Object Oriented Programming

Objects


All the components of a web page and browser are considered objects
An object can contain properties, methods, events, and other objects
You create objects in JS by placing them in a page with HTML.
Most of the things you can create via HTML are considered objects by JS.
Some the objects you will encounter:
window
document
form
textarea
button

Properties


These are the characteristics of an object
They 'feel' like variables.
Properties describe object characteristics
Properties have variable values

A JS program can read and write most properties
Example document.bgColor
document is an object
bgColor is a property of the document object
We can read the value of this object like this:
myColor = document.bgColor
That line would look at the bgColor property of the document object, and copy its value to the variable myColor.
Many properties can also be set by javascript code:
document.bgColor = myColor
This line would look at the variable myColor, copy the color value (presumably) found there, and copy that value to the bgColor property of the document object.

Different types of objects have different sets of properties
EG the document object has bgColor and fgColor properties, but a text object does not.

Properties are usually accessed through assignment statements
The properties of objects are initially set through html code. JavaScript just allows you to change some of those properties on the fly.
Use a book to get a list of the objects and their properties in JS.

Methods


Methods are the special commands that any particular object can do.
Many commands in object oriented languages are actually method.
Example:
var myName = ""; //string
var upperName = ""; //string
upperName= myName.toUpperCase();
toUpperCase is a method attached to the string object.
Because we knew that myName was a string, we could apply the string method toUpperCase() to it.
This code fragment would make a copy of myName, convert it to upper case, and put the copy in upperName. The value of myName would not change.
Methods usually end with ()
Different objects have different methods

Events


Objects can respond to changes in the environment
These events are stimuli from the user or environment
The most common event is onclick =
Usually this is followed by a javascript command or function
Often the onclick = functionName() is embedded into the html coding of a button.
EG:
<input type = "button"
name = "cmdHiThere"
value = "Click Me"
onClick = "javaScript:alert('Hi there!')">
will create a button on the page
When this button is clicked, it will pop up a small box saying "Hi there"

The Object Hierarchy


Objects can contain other objects.
"there's a fly on the wart on the frog on the branch on the limb of the tree…"
EG:
window.document.myForm.txtHithere
describes a text box called "HiThere" on a form called myForm on the document in the window.
Objects are separated by dots.
We could assign a value to this object (text boxes have a value property) like this:
window.document.myForm.txtHithere.value = "Well, Hello there"
That line would assign the string literal "Well, Hello there" to the value property of the txtHithere text box on the myForm form on the document on the window.
We could also use this syntax to get a value from the user
var address = "" ; //string
address = window.document.myForm.txtAddress.value;
Gets the value property of the txtAddress text box from the myForm form of the document of the window, and places that value in the variable address.
The importance of Naming objects sensibly…

Language components

Variables


Must be declared
Use the var statement to create a variable
Numbers and strings are treated differently, but JS usually takes care of the difference
Use eval(stringtoconvert) to convert a string to its numeric equivalent
Use numbertoconvert +="" to convert a number to a string
Global - use the var statement outside a procedure
available to all procedures
local - use the var statement inside a procedure
available only to the local procedure
If in doubt, make 'em local
usually start with lower case, upper case to distinguish words

Input and output - Through custom dialogs

General Characteristics


Relatively easy to program
These items happen one at a time, so the order is predictable
Very easy to program, but interrupts the flow of the page

The alert() function


Used to send output to user on the fly
Syntax:
alert(ValueToOutput);
Where ValueToOutput is a string value (literal, variable, or a combination)

The prompt function


Syntax:
variablename = prompt("question you are asking",defaultValue);
Where variablename is the name of a variable.
The first string value inside the parentheses is the question
The second optional value is the default value
The default value can be string, numeric, or left out altogether.

The confirm() function


Very similar to prompt, but pops up a dialog with ok and cancel buttons
Returns a true or false value only
Very good for yes / no questions
Syntax:
variableName = confirm("True / False question");
Where variableName is the name of a variable
True / False question is a question that can be answered true or false

Example of alert(), confirm(), and prompt():


<html>
<body>
<script>
var userName = ""; //string
var keepGoing = true; //boolean

while (keepGoing == true){
userName = prompt ("What is your name?", "Harold");
alert("Hi " + userName + "!");
keepGoing = confirm("Do you want to play again?");
}; //end while loop

</script>
</html>

The following boxes would be brought up one at a time…


Input and output on forms

General characteristics


Forms are the natural way to get information from the user
Forms are great ways to get input
They are limited for output, but it can be done.
Look at form elements as JavaScript objects
Copy values of objects to and from variables

TextBoxes


Use the textbox.value property
Syntax for input:
variableName = window.document.FormName.txtboxName.value
where variableName, FormName, and txtboxName are names of elements on your page or program

Syntax for output:
window.document.FormName.txtboxName.value = valueToOutput
where FormName, txtboxName are objects on your form,
valueToOutput is the value or variable you want to put in that object

Example


<html>
<head>
<script>
function copy(){
var myVal = ""; //string variable

//get value from input box
myVal = window.document.myForm.txtInput.value;

//copy value to output box
window.document.myForm.txtOutput.value = myVal;

}//end function
</script>


</head>

<body>
<form name = myForm>

Input:
<input type = "text"
name = "txtInput"
value = "">
<hr>
Output:
<input type = "text"
name = "txtOutput"
value = "">
<hr>
<input type = "button"
value = "Copy"
onClick = "copy()">

</form>
</body>
</html>


After "copy" button is clicked…


Other controls:

TextArea:


Pretty much the same as text boxes

Password :


Much like a text box, but hides password on Screen
The password IS NOT encoded or hidden within the script!!
The code that deals with the password is visible in the code.
That means that anybody who thinks to look at the source code can find the password.
(Although you could write some sort of encryption algorithm, but this could be figured out, too)
The simple answer is---- password checking programs are NOT secure in javaScript.
You'll need CGI for sophisticated password checking

CheckBoxes:


Return a true/false value for checked property
Also have a value property. The value is set at the form design time.

Selection lists


(It's really ugly)
Each item in the selection list has a value:
To get the value of the currently selected item:
varName = window.document,formName.selName.options[window.document,formName.selName.selectedIndex].value;
Where varName is the name of a variable you want to work with
formName is the name of the current form on which the selection object reides
selName is the name of the selection object

radio buttons


Basic syntax
varName = window.document.formName.radName[Index}.value
Where varName is the name of the variable in which you want to store the value
formName is the name of the form
radName is the name of the radio GROUP (remember, all items in the group have the same name)
Index is the number of the radio button in the group.
The value returned will be the value of the selected member of the group.

<html>
<head>
<script>
function checkTime(){
var timeNow = "";
var i = 0; //for loop counter
for (i=0;i<=2;i++){
if(window.document.myForm.optTime[i].checked == true){
timeNow = window.document.myForm.optTime[i].value;
alert(timeNow);
}; // end if
}; // end while
}; // end function
</script>
</head>
<body>
<form name = "myForm">
<input type = "radio"
name = "optTime"
value = "Morning">Early
<input type = "radio"
name = "optTime"
value = "Noon">Mid day
<input type = "radio"
name = "optTime"
value = "Night">Evening
<hr>
<input type = "button"
value = "click me"
onclick = "checkTime()">
</form>
</body>
</html>

Creates the following display on the page…


Example of Multiple Input / output objects:


<html>
<head>
<title>HTML Forms Sampler</title>
<script>
function readCheck(){
//Reads the check boxes and sends an appropriate response
if (document.myform.chkEggs.checked == true){
alert("You want eggs");
}//end if

if (document.myform.chkToast.checked == true){
alert("You want toast");
}//end if

if ((document.myform.chkToast.checked == false) &&
(document.myform.chkEggs.checked == false)){
alert("You don't want ANY breakfast!");
}//end if

}//end function


</script>

</head>

<body bgcolor = "lightgoldenrodyellow">
<font color = "blue">
<center>
<h1>HTML Forms Sampler<hr></h1>

<form name ="myform">

<input type = text
value = ""
onFocus = 'alert("Text Object")'><br>

<input type = button
value = "Click Me"
onClick = "alert('Command Button')"><br>

<textarea onFocus = "alert('Text area')">
This is a
Multiline
Text area
</textarea><br>

<input type =radio
name = optAmFm
value = "AM"
onclick = 'alert("AM ONLY")'>AM Station

<input type =radio
name = optAmFm
value = "FM"
onclick = 'alert("FM ONLY")'>FM Station<br>

<input type = checkbox
name = chkEggs
value = "Eggs"
onClick = readCheck()>Eggs

<input type = checkbox
name =chkToast
value = "Toast"
onClick = readCheck()>Toast<br>

<select name = selColor
//get the value of the currently selected option
onChange = "document.bgColor = this.options[this.selectedIndex].value">

<option value ="lightgoldenrodyellow">Light Goldenrod Yellow
<option value = "red">Red
<option value = "green">Green
<option value = "yellow">Yellow

</select>

</form>
</body>
</html>



When the text box is clicked:

Either the AM or FM button will highlight, but NOT BOTH!

JavaScript and HTML

Using onClick parameter of form elements


One line of javascript can be placed in an onclick parameter
example:
<input type = "button"
name = "cmdHiThere"
value = "Click me"
onClick = "alert('Hi there!')">
Note the use of single quotes inside double quotes
This is useful only for very simple programs -
Very useful in radio buttons for on-line quiz…
<html>
<head>
<title>Math quiz</title>
</head>
<body bgcolor = "lightgreen">
<form>
<h1>What is 3 + 1?</h1>
<h3>
<input type = "radio"
name = "Answer"
value = "2"
onClick = "alert('WAY too low')">
2<br>
<input type = "radio"
name = "Answer"
value = "3"
onClick = "alert('Too low')">
3<br>
<input type = "radio"
name = "Answer"
value = "4"
onClick = "alert('Perfect!')">
4<br>
<input type = "radio"
name = "Answer"
value = "5"
onClick = "alert('Too high')">
5<br>
</h3>
</form>
</body>
</html>



Inside form body


Uses <script></script> tags
<script language = "JavaScript"> will require JS.
The default script language in Internet Explorer is VBScript, which is a bit different
Hide from non-js browsers with html and JS comments, like this…
<html>
<body>
<!-- Hide the script from non-JS browsers
<script language = "JavaScript">
//my script goes here
// Stop hiding code -->
</script>
</body>

Notice the use of HTML comments as well as JS comments.
If you don't do this, non-JS browsers will read script as plain text,
and put it on the screen.

Placing code inside the body of the page causes the code to
occur AS THE PAGE IS LOADING.
This can be useful in certain circumstances
It is NOT interactive (much)

Examples:
<html>
<body>
<h1>
<script>
var userName = ""; //string
userName = prompt("What is your name?");
document.write(userName);
</script>
's custom version of my page</h1>

<hr>
<h3>Document last changed:
<script>
document.write(document.lastModified);
</script>
</body></html>

When this file is loaded, this shows up…


Then the page loads.

Through functions


Functions are defined generally in the <head></head>
They are NOT run, merely stored in memory
The function is called when another javascript statement (usually an onclick parameter) calls the function
Functions can also call other functions

Variables declared outside functions (but within <script> tags) are GLOBAL… any function can get to them
Variables inside functions live only as long as that function is active.

Javascript supports parameter passing (by value), the return statement, and recursion.
If you didn't understand that last statement, don't worry.
If you did, you can use the techniques you learned in C/C++

Functions are what allow JavaScript pages to have an interactive 'feel'
Generally, they are the best way to go

Inside an <a href></a>


This is not frequently used, but it is a powerful tool
Inside an anchor, you can use a "javascript:command" combination as an Href.
Generally this is used to call a function that has been previously defined.
This would be useful when defining an imagemap with javascript functions rather than URLs as the results
It is also useful when you want to temporarily 'turn off' a URL or test off-line.
Sometimes it is used to add "clickable" capabilities to a link


Output on a page

Writing to the current page.

document.write()


The document is the primary output device in HTML/Javascript
You can write text through a script with the window.document.write() method

Syntax:


window.document.write(text_to_write);
where text_to_write is a string value or variable.
The text can include html tags, which will be interpreted
It works fine while writing the document
For an example of this, look at the custom.html example above (Joe's page)

The problem:


The page contents are not reliable until the page has finished loading
Once the page has finished loading, you can't write to it any more!
(Except inside text areas, and a few other places)

In JavaScript, we force a page to 'finish loading' with a window.document.close() call
We have to do this so that the entire page will show up properly,
but once we do, we can't make further changes to the page.

Also, the javascript code itself is on a page. Changing the page that contains the program could cause problems with the program itself, so this is generally not allowed

The solution


You can print stuff to a document, but:
NOT the document that contains the code
The document should be written to as compactly as possible
The document should be closed as quickly as possible
the document can be in another window or another frame

Creating a new window

The window.open() method


This method allows you to create a new browser(!)
It works like the new browser command on the file menu of Netscape
The programmer has some other kinds of control

Syntax:


windowName = window.open(startingURLwindowName,,startingProperties);
where windowName is a variable name that will refer to this window object
You do NOT have to declare this variable. The window.open() will do that for us.
We will use this variable later to specify that we are writing to your custom window
startingURL is the URL where we want the browser pointed when it comes up.
In JavaScript programs we often use "" as the starting URL, because we will be writing code to populate the new window.
The second windowName is the name that will be used as a target. Many JS programmers just use the same value for both instances of the windowname.
StartingProperties is a special string used to set up various properties of the new window. We can use this string to specify whether a toolbar shows up, the size of the new window, and a few other things about it.
If you want to play with this property, get a good online or paper resource for some hints.

Writing stuff to the window

windowName.document.write()


This special variation of the document.write() method writes stuff to the window named by windowName.
It presumes that windowName has already been created with a window.open()
It is usually best to assemble everything you want to go in a page into a large string, then use one write statement to write that variable's contents onto the window.

Closing the window.document

Why it is necessary


Sometimes the results of a window.document.write() method will be immediately apparent.
This is not always the case:
If you sent <img src> information, it may not load the graphic until it has received all of the text
A windowName.document.close() function will tell the new window that everything needed to display the page has been sent.
It does NOT close the WINDOW, just the document.

Syntax


windowName.document.close();
where windowName is the name of the window object you want to close
Note, once you close the document, any subsequent writes will erase the current value!

Closing the window

What it does


Closing the WINDOW will cause the new window to disappear.
It is more drastic than a document.close()
It's considered good housekeeping, because the user shouldn't have to close windows that were opened by a program.

Syntax


windowName.close();
where windowName is the name of the window we want to close down.

Example


<html>
<head>
<title>Hi world</title>
<script>
function sayHi(){
//creates an output window to say "HI"

myWindow = window.open("","myWindow","height=100,width=100");
myWindow.height = 100;
myWindow.width = 100;
myWindow.document.write("<h1>Hi there!</h1>");
myWindow.document.close();
}
</script>
</head>

<body>


<form name = "myForm">
<input type = "button"
name = "cmdSayHi"
value = "Click Me to say Hi!"
onClick = "sayHi()">

<input type = "button"
name = "cmdHideHi"
value = "close the window"
onClick = "myWindow.close()">

</form>
</body>
</html>

Screen print:



When "Click me" button is pressed: the following window pops up as well:



Output through frames

general setup


Create a frames document
Put the html page with the javascript in the first frame
refer to the second frame as a member of the parent.frames[ ] array

Syntax


window.parent.frames[framenum].document.write(valueToWrite);
where framenum is a number for your frame (0 for first frame, 1 for second, etc).

Example:


<html>
<head>
<title>Timer demo</title>
<!-- uses frames for timer output -->

<script>
counter = 0; //global counter integer

function countit(){
counter++; //increment counter

//send stuff to the other frame...
window.parent.frames[1].document.write("<h1>");
window.parent.frames[1].document.write(counter);
window.parent.frames[1].document.write("</h1>");
window.parent.frames[1].document.close();

if (counter <10){
//call this function again (recursively!)
timerID = setTimeout('countit()',1000);
}; // end if
} // end function

</script>
</head>

<body>
<h1>This page counts in the other frame!</h1>

<script>

countit();

</script>
</h1>
</body>
</html>

(The value in the second frame changes on the fly!)

JavaScript Project


Write a mad - lib game in javascript.
Mad-libs, as you may remember, are those games that ask you for a bunch of words with certain characteristics, and then uses those words to fill in a story. Depending on the words that were entered, the story could be silly, funny, or serious.

The page should use text boxes to input a bunch of variables
At least one variable should come from a radio or selection box
(this could be even a graphic!)
Once the variables have been gathered from the text boxes, merge them with text to make a story.
Put the story either in a frame or a new window. If it goes in a new window, add a close button.