You are on page 1of 37

Contents

Warranty, Disclaimer and Copyright Policy
Get More Free eBooks and Other Cool Stuff
Introduction
Hands-on Learning
Java Script Data Types
Reserved Words
Java Script Strings
Java Script Arrays
Java Script Mathematics
Java Script Math Object
Assignment Operators
Comparison Operators
Control Structures
Logical Operators
Bitwise Operators
Functions
Recursion
Events
Objects
Using the Java Script Date Object
The Document Object Model (DOM)
Window Object
History Object
Location Object
Document Object

Warranty, Disclaimer and Copyright Policy

This material is provided on an "as-is" basis, and Bucaro TecHelp makes no warranty or
representation, express or implied, with respect to its quality performance or fitness for a particular
purpose. In no event shall Bucaro TecHelp be liable for direct, indirect, special, incidental, or
consequential damages arising out of the use of this material.

No patent liability is assumed with respect to the use of the information contained herein. Although
every precaution has been taken in the preparation of this manual, Bucaro TecHelp assumes no
responsibility for errors or omissions. Neither is any liability assumed for damages resulting from
the use of the information contained herein. This information is provided with the understanding
that Bucaro TecHelp is not engaged in rendering medical, legal, accounting or other professional
service. If legal advice or other expert assistance is required, the services of a competent
professional person should be sought.

By using this material, the user assumes complete responsibility for any and all damages resulting
from that use. Use of this program and materials requires agreement to the terms of this warranty
and disclaimer. If you do not agree to the terms of this warranty, do not use this material.

Copyright(C)2002-2008 Bucaro TecHelp. Permission is granted for this program to forward, reprint,
distribute, offer as free bonus or part of a product for sale as long as no changes are made to
copies that are distributed.

To receive an email notification when new articles, ebooks, clipart, graphics, or other content has
been added to Bucaro Techelp, Click Here to subscribe to Bucaro TecHelp News Feed Notification.

Contents

Get More Free eBooks and Other Cool Stuff

Visit Bucaro Techelp to download FREE ebooks including Bucaro TecHelp s popular PC Tech Toolkit.
Read Bucaro TecHelp's famous Easy Java Script and Easy CSS tutorials with cut-and-paste code.
Learn Basic PC Anatomy and where to find FREE diagnostic Tools and technical assistance. Learn
how to start your own online business, including many examples of people who started successful
businesses.
To receive an email notification when new articles, ebooks, clip art, graphics, or other content has
been added to Bucaro Techelp, Click Here to subscribe to Bucaro TecHelp News Feed Notification.

Contents

Introduction

One thing I learned as an Electronics Engineer is to substitute software for hardware as much as
possible. Why? Because software is cheaper and easier to modify. At some point though, you find a
limit to how much hardware you can replace with software. For one thing, eventually you have to
interface with the real world. For another thing, only hardware can achieve the highest operating
speeds. What does this have to do with JavaScript?

One thing I learned as a Web Programmer is to substitute client side processing for server side
processing as much as possible. Why? Because client side processing takes the load off the server
and distributes it among the client systems. Before JavaScript, all processing was done on the
server side. If one client was using your Web site the server had one processing operation. If a
thousand clients were using your Web site the server had a thousand times as much processing.

With client side JavaScript, all the server does is send the Web page to the client. If a thousand
clients are using your Web site, the server doesn't have much more processing to do than if just
one client is using your Web site. Instead a thousand processes are distributed to client systems.

At some point though, you find a limit to how much processing you can push off to the client. For
one thing, eventually the server has to processes requests sent from the client. For another thing,
it's difficult and unreliable for a Web site to store information on a client.

Maybe you are not ready to tackle the concept of trade offs between server side processing and
client side processing. The point that I am trying to make is that client side processing is very
important.

There are other proprietary methods of performing client side processing, like VBScript, ActiveX,
and Java. But all these methods either require a plug-in or they don't work in all browsers. Only
JavaScript is built-in to all modern browsers. The only practical way to accomplish client side
processing is with JavaScript. That's why JavaScript is the most popular language for programming
the Web.

JavaScript is an amazingly eloquent and cooperative language. It's easy to learn, easy to use, and
easy to debug. If you have been experimenting with HTML, now is the time to start using the power
of JavaScript to make your Web pages dynamic.

With JavaScript you can turn a Web page into a powerful multimedia application or even into a
database application. And you can do it without a complicated compiler. All you need is a simple
ASCII text pad and your favorite Web browser. So lets proceed now to put the power of JavaScript
into your hands.

Contents

Hands-on Learning

Even though Java Script is probably the easiest and most fun to use programming language on the
planet, it's still very boring to just read about programming. You'll find learning Java Script much
easier if you follow along by actually typing and executing the examples.

On of the great things about Java Script is that you don't need to learn a complicated integrated
development environment application in order to create programs and execute them. You don't
need a complicated word processing application to type a Java Script program, in fact word
processing applications add formatting codes to your file that will prevent your code from
executing. All you need is a simple ASCII text editor.

Windows Notepad is about as simple a text editor as you can get, and it's completely adequate for
Java Script Programming. Just use your Start Menu to navigate to the Accessories and group and
drag a copy of the Notepad icon to your desktop. Open a new document in Notepad and type the
code shown below.

<html>
<head>

</head>
<body>
Hello World
</body>
</html>

The code shown above is actually html (hypertext markup language) that defines a webpage. The
entire webpage is contained between the html opening tag <html> and the closing tag </html>.
The webpage is divided into two sections, the "head", which is delineated by the opening head tag
<head> and the closing head tag </head>, and the "body" which is delineated by the opening
body tag <body> and the closing body tag </body>.

Note that, within the body section we typed the text "Hello World". This is the text that we want
the webpage to display when we load it into our Web browser.

Create a folder where you want to save your Java Script example files, and then save your "Hello
World" webpage with the file exension .htm. A good file name would be example1.htm.

Now when you double-click on the name of the file, your Web browser (Internet Explorer or Mozilla
Firefox) will open and display the webpage (if you have your file associations set up correctly) and
the webpage will display the text "Hello World".

Everything we done so far is html code, we haven't actually done any Java Script coding yet, but if
you're looking at the words "Hello World" in your Web browser, you are now set up to begin Java
Script programming.

There are two places where you can put your Java Script code. You can put it in the webpage
document itself, or in an external file. If you put your Java Script code in the webpage, you can
enter it in the head section or the body section.

Java Script code usually goes in the head section of the webpage because the head section is
executed before the body section, and you usually want your Java Script functions and variables
registered before you enter any code that calls on them to be executed.

You could put your Java Script code in the body section, as long as you enter it in the webpage
before any code that calls on it. For example, if you write some code that is to be executed when
someone clicks on a button, you better have that code higher in the file than the code for the
button.

In any case, your Java Script code must contained within a "script block". A script block is
delineated by the opening script tag <script> and the closing script tag </script>. To be technically
correct, the opening script tag must have a type attribute that tells what kind of code is inside the
script block. Shown below is Java Script code block.

<script type="text/javascript">
document.write("Hello World");
</script>

Open a new document in Notepad and type the code shown below, and then save your file with the
name example2.htm.

<html>
<head>

<script type="text/javascript">
document.write("Hello World");
</script>

</head>
<body>

</body>
</html>

Now when you double-click on the name of the file, your Web browser will open and display the
text "Hello World". It looks exactly the same as the previous html example, so why do we need
Java Script? Well, for this rudimentary example, we don't really need Java Script, but if you're
looking at the words "Hello World" in your Web browser, you have just taken your first step toward
putting the awesome power of Java Script programming in your hands!

Earlier I mentioned that another place you could put your Java Script is in an external file. If you
want to try that, open a new document in Notepad and type the code shown below, and then save
your file with the name example3.js.

document.write("Hello World");

Open another new document in Notepad and type the code shown below, and then save your file
with the name example3.htm.

<html>
<head>
<script language="JavaScript" src="example3.js"></script>
</head>
<body>

</body>
</html>

Now when you open the file "example3.htm", your Web browser, it will find the link to the external
Java Script file and open and display the text "Hello World". It looks exactly the same as the
previous html example, so why would we place our Java Script code in an externally linked file?

You would place your Java Script code in an external file if you wanted to use that code in several
webpages. Then you would then need to maintain only one Java Script file which you could link to
any number of different webpages.

Note that in the external Java Script file, we didn't use the script block tags. You don't need to
include the script block tags because the .js file extension and the link in the webpage tells the
browser that the external file contains Java Script. In fact, putting script block tags in an external
file would prevent your code from executing.

If the examples in this section worked for you, then you have everything you need to proceed with
the rest of the examples in this ebook. You have just taken your first steps toward putting the
awesome power of Java Script programming in your hands!

Contents
Java Script Data Types

By Stephen Bucaro

Programs work with data. A data type specifies what kind of data, for example a number or a string
of characters. The type of a piece of data is important because it determines what kind of data can
be stored in it and what operations can be performed on it. For example, you can multiply the
number 2 by the number 3 to get the result 6. But if you multiply the character "2" by the
character "3", you get nonsense results.

Data types can be broken down into two categories, primitive and composite. Primitive data types,
like the integer, are the simplest. Composite data types, like the object, are composed of several
primitive data types.

Primitive Data Types

JavaScript supports several primitive data types.

• Integer
• Floating-point number
• String
• Boolean

Integers are whole numbers, either positive or negative. Integers are usually expressed in decimal
(base 10) notation, for example 123, but they can also be expressed in hexadecimal or octal
notation.

Hexidecimal (base 16) notation is commonly used when referring to data as it's stored in a
computers memory. A hexadecimal data type is indicated by starting a number with 0x, for
example 0x7aff.

Octal (base 8) notation was used when referring to data as its stored in a 4-bit memory cell and is
now obsolete. An Octal data type is indicated by starting a number with 0, for example 0275.

Floating-point numbers are fractional numbers, either positive or negative. Floating-point numbers
are usually expressed by including a decimal point, for example 123.45, but when expressing very
large or very small numbers, they can be expressed in exponential notation. Numbers expressed in
exponential notation include a decimal point along with the letter e, for example 1.234e8.

Strings are a row of one or more characters, for example a word or a paragraph. A string is
expressed by enclosing it in quotes, for example "hello". The quotes can be either single or double,
but the starting quote must match the ending quote. If you want to use a quote character within
your string, enclose the string in the opposite kind of quote, for example 'I said "hello" to you'.

Booleans are logical values that can be expressed as either true or false. Booleans are commonly
used when making tests or comparisons. For example, if logged-in equals true, then permit access,
if logged-in equals false, block access. During computation true evaluates to 1 and false evaluates
to 0.

Variables

A variable is a piece of data whos value may change during execution. The variable is identified by
a name. In Java Script a variable is identified by the keyword var. Below is an example of how to
create a variable named myName.

var myName;

• Variable names are case sensitive.
Undefined and Null

In addition to the four core data types, there are two other special data types.

• undefined
• null

undefined is the value held by a variable after it has been created, but before a value has been
assigned to it.

null is a value that means a variable contains nothing. null is not the same as 0, because 0 has a
mathematical value of zero, while null literally means nothing.

Literals

When you enter a data value into your code, it is called a "literal" because the value is not the
result of code execution, you "literally" provided the value in your code. A literal can be assigned to
a variable and, even though, initially, the literal and the variable are identical, the value in the
variable is not "literal" because the value of that variable can be modified by code execution.

Below is an example of a literal being assigned to a variable.

var strName = "Stephen";

In many programming languages, when you use a variable, you must state the type of the
variable, for example whether it is an integer, a string of characters, etc. Java Script automatically
allocates a variable of the correct type for the data that you assign to a variable.

We can modify the contents of the variable strName by execution of the code shown below (which
appends another literal to the first literal).

strName = strName += " Bucaro";

After execution the variable strName contains the string "Stephen Bucaro".

So a literal is the value to the right of the = sign, not the value contained in the variable after you
assign the literal to the variable.

If during execution, your code causes the data type to change, JavaScript automatically converts
between variable types.

Constants

A constant is a value that cannot be changed by program execution. A constant is identified by the
keyword const. You can initialize a constant through code execution, as shown below.

const a = b + c;

This is called a "run-time constant". Like a variable, the constant is created with a value of
"undefined". After you assign a value to a constant you can't change the value. You can use the
constant "a" as shown below;

var d = a + c;

But you can't use the constant "a" as shown below;

a = b + c;
Because this is an attempt to change the value of a constant, which is illegal.

• Constants, are not available in versions of Microsoft's JScript before JScript.net.

Using a Character String in a Mathematical Operation

If a variable is string type and you want to use it in a mathematical operation, use the built-in
function ParseInt() or ParseFloat() to convert the string to a number.

var strNum = “32”;
var strDen = “2.5”;
var nQuotient = ParseInt(strNum) / ParseFloat(strDen);

Using a Number in a String

If a variable is a number and you want to use it in a string, use the toString() method.

var nNum = 15.5;
var strNum = nNum.toString();

The typeof Operator

The JavaScript typeof operator can be used to determine the data type of a variable. The code
snippet below opens a messsage box that gives the type of data contained in the variable strName.

var strName = "Stephen";
alert("typeof strName = " + typeof(strName));

The variable was initialized with characters enclosed in quotes. The typeof operator returns
"string".

var total;
alert("typeof total = " + typeof(total));

The variable in the code above was not intialized with data before the call to the typeof operator, so
it returns "undefined".

var total = 45 + 55;
alert("typeof total = " + typeof(total));

The variable in the code above was intialized with digits not enclosed in quotes, so it returns
"number".

var total = 0x45 + 0x55;
alert("typeof total = " + typeof(total));

The variable in the code above was intialized with digits starting with 0x, indicating that they are
base 16. The typeof operator returns "number". Internally JavaScript stores Integers, regardless of
their base, as Floating-point numbers.

Contents

Reserved Words

By Stephen Bucaro
Reserved words or keywords are words that are part of the JavaScript language and therefor have
special meaning in Javascript. These reserved words, listed below, cannot be used for variable or
function names.

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

Contents

Java Script Strings

By Stephen Bucaro

In programming, the word "string" refers to an array of characters like a sentence or a paragraph.
JavaScript provides a built-in String object which provides you with many methods for searching
and manipulating strings. You can use the String object constructor to create a String object as
shown below.

<script type="text/javascript">
var myString = new String("This is my string.");
alert(myString);
</script>

Note that the string must be contained within quotation marks. In fact, when you assign a string of
characters within quotation marks to a variable in JavaScript, as shown below, it is automatically
converted to a string.

<script type="text/javascript">
var myString = "This is my string.";
alert(myString);
</script>

In fact, the keyword var is not strictly necessary, as the "=" character will automatically assume
that you are creating and assigning a variable, although I consider it bad programming practice to
leave it out.

Concatenating Strings

To concatenate means to connect together. If you need to concatenate two or more strings, you
can use the String object's concat method, as shown below.

<script type="text/javascript">
var firstString = "Now is the time for all good men ";
var secondString = "to come to the aid of their country.";

var myString = firstString.concat(secondString);
alert(myString);
</script>

In fact you can use the concat method to connect any number of strings together by separating the
strings names with commas, using the syntax shown below.

string.concat(string1, string2, ... ,stringN)

In fact, using the concat method is not strictly necessary, as you can use the "+" operator to
concatenate strings as shown below.

<script type="text/javascript">
var strFirst = "John";
var strLast = "Kennedy";
var strFull = strFirst + "F." + strLast;
alert(strFull);
</script>

Splitting Strings

What if you wanted to extract a substring from a string? For example, you might want to extract
the word "easy" from the sentence "JavaScript code is easy to read". First you could use the String
object's indexOf method to get the index of the first character of the word "easy".

Then you could use the indexOf method along with that previously obtained index to get the index
of the last character of the word "easy".

Finally, you could use the String object's substring method to get the substring between the
specified indexes, as shown below.

<script type="text/javascript">
var strSentence = "JavaScript code is easy to read.";

var first = strSentence.indexOf("easy");
var last = strSentence.indexOf("y", first);

var strEasy = strSentence.substring(first, last + 1);
alert("Extracted word: " + strEasy);
</script>

Note that the substring method returns the characters from the first index to the character Just
before the last index. Therefore, you have to add one to the last index to get the entire substring.

You could use a string as a database. Separate the data elements in the string with commas. This
is actually a common way to make small databases. It's called "comma-separated values" (CSV),
and supported by almost all spreadsheets and database management systems (The text file
containing the comma-separated values would have the file extension. csv).

To retrieve the data elements from the string containing the comma-separated values you could
repeatedly use something like the following statements.

<script type="text/javascript">
var strData = "data0,data1,data2,data3";
var loc1 = strData.indexOf(",");
var loc2 = strData.indexOf(",", loc1 + 1);

var dataElem = strData.substring(loc1 + 1, loc2);
alert("Data: " + dataElem);
</script>

But the String object already provides you with a method that does that for you. The split method
splits a string at the character that you specify.

<script type="text/javascript">
var strData = "data0,data1,data2,data3";
var strArray = strData.split(",");

alert("Data: " + strArray[2]);
</script>

The split method splits the string into pieces at the character that you specify (in this case
commas, and turns the substrings into an array. Then you use array notation to access the data.

Escape Codes

If you place certain characters within a string, it will cause an error. For example, if you place a
quotation mark within a string, it will cause an error. To use one of these characters within a string,
you need to replace them with their associated escape code. For example, the escape code for a
quotation mark is \".

var strQuote = "don\"t forget the escape code";

Escape Codes Used by JavaScript

\' single quotation mark
\" double quotation mark
\\ back slash
\r carriage return
\n new line
\t tab

Searching Strings

The positions of the characters in a string are numbered with indexes starting with 0. For example,
the index of the character "u" in the string "column" is 3. The JavaScript String object provides the
charAt(index) method which will return the character at any index in the string. The code below
demonstrates the use of this method.

<script type="text/javascript">
var strWord = "column";
var strLetter = strWord.charAt(3);
alert("the letter a index 3 is: " + strLetter);
</script>

The String object provides several methods that allow us to search for a character or substring
within a string. For example, the code below finds the word "easy" in the sentence "code is easy to
read".

<script type="text/javascript">
var strSentence = "code is easy to read";

var i = strSentence.indexOf("easy");

if(i < 0) alert("easy not found");
else alert("easy found at index: " + i);
</script>

After execution of the code, the variable i would contain the value 8. When the indexOf method
cannot find the indicated substring in the string, it returns the value -1. As you see in the code
above, we check for i being less than zero and then produce the proper message.

What if the sentence contains the word "easy" twice and we want to check only for the second one?
In that case, we would provide the indexOf method with a starting index from which to begin the
search.

<script type="text/javascript">
var strSentence = "this easy code is easy to read";

var i = strSentence.indexOf("easy", 10);

if(i < 0) alert("easy not found");
else alert("easy found at index: " + i);
</script>

The code above starts searching for the substring at index 10, which is past the first substring
"easy".

The string object also provides a method that will search for a substring starting from the end of
the string.

<script type="text/javascript">
var strSentence = "this easy code is easy to read";

var i = strSentence.lastIndexOf("easy");

if(i < 0) alert("easy not found");
else alert("easy found at index: " + i);
</script>

The code shown above will return the same index as the previous example, without requiring a
starting index. Even though it searches for a substring starting from the end of the string, it still
returns the index relative to 0 being at the beginning of the string.

What if you want to check an email address to make sure that it does not have a dot at the end?
That would indicate an invalid email address. You could use the String object's length property to
determine the length of the email address string. Then use the lastIndexOf method with length as a
starting index to retrieve the last character of the email address.

<script type="text/javascript">
var strEmail = "name@domain.com";
var len = strEmail.length;
var i = strEmail.lastIndexOf(".", len);
if(i == len - 1) alert("Invalid Email Adress");
else alert("Valid Email Adress");
</script>

Note in the code above that we subtract one from the length of the string before we compare it to
the index of the dot. Remember, because the indexes start with 0, the length of the string will be
one more than the highest index in the string.

Try the code above with and without the characters "com" on the end of the email address.

What if you wanted to compare the string "yesterday" with the string "Yesterday"? A comparison
would say that they are different because of the case difference in the first letter. But what if we
didn't care about case?

The String object contains two methods: toUppercase and toLowercase that let you change the
case of all the characters in a string. The code below uses the toUppercase method to change both
strings to all uppercase characters before making a comparison.
<script type="text/javascript">
var strOne = "yesterday";
var strTwo = "Yesterday";
if(strOne.toUpperCase() == strTwo.toUpperCase())
alert("The strings are identical");
else
alert("The strings are different");
</script>

Search and Replace Strings

Now for the grand finale example. We'll change the sentence "code is easy to read" into the
sentence "code is hard to read". If you can follow this, you have truly mastered the JavaScript
String object. First, extract a substring containing the part of the sentence up to the word "easy".

<script type="text/javascript">
var strSentence = "code is easy to read";

var last = strSentence.indexOf("easy");
var strBegin = strSentence.substring(0, last);

var first = strSentence.indexOf("y", last);
var len = strSentence.length;
var strEnd = strSentence.substring(first + 1, len);

var strNew = strBegin + "hard" + strEnd;
alert(strNew);
</script>

Next, extract a substring containing the part of the sentence after the word "easy". Then use the
concatenation operator to rebuild the new string.

The Java Script string object provides you with many methods for searching and manipulating
strings. In This article I provided you with examples of how to use the most important of these
methods. The string object has many other methods that you can use.

String Object Properties

length

String Object Methods

anchor(name)
big()
blink()
bold()
charAt(index)
fixed()
fontColor(color)
fontSize(size)
indexOf(substring,startIndex)
italics()
lastIndexOf(substring,startIndex)
link(ref)
small()
split(separator)
strike()
sub()
substring(startIndex,endIndex)
sup()
toLowercase()
toUppercase()
Contents

Java Script Arrays

By Stephen Bucaro

An array is defined as an ordered collection of data. You can visualize an array as a list, each item
in the list being identified by an index number starting with [0] for the first item.

An array can be used to store data that you allow users to search. This type of application mimics
the behavior of a database program. When designing a script, consider whether handling the data
as an array could have an advantage.

The browser itself creates a number of internal arrays for the html elements on your webpage. For
example, it maintains an array for the links on the webpage, the first link being identified as
document.links[0].

Use the new keyword to create an array. For example to create an array containing six names of
colors you might use the code shown below.

var strColor = new Array(6);

Then to enter data into the array, use statements indicating which index each string should be
assigned to, as shown below.

strColor[0] = "black";
strColor[1] = "blue";
strColor[2] = "green";
strColor[3] = "orange";
strColor[4] = "red";
strColor[5] = "white";

Java Script arrays have a length property. Using the declaration shown above, the strColor array is
explicitly defined to have a length of 6. However, Java Script arrays are dynamic, so you could
leave the length empty, as shown below.

var strColor = new Array();

This allows you to add items to the array at any time. In this case, the length property starts out
with a value of 0. You can assign a value to any index in the array and the length property will
automatically adjust for the new size of the array. If you know what the data will be, you can
declare and initialize the array at the same time as shown below.

var strColor = new Array("black", "blue", "green", "orange", "red", "white");

• JavaScript 1.2 allows you to construct an array without the new Array keywords, as shown below.

strColor = ["black", "blue", "green", "orange", "red", "white"]

In my opinion, this is bad programming practice because, the new keyword reminds the
programmer that a memory object has been created. Later in the script, when the data in the array
is no longer needed, the programmer may want to release the memory using the delete keyword.

You'll also note two other bad programming practices in the line above, the keyword var is missing
at the beginning of the declaration, and the semicolon is missing at the end. JavaScript permits this
type of sloppy programming, which results in many bugs and greater difficulty in locating the bugs.

Access an array element using its index. For example to access the array element "orange", in the
strColor array, use the code below.

var strFavorite = strColor[3];

• Remember, the first element in an array has the index 0. The last element in an array has an
index one less than the number of elements in the array, as indicated by the length property. For
example to access the last element in the strColor array ("white"), you could use the code below.

var strFavorite = strColor[strColor.length - 1];

Multidimensional Arrays

Java Script arrays can contain a variety of data types, for example strings, integers, floating point
numbers, and arrays. Assigning arrays as array elements allows you to create an array of arrays,
equivalent to a multidimensional array.

The multidimensional array shown below consists of an array of arrays which contain the names,
calories, and fat grams of sandwiches from various fast food companies.

var sandwich = [
["Arby-Q",360,4],
["Whopper",710,43],
["Chick-Fil-A",410,16],
["White Castle",140,7],
["Wendy's",410,19],
["Big Mac",600,33],
["Jack-n-box",310,14],
["Hardee's",850,57],
["Dairy Queen",290,12]
];

Note that I've used the shorthand method to construct this array. Otherwise I would need to use
the new Array keywords in each line, which would be a bit verbacious.

Use the statement shown below to access the fourth sandwich in the list.

var product = sandwich[3];

This would assign the White Castle sandwich array to the variable product. If you wanted to access
only the calories in a White Castle sandwich, you would use the statement shown below.

var product = sandwich[3][1];

Searching an Array

Note the resemblance of a multidimensional array to a database. Using simple Java Script code
along with Array object properties, you could use a multidimensional array to create a fairly
sophisticated database application.

One consideration in such a design would be the time required to transfer and load the entire
multidimensional array into the user's browser. You wouldn't want to use this technique for an
array containg millions of records. But it would be suitable for a database with up to several
thousand records.

If you wanted to search the sandwich array shown above for the sandwich with the lowest calories,
you could use the simple for loop shown below.

var lowestcal = sandwich[0][1];
for(var i = 0; i < sandwich.length; i++)
{
if(sandwich[i][1] < lowestcal)
{
lowestcal = sandwich[i][1];
}
}

alert(lowestcal);

The code initializes the variable lowestcal with the calories from the first element in the array, then
it loops through all the elements of the sandwich array replacing the value in lowestcal with a lower
value if it finds one.

Array Object Methods

concat(array)
Concatenate two arrays into a new array. Does not alter the two original arrays.
join(separator)
Returns the elements of the array delimited by a separator that you specify.
pop()
Performs the "stack" operation of returning and removing the last element of an array.
push(value)
Performs the "stack" operation of adding a value that you specify to the end of the array.
shift()
Performs the "stack" operation of returning and removing the first element of an array.
unshift(value)
Performs the "stack" operation of inserting a value that you specify to the beginning of the
array.
reverse()
Returns the elements of the array in order of last to first.
slice(StartIndex,endIndex)
Returns the elements of the array from a start index to an end index that you specify.
sort(compareFunction)
For an array of strings, returns the arrays elements sorted by ASCII code. For an array of
numbers, returns the arrays elements sorted by numeric value. Or returns the arrays
elements sorted by a function that you specify.
splice(startIndex,Count)
Returns part of the array from a start index to the number of elements that you specify.
toLocaleString()
Returns the elements from an array separated by commas.
toString()
Returns the elements from an array separated by commas.

An array is an ordered collection of data, each item of data being identified by an index number.
Java Script arrays can contain strings, integers, floating point numbers, and arrays. Assigning
arrays as array elements allows you to create a multidimensional array. Using simple Java Script
code along with Array object properties, you could use a multidimensional array to create a fairly
sophisticated database application.

Contents

Java Script Mathematics

By Stephen Bucaro

You can perform mathematical calculations with Java Script using normal mathematical notation as
shown below.
var nNumA = 9;
var nNumB = 4;
var nNumC = nNumA + nNumB;
var nNumD = nNumA * nNumB;
var nNumE = nNumA / nNUmB;

However, there are a few mathematical operators that you may not be familiar with. The modulus
operator (%) returns the remainder of a division rather than the quotient. The value in nNumC
below will be 2.

var nNumA = 12;
var nNumB = 5;
var nNumC = nNumA % nNumB;

The negation operator (-) returns the same result as multiplying the value by -1. The value in
nNumB below will be -8;

var nNumA = 8;
var nNumB = -nNumA;

Java Script provides the increment operator (++) to increase a value by one, and the decrement
operator to decrease a value by one. The value in nNumB below will be 4. The value in nNumC
below will be 2.

var nNumA = 3;
var nNumB = ++3;
var nNumC = --3;

Placing the increment or decrement operator in front of the variable means to increment (or
decrement) the value first before using it. Placing the increment or decrement operator in after the
variable means to use the value first, then increment (or decrement) it.

In the example below, the value of nNumB below will be 5, the value nNumA a will be 5. The value
of nNumD below will 4, the value of nNumC will be 5.

var nNumA = 4;
var nNumB = ++A;

var nNUmC = 4;
var nNUmD = A++;

In addition to using the mathematical notation described here, Java Script has a built-in Math
object gives you powerful routines that let you find Square root, logarithms, raise a number to a
power, perform trigonometric functions and much more. In addition it provides several properties,
such as the value of natural logarithm e, and the value of pi.

Contents

Java Script Math Object

By Stephen Bucaro

The JavaScript Math object gives you powerful routines that let you find Square root, logarithms,
raise a number to a power, perform trigonometric functions and much more. In addition it provides
several properties, such as the value of natural logarithm e, and the value of pi.

Math Object Properties
Property Value Description

Math.E 2.718281828459045091 Natural log

Math.LN2 0.6931471805599452862 Natural log of 2

Math.LN10 2.302585092994045901 Natural log of 10

Math.LOG2E 1.442695040888963387 Base-2 log of e

Math.LOG10E 0.4342944819032518167 base-10 Log of e

Math.PI 3.141592653589793116 pi

Because these properties return their values, you can use them like constants in your mathematical
expressions. For example, to obtain the circumference of a circle whose diameter is d, use the
statement below:

circumference = d * Math.PI

Math Object Methods

Method Returns
Math.abs(value) Absolute value
Math.acos(value) Arc cosine in radians
Math.asin(value) Arc sine in radians
Math.atan(value) Arc tangent in radians
Math.atan2(value1, value2) Angle of polar coordinates x and y
Math.ceil(value) Next integer greater than or equal to value
Math.cos(value) Cosine
Math.exp(value) Raise log e to the power of value
Math.floor(value) Next integer less than or equal to value
Math.log(value) Natural logarithm (base e)
Math.max(value1,value2) The greater of value1 or value2
Math.min(vallue1,value2) The lesser of value1 or value2
Math.pow(vallue1,value2) Value1 to the value2 power
Math.random() Random number between 0 and 1
Math.round(value) value + 1 when value >= value.5 otherwise value
Math.sin(value) Sine in radians
Math.sqrt(value) Square root
Math.tan(value) Tangent

Most Math object methods take one or two values as parameters, the only Math object method that
doesn't take a value as a parameter is the random method.

Contents

Assignment Operators

"Assignment" is when the code actually places a value into a variable. For example the equal sigh
below is used to assign the value 2 to the variable nNum.

nNum = 2;

If you want to confuse non-programmers, you can use special shorthand assignment operators that
perform a mathematical operation and assign a value at the same time. For example, the code
below assigns the value of nNum + 2 to nNum. The value of nNum below will be 5.

nNum = 3;
nNum += 2;

The code below does exactly the same thing.

nNum = 3;
nNum = nNum + 2;

Operator Alternate Code

nNum -= 3; nNum = nNum - 3;

nNum *= 3; nNum = nNum * 3;

nNum /= 3; nNum = nNum / 3;

nNum = nNum %
nNum %= 3;
3;

Contents

Comparison Operators

"Comparison" operators compare the values of two variables or statements and return the result of
the comparison as either true or false.

JavaSCript Comparison
Operators

operator comparison

> greater than

< less than

== equal to

!= not equal to
<= less than or equal to

>= greater than or equal to

The result of the comparison can be used to control the flow of the program. The if / else structure
is the most commonly used control structure.

nPrice = 29.00;
nHighest = 32.00;

if(nPrice < nHighest)
{
document.write("buy it!");
}
else
{
document.write("don\’t buy it.");
}

In the code shown above, the program would print “buy it.” because the value of nPrice is lower
than the value of nHighest. The comparison operator (<) returns true, and the code inside the “if”
block is executed.

If the value of nPrice was higher than the value of nHighest, the result of the comparison would be
false and the program flow would drop down to the else statement. The program would print "don’t
buy it."

The "if" structure is frequently used without the "else" block as shown below. In this case if the
value of nPrice was higher than the value of nHighest, the result of the comparison would be false
and the program flow would drop through, not printing anything.

nPrice = 29.00;
nHighest = 32.00;

if(nPrice < nHighest)
{
document.write(“buy it!”);
}
Another control structure is the “do / while’” loop as shown below.

nPrice = 64.00;
nHighest = 32.00;

do
{
--nPrice;
} while (nPrice > nHighest);

This structure executes the statement inside the brackets, decrementing the value of nPrice. Then
it performs a comparison to see if the value of nPrice is greater than the value of nHighest. If the
result of the comparison is “true”, the program executes the statement inside the brackets,
decrementing the value of nPrice again. This continues until the result of the comparison is “false”.
Then the program flow breaks out of the loop.

If you can figure out how the do loop control structure works, then you should be able to figure out
how all the basic control flow structures work. You will have no problem programming with
JavaScript, or with any other programming language for that matter, because all programming is
based on a few basic control structures.
Contents

Control Structures

if( comparison )
{
statements;
}

if( comparison )
{
statements;
}
else
{
statements;
}

switch( variable )
{
case (value_1):
statements;
break;
case (value_2):
statements;
break;
case (value_n):
statements;
break;
default:
statements;
break;
}

for(initial count; comparison; update counter)
{
statements;
}

while( comparison )
{
statements;
}

do
{
statements;
} while ( comparison );

We won’t go into detail on the control structures right now because here we are just introducing
them and the best way to learn control structures is to use them. But one thing we should know is
that the statement “break” can be used to break out of a loop, as shown below.

do
{
if(nPrice <= 0) break;
--nPrice;
} while (nPrice > nHighest);

In this code, we have included an “if” statement inside the "do" loop that checks for the condition
of the value nPrice being less than or equal to 0. If that condition is "true" we want to break out of
the loop, because less than or equal to 0 is not a valid value for nPrice.

This example also demonstrayes that control structures can be "nested". The "if" structure is
nested inside the "do / while" structure. This nesting can be done to any level, making it possible to
create incredibly powerful programs.

Contents

Logical Operators

What if you need to check the condition of more than one value in your control structure?
JavaScript provides “logical operators” for that purpose.

The most commonly used logical operators are && (And) and || Or. The example below executes
the phrase “if the value of nNumA or nNumB is less than nNumC, then execute the statements
within the block.

if(nNumA < nNumC || nNumB < nNumC)
{
statements;
}

Another logical operator is (!) Not. This operator changes a true boolean value to false, or a false
boolean value to true. In the code shown below, the comparison "is nNumA less than nNumB"
returns "false". But the "Not" operator changes it to "true" before returning it to the "if" control
structure, so the statements within the brackets would be executed.

nNumA = 10;
nNumB = 2;

if !(nNumA < nNumB)
{
statements;
}

Contents

Bitwise Operators

JavaScript also provides bitwise operators. These operators perform logical operations at the binary
bit level. Operators to shift the bits left or right within the data.

Bitwise Operators Used in JavaSCript

Operator Name Operation

& And Compares two bits, if both are 1, the result is 1

| Or Compares two bits, if one or the other is 1, the result is 1
Compares tw bits, if one or the other, but not both, is 1, the result
^ XOr
is 1

<< Shift left Shifts the bits to the left

Shift
>> Shifts the bits to the right
right

We won’t go into detail on the bitwise operators right now because they are used only in very
sophisticated programming. We will save learning how to do kind of programming for the future.

This article has provided you with an overview of the popular and powerful JavaScript web
programming language. In the next article we begin to do some hands-on programming.

Contents

Functions

A function is a block of code, or set of statements designed to perform a specific function. A
function has a name, one or more parameters can be passed into a function, and a function can
return a value.

The basic format for a function is shown below.

function functionName(parameter)
{
// lines of code
}

The function below receives a number and returns the square of that number

function square(nNumber)
{
return nNumber * nNumber;
}

Below is the code to test the square function.

<script language="JavaScript">

function square(number)
{
return number * number;
}

var nNum = 2;
var nSquare = square(nNum);

document.write("The square of " + nNum + " is " + nSquare);

</script>

A function can be designed to receive more than one parameter. The function below is passed two
numbers and returns their product.

function product(numberA, numberB)
{
return numberA * numberB;
}

Below is the code to test the product function.

<script language="JavaScript">

function product(numberA, numberB)
{
return numberA * numberB;
}

var nNumA = 2;
var nNumB = 3;
var nProduct = product(nNumA, nNumB);

document.write("The product of " + nNumA + " and " + nNumB + " is " + nProduct);
</script>

Contents

Recursion

Recursion is when a function calls itself. The standard example of recursion is a function that
calculates factorials. A factorial is defined by the formula below.

n! = n * (n - 1)! for n >= 1 with 0! = 1

For example 5! = 5 x 4 x 3 x 2 x 1

Below is a recursive function for calculating a factorial

function factorial(number)
{
if(number > 0)
{
return number * factorial(number - 1);
}
else
{
return 1
}
}

Below is the code to test the factorial function.

<script language="JavaScript">

function factorial(number)
{
if(number > 0)
{
return number * factorial(number - 1);
}
else
{
return 1
}
}

var nNum = 5;
var nFactorial = factorial(nNum);

document.write("The factorial of " + nNum + " is " + nFactorial);

</script>

Contents

Events

An event is a message sent by an object, such as the browser or an html element when a condition
exists. For example when the user clicks on a link, a click event occurs. When a user moves the
mouse pointer over a link, the mouseover event occurs.

List of Events

Event Occcurs When

abort USer cancels an action

blur the focus is removed from an element

click the user clicks on an event

change the value of a form field changes

error an error occurs

focus the focus is received by an element

load when a web page is loaded

when the mouse pointer moves off an
mouseout
element

when the mouse pointer moves over an
mouseover
element

reset when a form reset button is clicked

select when a form element is selected
submit when a form submit button is clicked

unload when a web page is unloaded

If you want to do something when a specific event occurs, you need to create an "event handler".
An event handler is a function that is executed in response to the event.

For example lets say that we wanted to inform the user of the number of times that they clicked on
an image. Below is a counting function.

var nCount;
nCount = 0;
function count()
{
nCount++;
}

Below is the code to test the count function.

<script language="JavaScript">

var nCount;
nCount = 0;
function count()
{
nCount++;
alert("you clicked " + nCount + " times");
}

</script>
<img height=35 width=34 src="x.gif" onClick="count();">

The above code shows the format to use the count function as an event handler for the images
click event. To use any event handler you would use the name of the event prefixed with "on".

Contents

Using the Java Script Date Object

By Stephen Bucaro

When you want to work with a date in Java Script, you need to create a Date object. The code
shown below creates a Date object and uses it to display today's date in a message box.

var today = new Date();
alert(today);

• If you want to follow along and get some hands-on experience, create a new file in Windows
Notepad or your favorite ASCII text editor and type in the html code shown below.

<html>
<body>
<script type="text/javascript">

... JavaScript code here ...

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

Save the file with the extension .htm. For each example, replace the text "... JavaScript code here
..." with the example code. Resave the file, then double-click on the file name to execute the
example.

If you're using Internet Explorer, you'll receive the message "Internet Explorer has restricted this
webpage from running scripts". Right-click on the message and in the popup menu that appears,
select "Allow Blocked Content...". This is how Microsoft Expects to protect Windows, by making it
annoying and unusable.

The Date object constructor reads the computers internal clock. The internal value in a Date object
is the number of milliseconds since midnight January 1, 1970 in GMT (Greenwich Mean Time).

• In the old days, we used to call this "Greenwich Meridian Time", because it's the time at Earth's 0
degrees longitude line, which happens to pass through the city of Greenwich, England, where they
have the over 325 year old Greenwich Observatory. But apparently some people couldn't figure out
what a "Meridian" was, so they changed it to "Mean". Today, most people use UTC (Coordinated
Universal Time), which is GMT based on an atomic clock and expressed as a 24 hour clock.

The date in the Date object is a static date, it will not change over time, you need to update it
programmatically. When you display the contents of a Date object, JavaScript converts it to the
local time zone as configured in your PC's Control Panel.

Getting Past or Future Dates

You can get a date from the past or future by passing a date, formatted as yyyy,mm,dd to the Date
object, as shown below.

var pastDate = new Date(2007,11,18);
alert(pastDate);

• Note: The Date object uses a zero-based month, with January being month 0. In other words,
subtract 1 from the number of the month that you pass to the Date object.

You can also get a date from the past or future by adding or subtracting the required number of
milliseconds from the current date, as shown below.

var today = new Date();
var todayMS = today.getTime();
var nextWeekMS = todayMS + (60 * 60 * 24 * 7 * 1000);
var nextWeek = new Date(nextWeekMS);
alert(nextWeek);

In this example, after we create a Date object, we use it's getTime method to retrieve it's contents
(the number of milliseconds since midnight January 1, 1970). Then we add a weeks worth of
milliseconds (calculated as shown below) to that value.

60 seconds in a minute * 60 minutes in an hour * 24 hours in a day * 7 days in a week * 1000
milliseconds in a second.

Then we create a new Date object, named nextWeek, passing the new milliseconds value to its
constructor. When we display this new Date object, it will contain the date one week from now,
including the day of the week.

• In the first example, we passed nothing to the Date object constructor. In the last example, we
passed a formatted date to the Date object constructor. This time we passed the number of
milliseconds. The ability to pass different parameters to a method with the same name is called
"overloading" in object-oriented programming. The first example, where we passed nothing, is
called the "default" constructor.

Find the Difference Between Two Dates

We can use the Date objects getTime method to get dates milliseconds, then we can subtract two
dates to determine the time interval between them. In the example below, I used the Math objects
abs method to remove the minus sign in case you want to use the code to subtract a more recent
date from an older date.

var date1 = new Date(2007,11,19);
var date2 = new Date(1948,8,17);
var difference = Math.abs(date1.getTime() - date2.getTime());

var years = Math.floor(difference/(60 * 60 * 24 * 365 * 1000));
var remainder = difference%(60 * 60 * 24 * 365 * 1000);
var months = Math.floor(remainder/(60 * 60 * 24 * 30 * 1000));
remainder = remainder%(60 * 60 * 24 * 30 * 1000);
var days = remainder/(60 * 60 * 24 * 1000);

alert(years + " years " + months + " months " + days + " days");

You can study the code that I used to convert the difference value (in milliseconds) to display as
years, months, and days. Note that here I assume that the number of days per month in the time
between the two dates averages out to 30. An experienced programmer might figure out how to
make this more exact. Also note that there is no reason you couldn't continue on to display the
number of seconds and even milliseconds.

Formatting Date Strings

When I executed the code in the first example, the message box displayed "Thu Dec 20 08:35:42
MST 2007". (The MST stands for Mountain Standard Time). This may not be your desired display
format. You can use the Date object's getMonth, getDate, and getFullYear methods to display the
date in the mm,dd,yyyy format, as shown below.

var today = new Date();
var month = today.getMonth() + 1;
var day = today.getDate();
var year = today.getFullYear();
alert(month + "/" + day + "/" + year);

You can use the Date object's getMonth, getDay, and getFullYear methods to display the date in
the Day of Week, Month, Date, Year format, as shown below.

month = new Array("January","February","March","April","May","June",
"July","August","September","October","November","December");
day = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday");

var today = new Date();
alert(day[today.getDay()] + " " + month[today.getMonth()] + " " +
today.getDate() + " " + today.getFullYear());

The code uses a month array, initialized with the names of the months, and a day array, initialized
with the names of the days of the week. The important thing to remember to understand the code
is that the getMonth method returns a zero-based month, with January being month 0, and the
getDay method returns a zero-based day of the week, Sunday being day 0.

Using the four methods from these examples (getMonth, getDate, getDay, and getFullYear) you
should be able to format a date string any way that you desire.

Validating Date Strings

One place were you might need to validate a date string is when it's source is a user entry from a
form text box. There are several ways to validate a date string. One way would be to slice and dice
the date string using string object methods. That's a whole other article.

Another method is to use a regular expression. That's a whole other article too, in fact whole books
have been written about using regular expressions. Regular expressions can get very complicated
and are kind of like a whole programming language in itself, or a form of mathematics. However,
I'll give you a basic example here with a short explanation.

The example below validates that the date string is in the format mm/dd/yyyy.

var exp = /^(0?[1-9]|1[0-2])\/(0?[1-9]|[1-2][0-9]|3[0-1])\/((18|19|20)\d{2})$/;
var inDate = "12/19/2007";
if(inDate.match(exp)) alert("Date Format OK");
else alert("Incorrect Date Format");

The first line of this code declares a regular expression. A regular expression might be thought of
as a template that the comparison string must match. To declare a regular expression in
JavaScript, put a forward slash at the beginning and at the end. The /^ indicates the beginning of a
string. The $/ indicates the end of a string. The comparison string must match the regular
expression enclosed in /^ $/.

The first regular expression in parentheses, (0?[1-9]|1[0-2]) matches the month. The | (pipe)
means the comparison characters must match either the part on the left, or the part on the right.

Looking to the left of the pipe, it says the comparison characters can have a first digit of 0 or no
first character, and the second character can be a digit between 1 and 9. Looking to the left of the
pipe, it says the comparison characters can be a 1 followed by a digit between 0 and 2. In other
words, for example, the month September may be entered as 09 or just 9.

Note that the regular expression within parentheses are separated by the characters \/. this is an
an escape sequence meaning match a forward slash. The second regular expression in parentheses
matches the day. The last regular expression in parentheses matches the year.

The remaining parts of the regular expression follow the same rules, except for the pattern d{2} at
the end of the last regular expression, which means the second part of the year can be two digits
(00-99).

The second line in the code is the date string to test, which would normally come from a user entry
from a form text box. The third line in the code uses the string object's match method, which
returns null if the regular expression doesn't match the string.

Regular expressions can get very complicated, and are probably useful only to those who like to
work puzzles. But if you can design a regular expression, it's a very terse and efficient way to solve
a programming problem.

Using the Java Script Date Object

When you want to work with a date in Java Script, you need to use the Date object. In this article,
you learned how to create a Date object for today, or for any date in the past or future. You
learned how to find the difference between two dates, and how to format a date string any way
that you desire. You also learned how to validate a date string returned from a text box in a form.
This involved an introduction to JavaScript regular expressions.

Contents
Objects

Objects are containers for the properties and methods owned by an element.

Note: When referring to a function that belongs to an object, that function is called a method.

For example a button is an object. A button has properties such as name, type, and value. A button
also has methods such as click().

When referring to an objects property or method, use the "dot" reference. For example to reference
the click() method of a button named clickme, you would use clickme.click().

The button object may be owned by a form object named testform, and the form is owned by the
document object. So the complete reference to the clickme button's click() method is
document.testform.clickme.click().

Using the above reference you could execute the click method of the button, simulating a mouse
click. An example of the code for this is shown below.

<form name="testform">
<input name="clickme" type="button" value="Test" onClick="alert('Click!');">
</form>
<img src="x.gif" OnMouseover="document.testform.clickme.click()">

Contents

The Document Object Model (DOM)

By Stephen Bucaro

The elements on a Web page are arranged like branches on a tree (more like an inverted tree,
since the root is the top). Each html element represents a node in the DOM tree. Each html
element is defined by an opening tag and a closing tag. An Html element that is nested inside
another tag is a child node of that parent node.

The purpose of the DOM is to provide an operating system and programming language independent
interface to the elements on a Web page. This allows designers using different platforms and
languages to modify and style Web pages. Unfortunately, things didn't start out that way.

The browser world started out with two competing models, one created for Netscape Navigator, the
other for Microsoft Internet Explorer. Unfortunately, the two object models were not entirely
compatible. As each company released new versions of their browsers, they used object models
that were not completely compatible with that companies previous version. Finally the World Wide
Consortium (W3C) was established to create an international standard. Unfortunately, that
compounded the problem.

The W3C created the W3C DOM which was not entirely compatible with neither Netscape's nor
Microsoft's browser model. Then the W3C released the W3C DOM Level 2, and W3C DOM Level 3
standards. Now we have a whole pile of incompatible standards, leaving designers leafing through
dog-eared compatibility charts, while writing convoluted browser detection algorithms (none of
which ever performed properly).

Ultimately all browsers are supposed to comply with the latest W3C standard, and browser
developers are working to achieve that goal - but it won't happen any time soon. However, after
leafing through your latest compatibility charts, you'll learn that, at least in the basic DOM, a higher
level of compatibility has been achieved. The secret to good web design is to use a conservative
approach.

Don't try to design for compatibility with browsers more than one version previous to the latest
release. Those old browsers are used by only a tiny segment of users, and that is not the big-
spender segment. Don't try to design for the latest gee-wiz trivial feature of the latest browser
versions, stick with the core basic DOM, which has the most universal compatibility.

The DOM chart provided here shows only part of the DOM. I would have liked to provided a more
complete chart, but I can't find an example of a DOM chart that is complete without getting overly
complex.

[window (self, parent, top, window, frames[])]

• [navigator]
• [mime Types[]]
• [plugins[]]
• history
• location
• [document]
• [head]
• [title]
• [style]
• [script]
• [body]
• [links[]]
• [anchors[]]
• [applets[]]
• [objects[]]
• [images[]]
• [div]
• [span]
• [p]
• [br]
• [hr]
• [table]
• [tr]
• [td]
• [ol]
• [li]
• [ul]
• [li]
• [forms[]]
• [text]
• [password]
• [textarea]
• [fileUpload]
• [hidden]
• [radio]
• [checkbox]
• [button]
• [reset]
• [submit]
• [select]
• [options[]]

As I stated at the beginning of this article, the purpose of the DOM is provide a programming
interface to the elements on a Web page. The best way to get programming access to an element
on a Web page is to give that element a unique id attribute, as shown below.

<div id="container"></div>

The statement above gives the html div element the id "container". You can then create a variable
that gives you access that div using the document.getElementById method as shown below.

var container = document.getElementById("container");

You can use that variable to dynamically (in other words - without accessing the sever to reload the
page) modify the div. For example, the statement shown below replaces the text in the div with the
text "place this text inside the div".

container.innerHTML = "place this text inside the div";

Using the innerHTML method, the text would be interpreted as html code. In other words if your
entire web page contents was inside the div, you could use this method to programmatically
upadate it. This shows you the power of the DOM.

Contents

Window Object

The window object is at the root of the document object model hierarchy. Using the window object
you can:

• Create new browser windows
• Create popup windows
• Manipulate existing windows

Window Object Properties:

name The name that the window can be referenced by
opener Reference to the window that opened this one
parent Reference to the window that opened this one
self Reference to this window
status The browser window status message
top The topmost browser window

Window Object Methods:

blur() Makes the window inactive
clearTimeOut(timerID) Cancels a timer
close() Closes the windows
focus() Makes the window active
open("URL","name","features Creates a new browser window
") Scrolls the window to the specified
scroll(x,y) coordinates
setTimeOut("function",ms) Sets a timer that calls the specified function

Window Object Events:

onBlur Occurs when a window is deactivated
onFocus Occurs when a window is activated
onLoad Occurs when a document is loaded
onUnLoad Occurs when a document is unloaded
Opening a browser window with JavaScript is extremely easy. If you don't believe me, type this
text into your web page.

<script>open()</script>

When you open your web page, a popup window named about:blank will appear.

In the code above we have used the fact that the browser defaults to Java Script. Proper coding
would have specified the script language and assigned the window to a variable so that we could
use that variable to control the window after we create it. The example below shows the proper
code to create a window and load a web page named mypage.htm into the window.

<script language="JavaScript">
var myPopUp = window.open("mypage.htm","pop_window");
</script>

Of course, you don't have to load a local web page into the window, you can put any URL in the
first argument of the window.open function. Note the second argument of the window.open
function, "pop_window". This gives the window a name that you can use to load a different page
into the window, as shown below.

<a href="mypage2.htm" target="pop_window">Link Text</a>

You can add a third argument, called the "features list", to the window.open function. Below is a list
of the features that you can specify.

location of the left border of the window in pixels from the left side of the
left
screen

location of the top border of the window in pixels from the top of the
top
screen

width width of the window in pixels

height height of the window in pixels

menubar specifies the menu bar

toolbar specifies the tool bar

location specifies the address bar

scrollbars specifies scrollbars

status specifies the status bar

resize specifies whether the window can be resized by the user

Assigning a feature the value 1 provides the feature. Assigning a feature the value 0 prevents the
feature. The example below creates a window with a menu bar and address bar, but no tool bar.
Note that the feature specifications are separated by commas, and you can put them in any order.

<script language="JavaScript">
var myPopUp = window.open("mypage.htm","pop_window","menubar=1,
location=1,toolbar=0");

</script>

What happens if you omit the specification of a feature? That depends on the browser version used
to view the page. In some browsers, features not specified appear by default. In some browsers
features not specified are not provided by default. To get reliable results, you should always specify
all the features.

If you like to reuse code, you can specify the features list in a string variable and then use that
variable name as the features list argument in the window.open function. This will prevent you
from having to memorize the features list.

<script language="JavaScript">
var features = "left=100,top=100,width=256,height=256,menubar=1,
toolbar=0,location=0,scrollbars=0,status=0";
var myPopUp = window.open("mypage.htm","pop_window",features);
</script>

In the examples we placed the window.open function in-line in the web page. This way the popup
window is created every time the web page loads. You can have more control over when your
window opens if you place the window.open function inside your own Java Script function as shown
below.

<script language="JavaScript">
var myPopUp
function openWindow()
{
var features = "left=100,top=100,width=256,height=256,menubar=1,
toolbar=0,location=0,scrollbars=1,status=1";
myPopUp = window.open("mypage.htm","new_pop_window",features);
}
</script>

The optimum place to put this function is in the HEAD section of your web page. That way the
function is defined before the body of your web page is loaded. Placing your window opening code
in a function in the HEAD of your web page lets you control when and how the window opens.
Below are some examples.

1. To open a window when your web page loads. Call your function from the onLoad event in the
BODY tag of your web page.

<body onLoad="openWindow();">

2. To open a window when the user clicks on a link. Call your function from the onClick event in the
link.

<a href="#" onClick="openWindow();">Link Text</a>

3. The URL "#" in the link above causes your web page to scroll to the top. You may not want that.
To avoid scrolling to the top of your web page, call your function from the onClick event of a form
button.

<input type="button" value="Open Window" onClick="openWindow();">

Note in the code above, we do not explicitly code a form. What happens is a default form is defined
in the forms array. You could properly code a form for the button, but it's not really necessary so
we won't get into that now.

To close a window in Java Script, you would use the window.close function. The window.close
function can be called by any of the methods described above. The most popular method is to call
the function in the onUnload event in the body tag. This way a popup window created by a web
page can be closed automatically when the user leaves the page.

<body onUnload="myPopUp.close();">

Another popular method to close a window is by placing a link or button in the popup window itself.

<input type="button" value="Close Me" onClick="window.close();">

This article gives you the basics of designing, opening, and closing browser windows using Java
Script. There is a lot more we can do with windows. For example we could improve our
openWindow function to accept the name of a web page as an argument. We could write scrolling
messages to the windows status bar. In future articles, I will show you how to do all kinds of
annoying things with windows using Java Script.

Contents

History Object

When you view pages in your browser window, it keeps a list of the pages that you visited in the
window.history object. Using scripts, you can make the browser move back to previously viewed
pages, and forward again through the history list.

History Object Methods

back()
forward()
go(int | "URL" | "Title")

The code below shows how to use the onClick event of a button with the history object to duplicate
the effect of the browsers toolbar back and forward buttons.

<input type="button" value="Back" onClick="history.back()">

<input type="button" value="Forward" onClick="history.forward()">

The go() method can accept either the URL or the title of a Web page. When executed, the go()
method will search the history list for a match and then load the corresponding page. But of course
the requested page must have been previously visited in order to be in the history list.

The go() method will also accept an integer defining how many entries to go back or forward in the
history list. Move back in the history list by using a negative number. Move forward in the history
list by using a positive number.

Contents

Location Object

When you load a Web page into your browser, the path or URL to that page is stored in the
window.location object. You can retrieve the page's path or URL from the location object, or you
can load a different page into the window by using the location objects replace("URL") method.

Location Object Properties

href The URL of the current page
pathname The path relative to the current directory
search The form post information

Location Object Methods

reload() Reloads the current page
replace("URL") Loads the specified URL

Contents

Document Object

The document object may be the most frequently utilized object of the DOM. It has many
properties and methods that can be used by scripts and you can use the document to access the
objects in the document.

Document Object Properties

alinkColor color of the active link
anchors[i] anchors array
bgcolor background color
cookie stores and retrieves cookies
fgcolor text color
forms[i] forms array
images[i] images array
lastModified date document was last modified
linkColor color of links
links[i] links array
location the documents URL
title the documents title
vlinkColor color of visited links

Document Object Properties Methods

removes the document from the window
clear()
closes the write stream to the document
close()
opens the write stream to the documen
open()
writes a string to the document
write("string")
writes a string to the document, placing a carriage
writeln("string")
return and line feed on the end of the string

Contents
WARNING! What you learn from these totally
FREE newsletters could cause your friends to
mistake you for someone else!

[] home/garden
[] automobiles
[] humor
[] business
[] marketing
[] parenting
[] investing
[] computers
[] pets
[] contests
[] inspiration
[] education
[] self-improve
[] entertainment
[] recreation
[] food/wine
[] travel
[] free stuff
[] womens stuff
[] genealogy
[]
[] health/fitness
writing/reading

Click here and choose as many as you like!

Visit Bucaro Techelp to download FREE ebooks including Bucaro TecHelp s popular PC Tech Toolkit.
Read Bucaro TecHelp's famous Easy Java Script and Easy CSS tutorials with cut-and-paste code.
Learn Basic PC Anatomy and where to find FREE diagnostic Tools and technical assistance. Learn
how to start your own online business, including many examples of people who started successful
businesses.

To receive an email notification when new articles, ebooks, clipart, graphics, or other content has
been added to Bucaro Techelp, Click Here to subscribe to Bucaro TecHelp News Feed Notification.