
Jump to Topic Links
Document.write("Hello World")
results in the puzzling error message "Document object does not exist." However, the only problem is the uppercase D. This statement:
document.write("Hello World")
works fine.
JavaScript changes! Like everything else on the Internet, JavaScript is always evolving and changing. Therefore, the Internet itself is your best resource for current information.
Operators "operate" on values. You deal with operators every day in your regular life - you probably just never heard them called that. For example, everyone knows that 1+1=2. In that statement, the + sign is the operator. JavaScript offers many operators beyond the basic ones used in arithmetic.
Though specific rules of syntax vary with some operators, the typical syntax is
variable operator value, ex. joe = 2
where variable is the name of a variable used to store a value, value is a number, string, value, expression, or property of an object, and operator is one of the operators described here.
The sections that follow group JavaScript into classes based on the type of operation performed:
Arithmetic operators act on numbers. Table 1 lists the arithmetic operators offered in JavaScript and provides examples of each.
Table 1: JavaScript's Arithmetic Operators.
| Operator | Used For | Example | Equals |
| + | Addition | 1+2 | 3 |
| - | Subtraction | 12-10 | 2 |
| * | Multiplication | 2*3 | 6 |
| / | Division | 10/3 | 3.3333333333 |
| % | Modulus(remainder) | 10%3 | 1 |
| ++ | Increment(add one) | x=5 x++ |
x=6 |
| -- | Decrement(subtract one) | x=5 x-- |
x=4 |
| - | Unary negation | -20 | negative 20 |
The modulus of a number is the remainder after the first division. For example, 10/3 results in 3, remainder 1. The modulo (%) operator returns that remainder, 1.
The increment operator, ++, is just a shortcut way of saying variable + 1. For example, the two statements that follow mean exactly the same thing. The latter one is just shorter and quicker to type: x = x + 1 x++
The same holds true for the decrement (--) operator.
With the negation operator, if the minus sign is used in front of a value without being
part of a larger expression, then JavaScript assumes it indicates a negative number, just
as in day-to-day arithmetic. For example x = 5; y = -x; results in x being equal to 5 and y
being equal to -5. (Note: the semicolon, ; , denotes the end of one statement. Javascript does not require that you put a semicolon at the end of each statement but it is a good idea)
To assign a value to a variable, use the simple = operator with the syntax
variablename = value
The = operator means is set to the value of and is the most common operator in javascript.For example x=15;
y=20;
z=x+y;
After all three lines have been executed, the variable x contains the number 15, the variable y contains 20, and the variable z contains 35 (the sum of 15+20).
Some shorthand operators exist that you can use to do some arithmetic and assign the result to a value in one fell swoop. Those operators are shown in Table 2. If these are confusing for you, you can ignore Table 2 and use the "longhand" way of doing them.
Table 2: JavaScript's Assignment Operators.
| Operator | Example | Means |
| = | x=3 | is set to |
| += | x+=y | x=x+y |
| -= | x-=y | x=x-y |
| *= | x*=y | x=x*y |
| /= | x/=y | x=x/y |
| %= | x%=y | x=x%y |
Comparison and logical operators compare two values and return either true or false. These are valuable for comparing things and are often used with if statements. Table 3 lists the comparison operators. Table 4 displays the logical operators:
Table 3: JavaScript's Comparison Operators.
| Operator | Meaning | Example |
| == | is equal to | 10==3 is false |
| != | does not equal | 10!=3 is true |
| > | is greater than | 10>3 is true |
| >= | is greater than or equal to | 10>=3 is true |
| < | is less than | 10<3 is false |
| <= | is less than or equal to | 10<=3 is false |
Table 4: JavaScript's Logical Operators.
| Operator | Meaning | Example |
| && | AND | (x = 10) && (y < 10) is true |
| || | OR | (x=10) || (y=10) is true |
| ! | NOT | x !=y is true |
A string is a chunk of text, such as hello, rather than a number such as 10. In Javascript, strings must be surrounded by quotes, either double, "stringgoeshere" or single, 'stringgoeshere'. Variables do not have quotes. Unlike numbers, you cannot add, subtract, multiply, and divide strings. Example: 2*3 = 6 is fine. But what is "Hello" * "Dudes"? The question makes no sense.
You can, however, concatenate strings, which is a fancy name for "stick them together." You use the + operator to concatenate strings. Here is an example where we create three variable, x, y, and z, all of which contains strings:
x="Hello"
y="Dudes"
z=x+y
The result is that z now contains HelloDudes. Notice that you put quotes around "Hello" and "Dudes" 'cause they are strings but not around x and y 'cause they are variables.
Why is there no space between the words HelloDudes? Because to a computer, strings are just meaningless strings of characters. To a computer, the string hello in no more meaningful than the string ghfkredg. They are both just strings. If you want to add a space between the words, you can pop a space into the expression. A literal space would be a space enclosed in quotation marks (" "). Hence, this series of commands x="Hello" y="Dudes"
z=x+" "+y
results in z containing Hello Dudes. A shortcut operator also exists for string concatenation +=. For example x="Hello" y="Dudes"
x+=" "+y
in which case x equals itself with a space and y tacked on. Ergo, x
then contains Hello Dudes.
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. The operators for a conditional expression are ? and : using this syntax:
myvar = (condition) ? value1 : value2
For example, the conditional expression that follows is a shorthand way of saying "If the variable named gender contains F, then put the string 'Ms.' in the variable named salutation. If the variable named gender does not contain F, then put the string 'Mr.' into the variable named salutation":
salutation = (gender=="F") ? "Ms." : "Mr."
JavaScript operators follow the standard order of precedence. But you can override natural precedence with parentheses. For example
5+3*10
equals 35 because the multiplication is naturally carried out first (according to the rules of precedence). That is, the machine first evaluates 10*3, which equals 30, and then adds 5 to that to get 35.
This expression has a different result:
(5+3)*10
This expression results in 80 because the parentheses force the addition to be carried out first (5+3 equals 8). That result then is multiplied by 10 to result in 80. Table 7 shows the order of precedence of the operators, from highest to lowest, when you do not use parentheses in an expression. Operators at the same level of precedence within an expression are carried out in left-to-right order.
Table 7: JavaScript Operators Order of Precedence.
| Action | Operator(s) |
| call, member | (),[] |
| negation/increment | ! ~- ++ -- |
| multiply/divide | * / % |
| addition/subtraction | + - |
| bitwise shift | << >> >>> |
| comparison | < <= > >= |
| equality | == != |
| bitwiseAND | & |
| bitwise XOR | ^ |
| bitwise OR | | |
| logical AND | && |
| logical OR | || |
| conditional | ?: |
| assignment | = += -= *= /= %= <<= >>= >>>= &= ^= |= |
| comma | , |
These comments identify commands within JavaScript code. To use them, you must place them between the <SCRIPT> ... </SCRIPT> tags. Comments are used by programmers to leave notes for themselves and anyone who reads their scripts about what they wrote. You will need to comment out your exercises in this class. Comments are ignored by browsers.
This comment
// comment
is a single-line comment where comment is any one line of text, whereas
/* comment */
is a multiple-line where comment is any amount of plain-English text.
<!-- comment
code
// comment -->
This preceding example shows the hide comment, where comment is any (optional) text and code is JavaScript coding. This comment hides JavaScript code from non-JavaScript browsers.
<SCRIPT Language = "JavaScript">
<!-- This will start hiding code from non-JavaScript browsers.
//This is a comment, and will be ignored.
document.write ("Hello World")
/*Here's a two line comment that will
be ignored */
document.write ("Goodbye World")
// and this stops the hiding -->
</SCRIPT>
This is a built-in array that contains one element for every anchor in the current Web page.
The syntax for the anchor object is
document.anchor[n]
where n is some number representing an item's position in the list. Alternatively, you can use
document.anchor.length
to identify the number of items in the list.
.length identifies how many items are in the anchors array.
When your page is displayed to a reader, the anchors array creates an element for each anchor in the page. The first anchor is anchor[0], the next is anchor[1], and so forth. The anchors.length value reflects the number of items in the array.
The actual name of the anchor is always null. That is, you cannot use the anchors array to discover an anchor's name. You also cannot create an anchor programatically. For example, the statement anchor[0]="howdy" does nothing.
The anchor object is a property of the larger document object.
The custom function in the following listing returns true if the current page has at least one anchor in it. It returns false if the page contains no anchors.
function hasAnchors() {
retval = true
if (document.anchors.length == 0) {
retval = false
} return retval
}
Arrays are groups of objects. Each array is given a variable name which is set to a new Array. After you create the Array, you put the objects of the Array into parenthesis following the reserved word Array.
variablename = new Array("arrayobject1", "arrayobject2", "arrayobject3", etc.)
Array index number refers to each objects place in the comma seperated list of objects. Javascript starts counting with 0, so arrayobject1 above would have an index number of 0. To call any object in an Array you call it by its index number using square brackets []. So:
You can use the Array object to store a list of values that can be called later by their Array index number. This can be valuable in many applications. For example, the getMonth() method of the Date object returns a number from 0(January) to 11(December). We rarely want the number of the month, but if we set up an Array of month names, we can cause the script to convert month numbers to month names.
This statement immediately terminates an ongoing for or while loop.
The syntax for the break statement is
break
The break statement can be used only within the curly braces following a for or while loop. When executed, break terminates the loop and breaks you out of the curly brackets to the first statement after the loop's closing curly brace (}).
The checkit() function below looks at each character in a string (lstring). If it finds a character that matches the character stored in onechar, it sets the variable retval to true and stops looking.
function checkit(onechar,lstring) {
retval = false
for (var i=1;i<=lstring.length;i++) {
if (lstring.substring(i,i+1)==onechar) {
retval=true break
}
}
return retval
}
This object refers to a clickable button on a form.
The syntax for the button object is
<INPUT type="button" value="button text">
where button text is the text that appears on the button face. The <INPUT...> tag must be placed within a pair of <FORM>...</FORM> tags. The INPUT tag can also contain other INPUT attributes, including JavaScript event handlers.
.name reflects the NAME attribute in the <INPUT> tag
.value reflects the VALUE attribute in the <INPUT>
tag
.click() Clicks the button
onClick Triggered when the reader clicks the button. (Note: the Submit object in a form also looks like a button but uses the onSubmit event handler.
Use button and the onClick event handler in the <INPUT> tag of a form - not in JavaScript code. The <SCRIPT>...</SCRIPT> tags are not required but the <FORM>...</FORM> tags are.
The button object is a property of the larger form object.
The following example displays on a button on the reader's Web page that says Click Me on its face. When the reader clicks the button, an alert message says Hello Dude!
<HTML><BODY><FORM name="OneButt">
<INPUT type="button" value="Click Me" onClick = "alert('Hello Dude!')">
</FORM></BODY></HTML>
Run the example
In an <INPUT> tag, this object specifies a checkbox form field. In JavaScript, it refers to a checkbox on a form.
The following line
<INPUT type="checkbox">
when placed between a pair of <FORM> tags, puts a checkbox on the current form. The statement also can contain other INPUT attributes, including the CHECKED, NAME, and VALUE attributes, and a JavaScript onClick event handler.
.checked true if box is checked, false if box is clear
.defaultchecked Reflects the CHECKED attribute of the <INPUT> tag
.name Reflects the NAME attribute of the <INPUT> tag
.value Reflects the VALUE attribute of the <INPUT>
tag
.click() Clicks on the checkbox.
onClick Triggered when the reader clicks on the checkbox
To create a checkbox, use the TYPE="checkbox" attribute in an <INPUT> tag between a pair of <FORM>...</FORM> tags.
Use event handlers within the <INPUT> tag to trigger a script when the reader clicks on the checkbox.
In the following example, the areyasure() function displays an alert message. However, that function is called up only if the reader opts to pay now by credit card when presented with the form. Note the <INPUT ... TYPE="checkbox"> tag and its onClick property that calls up areyasure() only if the checkbox is checked. Notice the this word in the conditional if statement. The this reserved Javascript word always refers to the object on the page that you are within, in this case the checkbox named creditcard. You could have also identified the checkbox by the full dotted syntax of document.payment_method.creditcard. In this case, the if conditional would have been if(document.payment_method.creditcard.checked) etc..
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function areyasure() {
alert("Think twice. This is not a secure web site!")
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="payment_method">
<INPUT TYPE="checkbox" NAME="creditcard" onClick="if (this.checked) {areyasure()}">
Pay now by credit card
</FORM>
</BODY> </HTML>
Run the example code
Here's another example where a custom function named clearCheckbox() automatically removes the checkmark from a checkbox by settings its checked property to false. The function is called when the reader clicks the checkbox named keep:
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function clearCheckbox() {
if (document.cake.eat.checked) {
document.cake.eat.checked = false
alert ("Can't have cake and eat it too")
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="cake">
<INPUT type="checkbox" name="eat"> I want to eat my cake.<P>
<INPUT type='checkbox' name='keep' onClick = 'clearCheckbox()'> I want to keep my cake
</FORM>
</BODY>
</HTML>
Run the example code
(Note: You could just use radio buttons without Javascript instead in this example since they only allow you to select one or the other button)
You can use the color values in the HTML book with Javascript although you will find that Javascript recognizes more color "names" like purple, etc. than does HTML.
You can change the background color of a document at any time by setting document.bgColor to a new color. However, you cannot change any foreground colors - fgColor (TEXT), alinkcolor, and so on - if the page has already been written and is displayed on the screen. To change foreground colors, you need to close the input stream to the document (document.close()), open a new document (document.open(), and rewrite the entire page with new color values in the <BODY> tag of the page.
This little page shows a button that, when clicked, changes the background color of the current page from pink to purple or vice versa. Note that the JavaScript if() statement still requires the hex number with a pound sign - '#ffc0cb' rather than 'pink'. Since the Javascript color names and HTML color names are different, I usually use hex with Javascript.
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function reversecolor() {
// The if statement still requires the triplet.
if (document.bgColor == '#ffc0cb') {
document.bgColor = 'purple'}
else {
document.bgColor = 'pink'
}
}
</SCRIPT>
<BODY bgColor = 'pink'>
<FORM>
<INPUT type = "button" value="click me" onclick="reversecolor()">
</FORM>
</BODY>
</HTML>
Run the example code
This statement terminates the remaining statements in a for or while loop and continues execution at the top of the loop (the next iteration of the loop).
The syntax for this statement is
continue
The continue statement makes sense only within the curly braces of a for or while loop. Unlike the break statement, continue passes control back to the top of the loop. It does not terminate the loop. In a for loop, continue jumps back to and executes the increment-expression. In a while loop, continue jumps back to and evaluates the condition statement.
Opening the following page
<HTML>
<BODY>
<SCRIPT Language = "JavaScript">
i=0
while (i < 10) {
i++
if (i/3 == parseInt(i/3)){
continue
}
document.write ("i=",i,"<BR>")
}
</SCRIPT>
</BODY>
displays this on the Web browser screen.
i=1Numbers that are evenly divisible by three (3, 6, 9) are omitted because the if() statement in the while loop forces the loop to start over, without getting to the document.write() statement, when the value of i is evenly divisible by 3. The method(actually a Javascript upper level function), parseInt, converts a non-integer value into an integer(one number, no fractions). So, whenever i/3 divides to an integer the loop does not document.write() but loops back to the top.
This object defines a date/time as the number of milliseconds since January 1, 1970, an arbitrary start date. Of course, we rarely care how many milliseconds it has been since then although it tells you how long since Rholl has been a sophomore in high school. So, the way to use dates is to create a new Date object and use one of the methods to either get date info from the computers clock(very common) or set date info for later use in a script(less common).
To create a new date object, use the following syntax:
dateObjectName = new Date
where dateObjectName is a new variable that now contains the properties(month, hours, year, etc.) of the current time.
To use Date methods, follow this syntax
dateObjectName.methodName(optional parameters)
where dateObjectName is either the name of your created Date object and methodName is one of the methods listed in the following section.
.getDate() Returns the day of month (1 to 31)
.getDay() Returns the day of the week from 0 (Sunday) to 6 (Saturday)
.getHours() Returns the hour from 0 (midnight) to 23 (11:00 PM)
.getMinutes() Returns the minute from 0 to 59
.getMonth() Returns the month from 0 (January) to 11 (December)
.getSeconds() Returns the seconds (0 to 59)
.getTime() Returns the milliseconds transpired since 1/1/70
.getTimezoneOffset() Returns the difference between local time and GMT (meridian time)
.getFullYear() Returns the year, such as 2001
.parse(string) Converts a string in Dec 25, 2000 to the number of milliseconds transpired since 1/1/70
.setDate(num) Sets the day of an existing object to num where num is a value between 1 and 31
.setHours(num) Sets the hour of an existing object to num where num is a value between 0 and 23
.setMinutes(num) Sets the minutes of an existing object to num where num is a value between 0 and 59
.setMonth(num) Sets the month of an existing object to num where num is a value between 0 and 11
.setSeconds(num) Sets the seconds of an existing object to num where num is a value between 0 and 59
.setTime(num) Sets the date and time of an existing object to num where num represents the number of milliseconds transpired from 1/1/70
.setYear(num) Sets the year of an existing object to num where num is a value between 70 and 99
.toGMTString(dateobject) Converts the dateobject to a string expressed in Internet GMT format
.toLocaleString(dateobject) Converts the dateobject to a string expressed in local date/time format
.UTC(year, month, day [, hrs] [, min] [, sec])
Converts date/time values expressed in Universal Coordinated Time values to the number of
milliseconds transpired since 1/1/70
Opening the following page on March 31, 2003, at approximately 4:30 pm
<HTML>
<BODY>
<SCRIPT Language="JavaScript">
today = new Date
document.write ('today = ',today,'<br>')
document.write ('today.getDate() = ',today.getDate(),'<br>')
document.write ('today.getHours() = ',today.getHours(),'<br>')
document.write ('today.toGMTString() = ',today.toGMTString(),'<br>')
document.write ('today.toLocaleString() = ',today.toLocaleString())
</SCRIPT>
</BODY>
</HTML>
would display this in the Web browser document:
today = Mon Mar 31 16:30:38 CST 2003
today.getDate() = 31
today.getHours() = 16
today.toGMTString() = Mon, 31 Mar 2003 16:30:38 UTC
today.toLocaleString() = Monday, March 31, 2003 4:30:38 PM
The document object represents the entire page currently on display in the Web browser.
The syntax for the document object is
document.propertyName
or
document.methodName(parameters)
.alinkColor Reflects the ALINK attribute of the document's <BODY> tag
anchors An array reflecting all anchors in a document
.bgColor Reflects the BGCOLOR attribute of the document's <BODY> tag
.cookie Specifies a cookie
.forms An array reflecting all forms defined within the page using <FORM> tags
.images An array reflecting all images in a document. Can also be used in an if conditional to see if the browsers sees images.
.lastModified The date/time that the page was last modified
.linkColor Reflects the LINK attribute of the document's <BODY> tag
.links An array reflecting all links in a document
.location Reflects the complete URL of the current page
.referrer Reflects the URL of the calling page
.title Reflects the contents of the <TITLE> tag
.vlinkColor Reflects the VLINK attribute in the
document's <BODY> tag
The anchor object, form object, history object, and link object are also properties of
the document object.
.clear() Removes the page from the browser window
.close() Terminates the input stream to the page, but leaves the page displayed on the screen
.open(mimetype) Opens the input stream to a page to collect incoming write() and writeln(). If ommitted, mimetype is standard text/html
.write(string_expression) Writes string_expression directly to the page
.writeln(string_expression) Writes string_expression directly to
the page and sends a line break (Unix only)
onLoad When used in the <BODY> tag, specifies JavaScript code to be executed as soon as the page is opened.
onUnload When used in the <BODY> tag, specifies JavaScript code to be executed as soon as the page is unloaded.
Though onLoad() and onUnload() technically are event handlers for the larger window object, you place them within the <BODY> tag of the current page.
JavaScript's document object provides access to the entire Web page, including the <HEAD> section, <BODY> definition, and various objects within the page, such as anchors, forms, and links.
The document object is a property of the larger window object.
<HTML> <HEAD> <TITLE>JavaScript Document Object</TITLE> </HEAD> <BODY bgcolor=#ffffcc fgcolor=#222222 link=#ff0000 vlink=#00ff00 alink=0000ff> <P> Hello, my name is JavaScript Document Object and I'll be your web page. I have two hyperlinks in me, one to
<A HREF="http://www.osseo.k12.mn.us/pcsh/jscl/index.htm" >PC's Javascript Homepage</A>. The other to <A HREF="http://home.netscape.com" >Netscape's home page</A>. Below are some of the properties about me.<BR> <P> <SCRIPT LANGUAGE = "JavaScript"> document.write ("document.bgColor = " + document.bgColor + "<BR>") document.write ("document.linkColor = " + document.linkColor + "<BR>") document.write ("document.alinkColor = " + document.alinkColor + "<BR>") document.write ("document.vlinkColor = " + document.vlinkColor + "<BR>") document.write ("document.location = " + document.location + "<BR>") document.write ("document.lastModified = " + document.lastModified + "<BR>") document.write ("document.title = " + document.title + "<BR>") </SCRIPT></BODY> </HTML>
The elements array is an array of objects corresponding to each field within a form. The first item in the array, elements[0], is the first form field. The second item, elements[1], is the second form field, and so on.
The syntax for the elements array is
document.formName.elements[index]
or
document.formName.elements.length
where formName is either the name of a form or an element in the forms array and
index is an integer representing the object's position in the array.
.length Reflects the number of fields on the form
.value Reflects the contents of one form field
The value returned by .value reflects either the contents of the field or the VALUE attribute of the field's INPUT tag, depending on the type of field being referred to.
The elements array is a list that contains one item for each object (button, checkbox, hidden, password, radio, reset, select, submit, text, or textarea object) in a form. This provides a way to refer to fields in a form without using the name. For example, suppose that your document contains a form named UserInput. The first field in that form is named ReaderName. You can refer to the contents of the field using either of the following JavaScript statements:
document.UserInput.ReaderName.value
or
document.UserInput.elements[0].value
where elements[0] is the generic term for "the first field in the form."
The elements array is a property of the larger form object
The following script displays a form with a final button titled Show Facts.
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function showElements() {
msgWindow=window.open("","displayWindow")
msgWindow.document.write ("<H1><CENTER>FORM FACTS</CENTER></H1><P>")
for (var i=0; i <= document.survey.elements.length-1;i++) {
msgWindow.document.write ("document.survey.elements[",i,"].value", document.survey.elements[i].value,"<BR>")
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name = "survey">
<! hidden form field>
<INPUT NAME="hidden" VALUE="surveyform" TYPE=HIDDEN><BR>
<! text form field>
Your Name: <INPUT NAME="ReaderName" VALUE="" MAXLENGTH="25" SIZE=25><P>
<! checkbox form field>
You like JavaScript: <INPUT TYPE="CHECKBOX" NAME="LikesJavaScript" VALUE="true" CHECKED><P>
<! selection box form field>
Which Browser do your use?:
<SELECT NAME="WhichBrowser">
<OPTION SELECTED VALUE="InternetExplorer">Internet Explorer
<OPTION VALUE="Netscape">Netscape
<OPTION VALUE="other">Other
</SELECT>
<P>
<! radio button group form field>
What kind of server do you use? :
<INPUT TYPE="RADIO" NAME="Server" VALUE="Own Server">Own Server
<INPUT TYPE="RADIO" NAME="Server" VALUE="National ISP">National ISP
<INPUT TYPE="RADIO" NAME="Server" VALUE="Local ISP">Local ISP
<! Submit and Reset buttons>
<P>
<INPUT TYPE=SUBMIT VALUE="Submit" NAME="submitbutton">
<INPUT TYPE=RESET VALUE="Reset">
<P><P>
<! button to trigger showElements() custom function>
<INPUT TYPE="button" VALUE="Show Facts" onClick = "showElements()">
</FORM>
</BODY></HTML>
Suppose that you now open this script and fill in the form(see right) that appears with the
following information/selections: Name=Jo Jo Jones, You Like JavaScript is checked, Which
Browser Do You Use is Netscape, and the Server option is Own Server. Then you click
the Show Facts button. A new window appears showing the the following facts:
Here you can see how the .value property depends on the type of form field being
referenced. For the first two items, which are a hidden text box and a text box, the value
is the actual stuff in the field. The checkbox for liking Javascript is either True or False. The named value of the pulldown selects is the output for the browser type choice. Note that each radio button is considered a single
object, and hence there are three elements (4-6) in the elements array. The .value of the
buttons are the button titles because the button titles are named by using the VALUE
attribute in the <INPUT type='button'...> tag.
Event handlers are used in HTML tags, such as <INPUT> and <BODY>, to execute JavaScript code in response to some event that occurs in the reader's page. Table 9 summarizes the event handlers, what actions trigger them, and the tags that can use them.(Note: Event handlers and the tags vary due to browser version. Try them to be sure)
Table 9: Summary of JavaScript Event Handlers
| Event Handler | When Triggered | Some of the tags to use with |
| onBlur | When the reader moves the insertion point out of a field | window, select, text, textarea, password, <BODY> |
| onChange | After the reader changes the contents of a field and moves on to another field | select, text, textarea, password |
| onClick | When the reader clicks on an item | button, checkbox, radio, link, reset, <A>...</A> |
| onFocus | When the reader moves the insertion point into a field | window, select, text, textarea, password, <BODY> |
| onLoad | When a document is loaded into view window | window, <BODY>, <FRAMESET> |
| onMouseOver | When reader points to a hyperlink | <A>...</A>, <BODY> |
| onMouseOut | When reader's mouse leaves a hyperlink | <A>...</A>, <BODY> |
| onSelect | When the reader selects text within a text or text area field | text, textarea, password, checkbox, radio |
| onSubmit | When the reader submits a form | <FORM> |
| onUnload | When the reader exits a document window | window, <BODY>, <FRAMESET> |
This statement defines a loop that repeats a series of commands as long as some condition holds true.
The syntax of for statements is for (initial-expression; condition; increment-expression) { statements }
where initial-expression is an expression that sets the starting value, condition is an expression that proves true or false, increment-expression is an expression that incrememts the initial expression, and statements are Javascript statements that are executed with each pass through the loop as long as condition proves true.
The for loop is generally used to set up a loop and create a counter that is incremented with each pass through the loop. The initial-expression is evaluated first, followed by the condition. If the condition proves true, then all statements within the curly braces that follow are executed once. Next, the increment-expression is executed and the condition is re-tested. When the condition proves false, the loop terminates and the javascript resumes just after the closing curly brace(}) of the for loop.
When this Web page is opened in a browser
<HTML>
<BODY>
<SCRIPT Language = "JavaScript">
for (var i=1; i <= 10; i++) {
document.write ('i = ',i,'<br>')
}
</SCRIPT>
</BODY>
</HTML>
it displays:
i = 1because for each pass through the loop, the document.write statement writes "i =
" followed by the current value of i. It then i++ increments the value in i by 1 and
the loop continues as long as i is less than or equal to 10. What often confuses students about for loop is the order of the expressions. They expect the increment(or it could be decrement) to execute right after the conditional but it doesn't until after the statement(s) are executed and before the start of the next loop.
This statement iterates a value over all properties of an object.
The syntax for this statement is for (variable in object) { statements }
where variable is any valid variable name, object is the name of any existing object, and statements are Javascript statements that are executed as long as variable is less than or equal to the number of properties assigned to an object.
All objects have properties. The for...in loop can get at those properties without using specific property names. For example, if i is the variable defined in the for...in loop, the first pass through the loop references the object's first property. The second pass through the loop references the object's second property and so on until all properties for that object have been referenced.
In the following page, the custom function named dump_props writes out all properties for any object (obj) passed to it. It displays the name of the object as well via the passed obj_name argument:
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function dump_props(obj, obj_name) {
msgWindow=window.open("","displayWindow")
var result = ""
for (var i in obj) {
msgWindow.document.write (obj_name + "." + i + " = " + obj[i] + "<BR>") }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name = 'testform'>
<TEXTAREA NAME="SomeText" ROWS=3 COLS=25> type something here</TEXTAREA>
<INPUT type="button" value="Click Me" onClick =
dump_props(document.testform.SomeText,'SomeText')">
</FORM>
</BODY>
</HTML>
When executed, the BODY of this script displays a form with a textarea form field and a button. Clicking that buttons calls up the dump_props function to display all properties for the document.testform.SomeText object, writing the name SomeText with each pass through the loop. The result, which is shown in the following example, is a catalog of all properties associated with the form fields. The null properties typically are properties that are not associated with this particular type of form field:
SomeText.defaultChecked = nullThe form object refers to a single form within a Web page. The forms array is a list that contains one element for every form in the Web page (one element for every <FORM> tag.)
You create a form by typing <FORM>...</FORM> tags into a page. To refer to a form, property, or method from within JavaScript code. you can use any of these syntaxes:
document.formName.propertyName
document.formName.methodName(parameters)
document.forms[index].propertyName
document.forms[index].methodName(parameters)
document.forms.length
where formName is the value of the NAME attribute in the <FORM> tag, propertyName is one of the pre-defined form properties, methodName is one of the pre-defined methods of forms, index is an integer representing a form object where forms[0] is the first form in the page, forms[1] is the second form in the page, and so on. The last syntax, document.forms.lengths, returns the number of forms defined within the current page (such as 1 if the page contains one form).
.action Reflects the ACTION attribute as defined in the <FORM> tag
.elements An array reflecting all the elements (fields) in the form
.encoding Reflects the ENCTYPE attribute as defined in the <FORM> tag
.length Reflects the number of elements in a single form
.method Reflects the METHOD attribute as defined in the <FORM> tag
.target Reflects the TARGET attribute as defined in the
<FORM> tag
The following JavaScript objects are also properties of the form object. Each of these objects is created with <INPUT> tags that are placed between a pair of <FORM>...</FORM> tags:
button object A clickable button on the form
checkbox object A checkbox on the form
hidden object A hidden text field
password object A password box on the form
radio object A radio button on the form
reset object The form's Reset button
select object A select box (drop-list) on the form
submit object The form's Submit button
text object A text box form field
textarea object A multi-line text box form field
The forms array has one property, .length, which reflects the number of forms in
a document.
.submit() When executed, it submits the form as though the reader had clicked
the Submit button
onSubmit Triggered when the reader clicks the Submit button
Each form in a document is a distinct object with a name, as defined in the NAME attribute of the form, and a number. The number is assigned automatically when the page is opened. So, for example, if the current page contains one form, but that form's <FORM> tag doesn't contain a NAME attribute, you can still refer to the form from within JavaScript code as document.forms[0].
The form object is a property of the larger document object.
The page that follows illustrates the use of a form's submit() method to check the validity of entered data before submitting a form. When the reader clicks the Done button, that button's onClick event handler calls upon the checkData() function. checkData() uses the contains() function to see if the reader's entry (which is supposed to be an email address) contains an @ character. If the entry doesn't contain an @ character, only the message This doesn't look like an email address to me! is returned in an alert box. Nothing is submitted. If the entry does contain an @ character, the document.myform.submit() submits the form.
(This is just an example. For the submission to really happen, the <FORM> tag
needs to specify where to send the submitted form.)
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
var dataOK=false
function contains(onechar,lstring) {
retval = false
for (var i=1;i<=lstring.length;i++) {
if (lstring.substring(i,i+1)==onechar) {
retval=true
break
}
}
return retval
}
function checkData (){
if (contains("@",document.myform.eaddress.value)) {
document.myform.submit()} //submit myform.}
else {
alert("This doesn't look like an email address to me!")
return false
}
}
</SCRIPT>
<BODY>
<FORM NAME="myform">
<B>Enter your email address, click Enter
then attempt to enter www.osseo.com and click Enter:</B>
<INPUT TYPE="text" NAME="eaddress"><P>
<INPUT TYPE="button" VALUE="Enter" NAME="button1" onClick="checkData()">
</FORM>
</BODY></HTML>
Run the example code
A frame is a smaller window within the larger browser window. Each frame can display a different document or URL and each frame is independently scrollable. Each frame also has its own history list. For example, to go back in a frame, the reader right-clicks the frame and chooses Back In Frame from the menu that appears.
Frames are defined by the HTML tags <FRAMESET> and <FRAME>. See Chapters 25 and 30. You may include JavaScript onLoad and onUnload() event handlers in the <FRAMESET> tag. In JavaScript code, you can refer to frames using any of these syntaxes:
[windowReference.]frameName.propertyName
[windowReference.]frames[index].propertyName
window.propertyName
self.propertyName
parent.propertyName
where frameName is the value of the NAME attribute in the <FRAME> tag of a frame definition, index is an integer representing a frame as a number, and propertyName is any of the valid properties for frames, as follows.
The optional windowReference is a window name as defined by a var x = window.open(...) statement, or one of the synonyms top or parent..
The frames array has a length property that identifies how many child frames are in a window or frame. To access that value use either of these syntaxes:
[windowReference.].frames.length
[frameReference.].frames.length
.frames An array reflecting all the frames in a window
.name Reflects the NAME attribute as defined in the <FRAME> tag
.length Reflects the number of child frames within a frame
parent A synonym for the window or frame containing the current frameset
self A synonym for the current frame
window A synonym for the current frame
The frames array has one property:
.length Reflects the number of child frames within a frame
.clearTimeout() Cancels an ongoing timer set by the .setTimeout() method
.setTimeout() Evaluates an expression after a specified amount of time
Although they are (technically) event handlers of the window object, you can use the onLoad and onUnload event handlers in a <FRAMESET> tag.
The <FRAMESET> tag is used in a special Web page whose sole purpose is to define a set of frames that can display documents independently of one another. Each is, to JavaScript, an independent window object.
If a <FRAME> tag contains SRC and NAME attributes, you can refer to that frame from a sibling frame by using the synonym parent to refer to the page that defined both frames - that is, the parent frame that contains the <FRAMESET> and <FRAME> tags. For example, if the third frame in a set is named mainFrame, neighboring sibling frames can refer to that frame using parent.mainframe.
JavaScript also maintains an array of frames so that you can refer to unnamed frames by number. The first frame is frames[0], the second frame is frames[1], and so on. Referring back to the preceding example, if the third frame was not given a name in its <FRAME> tag, JavaScript can still refer to it as parent.frames[2].
The top property also is a synonym that can be used in place of the frame name. The top property refers to the top-most window that contains frames or nested framesets. Thus, if one <FRAMESET> page creates another <FRAMESET> page and you are in the bottommost page, then parent refers to the page that created the frame you are in and top refers to the <FRAMESET> page that created the frames above the parent.
The self and window properties are synonyms for the current frame, and you can optionally use them to refer to the current frame (not the parent or the top frame).
The frame object is a property of the larger window object.
Suppose that the following Web page is named index.html and is the first page that opens when a reader comes to this site. The page splits the browser window into a narrow window named toc (for table of contents) and a larger window named main.
<HTML>
<! Set up the frames >
<! ----- Split into two columns>
<FRAMESET COLS= "130,*">
<FRAME NAME="toc" SRC = "places.htm" MARGINWIDTH = "0" MARGINHEIGHT="0">
<FRAME NAME="main" SRC = "home.htm" MARGINWIDTH = "10" MARGINHEIGHT="10">
</FRAMESET>
</HTML>
The places.htm page, which is displayed in the narrower toc frame, can control documents in the larger main frame by referring to parent.main as in the examples that follows:
<FORM> <! Go back in main frame> <INPUT type="button" onClick = "parent.main.history.back()"> <! Go forward in main frame> <INPUT type="button" onClick = "parent.main.history.forward()"> </FORM>
A statement that declares a user-defined JavaScript function, typically in the <HEAD> of a Web page.
The syntax for the function statement is
function name(param , param, ...) {
statements
}
where name is the name that you assign to the function (cannot contain spaces, cannot be a reserved word) and the optional param statements are names that you assign to parameters that will be passed to the function with any call to the function. The params can be any combination of strings, numbers, and objects.
The function() statement defines a custom JavaScript function that, once defined, can be called by any JavaScript code or event handler on the Web page. To ensure that a function is defined before it is called up, define all user-created functions between the <HEAD> and </HEAD> tags of the Web page. You will find that user-created functions are the backbone of Javascript.
If you want the function to return a value, the function must include a return statement that specifies the value to return.
You cannot nest a function statement within another statement or within itself.
All parameters are passed to the function by value and any changes to the value are local to the function. In other words, if the function changes the value of the parameter, the change is not reflected globally(outside your function) or in the calling function. The only changed value that comes out of a function is the value specified in the return statement.
The following Web page contains two custom functions named strToZero() and validate(). The strToZero takes any value, ensures that it is a number (not a string), and returns a number. If a non-numeric string value is passed to the function, the function returns the number 0.
The second function, validate(), does not return a value. Instead, it checks to see if the value passed to it is a number between 1 and 10. If the number is not between 1 and 10, the validate() function just displays the alert message Please enter a number between 1 and 10.
Both functions are called by the onClick event handler of a form field. Note that the strToZero() function first ensures that the user's entry is indeed a number (not a string) and that the validate() function operates upon that number.
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
//function convert any non-numeric value to a zero.
function strToZero(anyval) {
anyval = ""+anyval
if (anyval.substring(0,1) < "0" || anyval.substring(0,1) > "9") {
anyval = "0"
}
return eval(anyval)
}
//function to ensure that number is between 1 and 10.
function validate(anynum) {
if (anynum <1 || anynum > 10) {
alert ("Please enter a number between 1 and 10.")
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Enter a number between 1 and 10 and click outside the textbox
then Enter a number greater than 10 and click outside the text box:
<INPUT NAME = "Rating" SIZE = 2 onChange = "validate(strToZero(this.value))">
</FORM>
</BODY>
</HTML>
Run the example code
A hidden object is a form field that is not visible to the reader. This object is generally used to pass information to yourself as the recipient of the form.
To create a hidden form field, use type="hidden" within an input tag, between a pair of <FORM> ...</FORM> tags.
To refer to a hidden object from within JavaScript code, use either of these syntaxes:
document.formName.hiddenName.propertyName
or
document.formName.elements[index].propertyName
where hiddenName is the value of the NAME attribute as defined in the hidden object's <INPUT> tag, formName is either the value of the NAME attribute of a form object or an element in the forms array, index is an integer representing the fields position in the elements array, and propertyName is one of the properties listed below.
.name reflects the NAME attribute as defined in the hidden object's <INPUT> tag.
.value reflects the current value of the hidden form field
A hidden object is a form element and must be defined within a <FORM> tag. It is totally invisible on the Web page - and visible only in the document source view. Use a hidden field when you want to pass private information, such as the name of the form, to yourself along with the reader's responses to form fields.
You can programmatically change the value of the hidden object by changing its .value property.
A hidden object is a property of the larger form object.
This page shows how to place a hidden field on a form using an <INPUT> tag, and then programmatically change the contents of the field. In this example, the script named stampForm() places the current date/time in the hidden field named timestamp. The function is executed as soon as the page is loaded, thanks to the onLoad event handler in the body tag.
Of course, you cannot see the contents of a hidden field, so this page has a little button that lets you peek at the hidden field's contents (your reader will never need that button). When you click the button, the showSecret() function is called up to reveal the contents of the hidden field.
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function stampForm() {
rightnow = new Date()
document.myForm.timestamp.value = rightnow
}
function showSecret() {
msg = "hidden field contains " + document.myForm.timestamp.value
alert (msg)
}
</SCRIPT>
</HEAD>
<BODY onLoad = "stampForm()">
<FORM name = "myForm">
<INPUT type = "hidden" name = "timestamp">
<INPUT type = "button" value = "Try Me" onClick = "showSecret()">
</FORM>
</BODY></HTML>
Run the example code
This object contains information on the URLs that the reader has visited within the current window.
In JavaScript, you can use either of these syntaxes to refer to the history object:
history.propertyName
history.methodName(parameters)
where propertyName is one of the properties and methodName is one of the methods that follows.
.length Reflects the number of entries in the history object
.back() Displays the previous page in the history list, if any
.forward() Displays the next page in the listory list, if any
.go(n) Displays the page that is n pages from the current list in the page
In the last example, n can be either a positive or negative number. For example, history.go(4) moves four pages ahead in the history list, whereas history.go(-4) moves four pages back in the history list.
The history object is a list of URLs that the user has visited in the current session and also in the current frame, if multiple frames are displayed on the screen. The properties and methods of this object let you move through the history list programmatically via JavaScript code.
The history object is a property of the larger document object.
The following statements display a button labeled Back in the current Web page. When the reader clicks that button, the previous page in the frame named main is displayed. This example assumes that a prior page has used the <FRAMESET> and <FRAME> tags to define a frame named main.
<FORM> <INPUT type = "button" value = "Back" onClick = "parent.main.history.back()") </FORM>
This statement makes a decision within a script.
The general syntax for the if statement is
if (condition) { statements1 }
where condition is any expression that results in a true or false outcome and statements1 and statements2 are JavaScript code.
When executed, the condition is evaluated and must return a true or false value. If the result is true, then the code within the first pair of curly braces, {statements1} is executed. If the condition proves false, that code is ignored.
Else is optional. If included, the code within the second pair of curly braces, {statements2} is executed. Even if you want nothing to happen in a false conditional, it is a good idea to include Else and just leave the second curly brackets empty.
You can nest if() statements, which means that either statements1 or statements2 can contain more if() statements.
When checking to see if a variable equals some value in an if() condition, be sure to use the double equal signs operator (==) rather than the single equal sign (=). To specify AND in an if() condition, use the && operator. To specify OR in an if() condition, use the || operator.
In the following Web page, the genderOK() function converts the value passed to it to uppercase (using the toUppercase() method of the string object). The if() statement then checks to see if that string is letter M or the letter F. If it is, the function does not do anything. If the string is neither M or F, then the function displays the message Please enter M or F in the Gender box.
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function genderOK() {
testing.Gender.value = testing.Gender.value.toUpperCase()
if (testing.Gender.value == "M" || testing.Gender.value == "F"){
//do nothing
}
else {
alert ("Please enter M or F")
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="testing">
Gender:<INPUT name='Gender' Size = 2 onBlur = "genderOK()">
Name:<INPUT name='ReaderName' Size = 20>
</FORM>
</BODY></HTML>
A link object is a piece of text or an image identified as a hypertext link within the current Web page, via <A HREF...>...</A> tags.
Within a Web page, you use the <A HREF...>...</A> tags to define a hyperlink (that is, a link). To determine how many links are in the Web page, use the syntax
document.links.length
To refer to a specific link in the page using JavaScript code, use the syntax
document.links[index].propertyName
where index is an integer representing the link's position in the links array and propertyName is one of the valid properties for the link object.
.hash Specifies an anchor name in the URL
.host Specifies the hostname:port portion of the URL
.hostname Specifies the host and domain name, or IP address, of a network host
.href Specifies the entire URL
.pathname Specifies the URL-path portion of the URL
.port Specifies the communications port that the server uses for communications
.protocol Specifies the beginning of the URL, including the colon
.search Specifies a query target reflects the TARGET attribute
Event handlers for hyperlinks are specified in the <A HREF...> tag that defines the link. Three event handlers are available:
onClick Triggered when the user clicks on the link
onMouseOver Triggered when the user points to the link
onMouseOut Triggered when the mouse leaves the link
When a page is opened, JavaScript automatically creates a list (array) of all hyperlinks in the page. The first hyperlink is links[0], the second one is links[1], and so on. Each link object within that array is a location object - a complete URL. Each item in the links array has the same properties as a location object. If a link object also is an anchor object, the object has entries in both the anchors and links arrays.
The link object is a property of the larger document object
The most common use of link properties is image rollovers by creating a function and then calling the function with an onMouseOver() event handler. For example, in this script from our book, mousing over and out on the image link, changes the image from one to another and back.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">
<!-- Hide script from old browsers
if (document.images) {
arrowRed = new Image
arrowBlue = new Image
arrowRed.src = "redArrow.gif"
arrowBlue.src = "blueArrow.gif"
}
else {
arrowRed = ""
arrowBlue = ""
document.arrow = ""
}
// End hiding script from old browsers -->
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<A HREF="next.html" onMouseover="document.arrow.src=arrowRed.src"
onMouseout="document.arrow.src=arrowBlue.src"><IMG SRC="blueArrow.gif"
WIDTH="147" HEIGHT="82" BORDER="0" NAME="arrow" ALT="arrow"></A>
</BODY>
</HTML>
Run the example code
This object contains information on the current document's URL.
The syntax for this object is
window.location.propertyName
where propertyName is one of the properties for the location object as listed in the following "Properties" section. Omitting the property name is equivalent to specifying the href property (the complete URL).
Notice that there is no .value property for window.location. What you usually use is window.location.href to give you the full URL.
The full set of properties is summarized here:
.hash Specifies an anchor name in the URL
.host Specifies the hostname:port portion of the URL
.hostname Specifies the host and domain name, or IP address, of a network host
.href Specifies the entire URL
.pathname Specifies the URL-path portion of the URL
.port Specifies the communications port that the server uses for communications
.protocol Specifies the beginning of the URL, including the colon
.search Specifies a query
The location object can be changed in your Javascript to display a new page in the window or frame. This is the most common way of moving from one page to another with Javascript.
The location object is contained within the window object. In a framed site, each frame has its own unique location object, which is the URL of the page being displayed within that frame (window). If you reference a location object without specifying a window, the location object represents the current location. You can also reference specific windows by its window name - for example, parent.frame2.location.propertyName as long as the page that the script is on has information about the window names so it can identify the window you are calling.
The location object is a property of the larger window object.
The sample Web page that follows contains an anchor (bookmark) named Top just after the opening body tag. Near the bottom of the page is a button labeled Go To Top that, when clicked, adds the hash #Top to the Location box. When the reader clicks the button, he or she is taken back to the top of the page:
<HTML>
<BODY>
<A NAME = "Top"></A>
<H1><CENTER>I Have a Top</H1></CENTER>
Scroll down to bottom of this page to find a button...
<SCRIPT Language = "JavaScript">
for (var i=1; i<=40;i++) {
document.write ("keep going<p>")
}
</SCRIPT>
<FORM name="mini1">
<CENTER>
<INPUT type="button" value="Go To Top" onClick = "self.location.hash = 'Top'">
</CENTER>
</FORM>
</BODY></HTML>
Run the example code
To create a long page, this code uses a for loop that starts the variable i at 1 and increments it(i++) one number per loop until it is greater than 40 when the document.write("keep going") stops. If you have extra time on your hands, run the example code and count. There should be 40 "keep going" strings.
The sample Web page that follows contains an anchor (bookmark) named Top just after the opening body tag. Near the bottom of the page is a button labeled Go To Top that, when clicked, adds the hash #Top to the Location box. When the reader clicks the button, he or she is taken back to the top of the page:
<HTML>
<SCRIPT Language = "JavaScript">
function rhollFavs() {
if (document.choices.testing[0].checked) {
window.location.href="http://www.google.com"
}
if(document.choices.testing[1].checked) {
window.location.href="http://www.osseo.k12.mn.us/sec/pcsh/"
}
}
</SCRIPT>
<BODY>
<FORM name="choices">
<INPUT type="radio" Name="testing" value="google"> Rholl's favorite search engine<br>
<INPUT type="radio" Name="testing" value="pcsh"> Rholl's favorite school<p>
<INPUT type="button" value="Drumroll Please" onClick = "rhollFavs()">
</FORM>
</BODY></HTML>
Run the example code
The math object is a built-in object that has properties and methods for mathematical constants and methods.
To use a Math object, follow the syntax
Math.propertyName
or
Math.methodName(parameters)
where propertyName is one of the properties of the Math object, methodName is one of the methods of the Math object, and parameters are appropriate values for the method.
.E Euler's constant (approximately 2.718).
.LN2 The natural logarithm of 2 (approximately 0.693).
.LN10 The natural logarithm of 10 (approximately 2.302).
.LOG2E The base 2 logarithm of e (approximately 1.442).
.LOG10E The base 10 logarithm of e (approximately 0.434).
.PI The ratio of the circumference of a circle to its diameter (approximately 3.14159).
.SQRT1_2 The square root of one-half; equivalently, one over the square root of two (approximately 0.707).
.SQRT2 The square root of 2 (approximately 1.414).
.abs(n) Returns the absolute value of n.
.acos (n) Returns the arcosine (in radians) of n.
.asin(n) Returns the arcsine (in radians) of n.
.atan(n) Returns the arc tangent (in radians) of n.
.ceil(n) Returns the least integer greater than or equal to n.
.cos(n) Returns the cosine of n.
.exp(n) Returns en, where n is the argument and e is Euler's constant.
.floor(n) Returns the greatest integer less than or equal to n.
.log(n) Returns the natural logarithm (base e) of n.
.max(x,y) Returns either x or or y, whichever is greater.
.min (x,y) Returns either x or or y, whichever is smaller.
.pow(x,y) returns x to the exponent power, that is, xy.
.random() Returns a random number between 0 and 1. See example below for number greater than 1.
.round(n) Returns the value of a n rounded to the nearest integer.
.sin(n) Returns the sine of n.
.sqrt(n) Returns the square root of n.
.tan(n) Returns the tangent of n.
The Math object is a built-in JavaScript object. Note the use of the uppercase M in Math and the use of uppercase letters in all properties.
Because the random() method returns a number between 0 and 1, you can create a custom function that returns a random number greater than one by adding some more code to the random() method. The following Web page shows a randNum() function and includes a small form and button to test the custom function:
<HTML>
<HEAD>
<SCRIPT language = "JavaScript">
function randomNum() {
x=parseInt(Math.random()*10)
document.testForm.randomnum.value=x
}
</SCRIPT>
</HEAD>
<BODY>
Let's test the random number custom function, using numbers between 1 and 10.<P>
<FORM name="testForm">
<INPUT name = "randomnum" size = 3"><P>
<INPUT type="button" value = "Click for random number"onclick =
"randomNum()">
</FORM>
</BODY>
</HTML>
Run the example code
Methods are part of the Javascript language that have a built in action... they do something. Ex. the write() method writes to a browser window. the alert() method causes an alert box to pop up.
The syntax for this object is methodname(). All methods are followed by parenthesis(). The parenthesis may be empty or contain parameters. Note: You will examples find in other sections of this page how the methods are used. Often it is with dotted syntax. ie. formx.checkbox1.click()
<HTML>
<BODY>
<CENTER>
<SCRIPT Language = "JavaScript">
document.write ("<b>I did not create this method</b>")
</SCRIPT>
</CENTER>
</BODY>
</HTML>
causes the following message to display on the screen(document):
| Method name | Action caused | Example(assume all on one line) |
| alert() | causes a gray popup window(alert box) with whatever value is inside the parenthesis to appear | alert("wrong password") |
| blur() | removes the browser focus from the current object. Can be run on a window or an element in a form. | window.blur() |
| click() | simulates a user's clicking of a form object. Can be used to click a form element when something else has occurred. | formx.checkbox1.click() |
| close() | method used to close a window. | window.close() |
| concat() | This method joins the text contained in one string with the text from other specified strings and returns a new string. | document.write(myString1.concat(myString2)) |
| eval() | returns the value of whatever is in the parenthesis. Often used for math equations. | eval("4+3") |
| focus() | like blur(), useful with windows and form elements. brings the focus to the object you call it on. | formx.textarea1.focus() |
| getDate() | returns a number from 1-31 specifying today's date. | datevariable.getDate() |
| getDay() | returns a number from 0-6 specifying today's day name. To get the actual day name, you will need to create an array of day names and call the method on the array as in the example | arrayName[datevariable.getDay()] |
| getElementById() | useful in forms. You can give an element on your page an Id(name) and call it in your javascript. | document.getElementById() |
| getFullYear() | returns a 4 digit number specifying the current year. | datevariable.getFullYear() |
| getHours() | Returns hour of the day from 0-23. You will need to use some if statements to convert 0-23 to 1-12 am and pm. if datevariable.hoursvariable > 11 etc.. | datevariable.getHours() |
| getMinutes() | returns a number from 0-59 specifying the current minutes. | datevariable.getMinutes() |
| getMonth() | returns a number from 0-11 specifying today's month name. To get the actual month name, you will need to create an array of month names and call the method on the array as in the example | arrayName[datevariable.getMonth()] |
| getSeconds() | returns a number from 0-59 specifying the current seconds. | datevariable.getSeconds() |
| open() | opens a new window or document. | window.open('filename.htm', 'newWin2','width=350,height=200,top=250') |
| print() | prints the contents of the current window. | window.print() |
| prompt() | This method displays a dialog box prompting the user for some input. Can be used with other javascript as a password technique or a way to greet your user by the name they type in the prompt box. | prompt("Please enter your password.", "Type password here") |
| reload() | reloads the contents of the current window. | window.location.reload() |
| replace() | replaces the current url with the new one you specify. Disables the users back button also. | window.location.replace("newurl.htm") |
| reset() | resets the default values of any elements in a form. | formx.reset() |
| select() | mostly used with forms to select an element in a form. I like to use it to put the cursor into the first text box of a form for the user | formx.1sttextname.select() |
| setInterval() | causes a function to be continually repeated within a certain number of milliseconds. Very handy for slideshows, changing or moving things automatically. Use this method on many of the extra credit assignments in this class. The method accepts 2 assignments in the parenthesis(the name of your function, number of milliseconds). | setInterval("myFunction()", 1000) |
| write() | writes strings to the browser window. In itself, not a big deal but used with other javascript, the write() method allows you to dynamically update a page with user input. | document.write("Hello World") |
| Math.xx() methods | The Math object in javascript has several methods that work with numbers. You can use them to return number values(like in a calculator) or, used with other javascript, to cause a number of non-Math effects. Common Math object methods include: : Math.abs(x), Math.ceil(x), Math.cos(x), Math.floor(x), Math.log(x), Math.max(x, y), Math.min(x, y), Math.random(), Math.round(x), Math.sin(x) and Math.sqrt(x). | |
| Array.xx() methods | The Array object in javascript has several methods that work only in Netscape. I will not list them since most of your users now use IE. However, a couple of Array object methods that work in IE include: Array.sort() sorts all of the objects in an array in alphabetical order, Array.concat() strings all of the object in an array together, Array.reverse() reverses the order of the objects in an array, Array.valueOf() returns a primitive value of all of the objects in the array. | |
| String.xx() methods | The String object in javascript has several methods that are helpful when working with strings: stringname.concat(), stringname.bold(), stringname.charAt(), stringname.fontcolor(), stringname.fontsize(), stringname.italics(), stringname.toUpperCase(), stringname.toLowerCase(), | |
This statement creates a new instance of an object type.
The syntax for the new statement is
objectname = new objecttype (parameter1 ,parameter2, ...)
where objectname is the name you assign to the specific object being created, objecttype is the type of object you are creating, and parameters are properties of the object.
Use the reserved new keyword to create a new instance of an object in much the same way you would create a variable.
In this example, you create a new date object named rightnow that reflects the system date and time when the page is opened. You then use the toLocaleString() method of the date object to display a message in the format Your visit begins at 04/02/97 12:30:00. Note that the actual appearance(LocalString) of the date object will depend on your computer. It may be different than what I list here.
<HTML>
<BODY>
<SCRIPT language = "JavaScript">
rightnow = new Date()
document.write ("Your visit begins at ")
document.write (rightnow.toLocaleString())
</SCRIPT>
</BODY>
</HTML>
Run the example code
This function converts a string containing numeric characters to a floating point number. A float, or floating point number is a decimal number to two places.
The syntax for this function is
parseFloat(string)
where string is a string that represents the value you want to parse.
parseFloat() parses its argument, a string, and returns a floating point number. If it finds a character other than a sign ( + or -), numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters.
If the first character cannot be converted to a number, parseFloat returns NaN, indicating that the value is not a number.
When this small Web page is opened
<HTML>
<BODY>
<SCRIPT Language = "JavaScript">
string1 = "16.678 ounces"
string2 = "Parcel number 630"
document.write ('parseFloat(string1) = ',parseFloat(string1))
document.write ('<BR>')
document.write ('parseFloat(string2) = ',parseFloat(string2))
</SCRIPT>
</BODY>
</HTML>
it displays the following on the screen:
parseFloat(string1) = 16.678
parseFloat(string2) = NaN
This function parses a string and returns an integer of the specified radix or base.
The syntax for the function is
parseInt(string ,radix)
where string is a string that represents the value that you want to parse and radix is an integer that represents the base numbering system of the return value.
The parseInt function parses its first argument, a string, and attempts to return an integer of the specified radix (base numbering system). A radix of 10 indicates to convert to a decimal number, 8 octal, 16 hexadecimal, and so on.
If parseInt encounters a character that is not a numeral in the specified radix, it ignores all characters from that point on. Floating point numbers(ex. 2.34) are truncated to integer values. If the radix is not specified, JavaScript assumes the following:
If the first character of the string cannot be converted to a number, parseInt() returns NaN, indicating that the value is not a number:
Example
Opening this small page
<HTML>
<BODY>
<SCRIPT Language = "JavaScript">
string1 = "-1.987654321"
string2 = "$500.00"
document.write ('parseInt(string1) = ',parseInt(string1))
document.write ('<BR>')
document.write ('parseInt(string2) = ',parseInt(string2))
</SCRIPT>
</BODY>
</HTML>
displays this in the Web browser screen:
parseInt(string1) = -1In a form, a password object is a text field that hides the reader's entry by displaying an asterisk (*) for each character typed.
To create a password field, place an <INPUT type='password'...> tag between a pair of <FORM>...</FORM> tags.
To refer to a password object's properties and methods via JavaScript code, use any of these syntaxes:
formName.passwordName.propertyName
formName.passwordName.methodName(parameters)
formName.elements[index].propertyName
formName.elements[index].methodName(parameters)
where passwordName is the NAME attribute as defined in the password object's <INPUT> tag, formName the NAME attribute as defined in the <FORM> tag, index is an integer representing the password field's position in the elements array, propertyName and methodName are any valid property/method for the password object, as listed in the next section, and parameters are any parameters that are acceptable to the method.
.defaultValue reflects the VALUE attribute as defined in the <INPUT> tag
.name reflects the NAME attribute as defined in the <INPUT> tag
.value reflects the VALUE attribute is set
programmatically, but not a user's entry
.focus() moves the insertion point into the password field
.blur() moves the focus out of the password field so nothing can be typed there
.select() selects the contents of the password field.
A password object is a form element that must be defined with an <INPUT> tag between a pair of <FORM>...</FORM> tags. The password object is a property of the larger form object.
Password protection in Javascript is not very secure as a knowledgable user can view the source to see the password. A compiled program is more secure as the source code is invisible. However, with javascript, you can minimally password protect the password in an input tag, as the following example shows:
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function passCheck() {
if (document.ReaderInfo.passw.value=="rholl") {
window.location.href="http://www.google.com"
}
else {
alert ("Wrong Password Dude!")
}
}
</SCRIPT>
</HEAD>
<BODY>Type the password and click the Enter button to go
to the world's greatest search engine.
Hint: The password is your teachers last name.
Try a wrong password also.
<FORM name = "ReaderInfo">
<INPUT type="password" value="" name="passw" size=20>
<INPUT type="button" value="Enter" name="button" onclick="passCheck()">
</FORM>
</BODY>
</HTML>
Run the example code
This object is a single radio button (aka option button) on a form.
To create a group of radio buttons on a form, you can manually enter <INPUT type='radio'...> tags between a pair of <FORM>...</FORM> tags.
To access a radio button's properties and methods via JavaScript, use any of these syntaxes:
formName.radioName[index#].propertyName
formName.radioName[index#].methodName(parameters)
where radioName is the NAME attribute as defined in the <INPUT> tag, index# is an integer representing a specific radio button in a radio group, formName is the NAME attribute of a form object. The propertyName, methodName, and parameters represent any of the valid properties/methods/parameters for the radio object, as listed in the following sections.
.checked Lets you see if a button is selected and programatically select a radio button
.default Reflects the CHECKED attribute of the button's <INPUT> tag
.length Reflects the number of radio buttons in a radio button group
.name Reflects the NAME attribute as defined in the button's <INPUT> tag
.value Reflects the VALUE attribute as defined in the
button's <INPUT> tag
.click() Programatically clicks on the radio button
onClick Triggered when the reader clicks on the radio button
All of the radio buttons in a radio button group use the same name property. To access the an individual radio button via JavaScript, follow the object name with an index starting from 0, indicating the button's position in the group. For example, take a look at the radio buttons defined in the following html page:
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function soWhat() {
if(document.flashy.flashers[0].checked)
{ alert("Hey, you checked the first one.")}
if(document.flashy.flashers[1].checked)
{ alert("You have selected the 2nd radio button.")}
if(document.flashy.flashers[2].checked)
{ alert("The third radio button was your choice.")}
}
</SCRIPT>
</HEAD>
<BODY>Select a radio button and will discover an astounding fact.
<FORM name = "flashy">
<INPUT TYPE="RADIO" NAME="flashers" VALUE="first" onClick="soWhat()">first
<INPUT TYPE="RADIO" NAME="flashers" VALUE="second" onClick="soWhat()">second
<INPUT TYPE="RADIO" NAME="flashers" VALUE="third" onClick="soWhat()">third
</FORM> </body> </html>
Run the example code
The only way to name the selected radio button is using the index number, ex. flashy.flashers[index number].checked. I chose to write 3 if conditionals, one for each index number possibility that were checked each time a radio button is clicked.
The radio object is a property of the larger form object.
Opening the sample Web page that follows shows a simple form with two radio buttons, one labeled Female, the other labeled Male. Below the checkboxes appears a button labeled "Click Me":
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function showChoice() {
var msg = ""
if (document.ReaderInfo.gender[0].checked) { msg = 'Female' }
if (document.ReaderInfo.gender[1].checked) { msg = 'Male' }
document.ReaderInfo.result.value="Are you sure you are "+ msg
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name = "ReaderInfo">
<INPUT TYPE="RADIO" NAME="gender" VALUE="Female">Female<BR>
<INPUT TYPE="RADIO" NAME="gender" VALUE="Male">Male<BR><P>
<INPUT type="button" value="Click Me" onClick="showChoice()">
<INPUT type="text" name="result" value="" size="30">
</FORM>
</BODY>
</HTML>
Run the example
When the reader clicks on the button, the choice the user made is written into the text box. The showMessage() custom function determines which choice was made by inspecting the .checked property of each radio button and assigning a value to the variable named msg when it finds the checked button. The value of the text box is then assigned the combination of a string and the variable msg.
These words have special meaning in JavaScript and cannot be used as variable names, function names, methods, or object names. Some are not used in current JavaScript but are reserved for future use.
Abstract |
float |
public |
boolean |
for |
return |
break |
function |
short |
byte |
goto |
static |
case |
if |
super |
catch |
implements |
switch |
char |
import |
synchronized |
class |
in |
this |
const |
instanceof |
throw |
continue |
int |
throws |
default |
interface |
transient |
do |
long |
true |
double |
native |
try |
else |
new |
var |
extends |
null |
void |
false |
package |
while |
final |
private |
with |
finally |
protected |
This object refers to the Reset button on a form.
To define a Reset button on a form, use the stand