Sie sind auf Seite 1von 192

GIAO TRNH DAY HOC NOI DUNG : JAVASCRIPT

Kien thc phai co: HTML

: Basic Level

Collected by Nhat Duy Nguyen nhatnd@hcm.fpt.vn Source : www.w3schools.com

TP.HCM, 27-08-2004

Table of Content
JS JS JS JS JS JS JS JS JS JS JS JS JS JS JS JS JS Basic HOME.............................................................................................................................................6 Introduction...................................................................................................................................6 How To...........................................................................................................................................7 Where To.......................................................................................................................................8 Variables......................................................................................................................................11 Operators.....................................................................................................................................12 Functions.....................................................................................................................................14 Conditional...................................................................................................................................18 Looping........................................................................................................................................23 Guidelines....................................................................................................................................26 Objects Array............................................................................................................................................28 Boolean........................................................................................................................................34 Date.............................................................................................................................................36 Math.............................................................................................................................................42 String...........................................................................................................................................44

JS DOM JS HTML DOM....................................................................................................................................48 Examples JS DOM Examples..............................................................................................................................50

Anchor Object.................................................................................................132
Change URL and text of a hyperlink............................................................................................49 Change the target attribute of a link...........................................................................................49 Using focus() and blur()............................................................................................................50 Anchors array..........................................................................................................................51

Applet Object..................................................................................................134 Area Object.....................................................................................................135 Base Object....................................................................................................135 Basefont Object..............................................................................................137 Body Object....................................................................................................137 Button Object.................................................................................................138
Create a button........................................................................................................................53 Click on a button and display the name of the form.......................................................................53 Click on a button and display the names of all the elements in a form.............................................54

Checkbox Object.............................................................................................139
Check and uncheck a checkbox..................................................................................................54 Checkboxes in a form...............................................................................................................55 Checkbox................................................................................................................................56

Document Object............................................................................................141
Write text to the output............................................................................................................57 Write text with formatting to the output......................................................................................57

Return the number of anchors in a document...............................................................................58 Return the domain name of the document's server.......................................................................58 Return the referrer of a document..............................................................................................58 Return the title of a document...................................................................................................59 Return the URL of a document...................................................................................................59 Return a specified element, using getElementById().....................................................................60 Return the number of elements with equal names, using getElementsByName()...............................61 Open a new document and add some text...................................................................................61 Open a new document specifying mime type and replace...............................................................62 Count forms in a document........................................................................................................63 Count images in a document......................................................................................................63 Access an item in a collection.....................................................................................................64

Event Object...................................................................................................143
Which mouse button was clicked?...............................................................................................65 What are the coordinates of the cursor?......................................................................................65 What is the unicode of the key pressed?......................................................................................66 What are the coordinates of the cursor, relative to the screen?.......................................................67 What are the coordinates of the cursor?......................................................................................67 Was the shift key pressed?........................................................................................................68 Which element was clicked?.......................................................................................................69 Which eventype occured?..........................................................................................................70

FileUpload Object............................................................................................145 Form Object....................................................................................................146


View and change the action URL of a form...................................................................................70 Return the method used when sending form data.........................................................................71 Reset the fields in a form..........................................................................................................72 Submitting a form....................................................................................................................73 Validate an e-mail address in a form...........................................................................................73 Validate an input field with minimum and maximum values............................................................74 Validate an input field with a maximum number of characters........................................................75 Form validation........................................................................................................................76 Set focus to an input field..........................................................................................................77 Select the content of an input field.............................................................................................77 Radio buttons in a form.............................................................................................................78 Checkboxes in a form...............................................................................................................78 Dropdown list in a form.............................................................................................................80 Another dropdown list...............................................................................................................81 A select-menu in a form............................................................................................................82 Jump to the next field when the current field's maxlength has been reached....................................82

Frame, Frameset.............................................................................................148
Make the frames resizable and not resizable................................................................................84 Frames with and without scrollbars.............................................................................................85 Change the source of frames.....................................................................................................86 Break out of a frame.................................................................................................................87 Update two other frames..........................................................................................................88 Update two iframes IE and Opera only.........................................................................................................................89

Hidden Object.................................................................................................150 History Object.................................................................................................151 IFrame Objects...............................................................................................151 Image Object..................................................................................................153


Change the height of an image..................................................................................................89 Change image........................................................................................................................90

Link Objects....................................................................................................154 Location Object...............................................................................................155


Send the client to a new location (URL/page)...............................................................................90 Refresh a document.................................................................................................................91

Meta Objects...................................................................................................156 Navigator Object.............................................................................................156


How to detect the client's browser..............................................................................................92 More details about the client's browser........................................................................................92 All details about the client's browser...........................................................................................93 Redirect user depending on browser...........................................................................................94

Option and Select Objects...............................................................................158


Disable and enable a dropdown list.............................................................................................95 Return the name of the form that contains the dropdown list..........................................................96 Return the number of options in the dropdown list........................................................................97 Change the size of a dropdown list.............................................................................................97 Select multiple options in a dropdown list....................................................................................98 Return the selected option as text..............................................................................................99 Return the selected option as a number.....................................................................................100 Change the option text............................................................................................................101 Remove an option from a dropdown list.....................................................................................102

Password Objects...........................................................................................159 Radio Objects..................................................................................................160 Reset Objects..................................................................................................162 Screen Object.................................................................................................163 Select Objects.................................................................................................164 Style Objects...................................................................................................165 Submit Objects...............................................................................................172
Detect details about the client's screen......................................................................................103

Table Object...................................................................................................173
Change the width of a table border...........................................................................................104 Change the cellPadding and cellSpacing of a table.......................................................................105 Specify frames of a table.........................................................................................................106 Change height of a row...........................................................................................................107 Specify rules for a table...........................................................................................................108 Create a caption for a table......................................................................................................108 Deleting rows in a table...........................................................................................................110 Adding rows to a table............................................................................................................111 Align the cell content in a table row..........................................................................................112 Change the cell content in a table row.......................................................................................113 Vertical align the cell content in a table row...............................................................................114 Align the cell content in a single cell..........................................................................................116 Vertical align the cell content in a single cell...............................................................................117 Adding cells to a table row.......................................................................................................117 Change the colspan of a table row............................................................................................118

TableData Objects...........................................................................................176

TableHeader Objects.......................................................................................178 TableRow Objects...........................................................................................180 Text Objects...................................................................................................182 Textarea Objects.............................................................................................183 Window Object...............................................................................................185
Display an alert box................................................................................................................119 Alert box with line-breaks........................................................................................................119 Display a confirm box.............................................................................................................120 Display a prompt box..............................................................................................................120 Open a new window when clicking on a button...........................................................................121 Open a new window and control its appearance..........................................................................122 Open multiple windows with one click Send the client to a new location (URL/page) Refresh a document Write some text in the windows status bar Print a page...........................................................................................................................123 Trapped in a frame? This is how you break out of frames Update 2 frames with one click Update 2 other frames Resize a window Resize a window to a specified size...........................................................................................124 Scroll the window...................................................................................................................124 Scroll the window to a specified position....................................................................................127 The setInterval() and clearInterval() methods............................................................................128 The setTimeout() method........................................................................................................130 The setTimeout() method with a pointer to a function..................................................................130 The setTimeout() method with a pointer to a function 2...............................................................130 Create a pop-up.....................................................................................................................131

Introduction to JavaScript
JavaScript is used in millions of Web pages to improve the design, validate forms, and much more. JavaScript was developed by Netscape and is the most popular scripting language on the internet. JavaScript works in all major browsers that are version 3.0 or higher.

What You Should Already Know


Before you continue you should have a basic understanding of the following:

WWW, HTML and the basics of building Web pages

If you want to study these subjects first, go to our Home Page.

What is JavaScript?
JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language - a scripting language is a lightweight programming language A JavaScript is lines of executable computer code A JavaScript is usually embedded directly in HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license JavaScript is supported by all major browsers, like Netscape and Internet Explorer

Are Java and JavaScript the same?


NO! Java and JavaScript are two completely different languages! Java (developed by Sun Microsystems) is a powerful and very complex programming language - in the same category as C and C++.

What can a JavaScript Do?


JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server, this will save the server from extra processing

JavaScript How To ...


The HTML <script> tag is used to insert a JavaScript into an HTML page.

Examples
Write text How to write text on a page. Write text with formatting How to format the text on your page with HTML tags. <html> <body> <script type="text/javascript"> document.write("<h1>Hello World!</h1>") </script> </body> </html>

Hello World!

How to Put a JavaScript Into an HTML Page


<html> <body>

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


</body> </html>

The code above will produce this output on an HTML page: Hello World! Example Explained To insert a script in an HTML page, we use the <script> tag. Use the type attribute to define the scripting language

<script type="text/javascript">
Then the JavaScript starts: The JavaScript command for writing some output to a page is document.write

document.write("Hello World!")
7

Then the <script> tag has to be closed

</script>
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.

How to Handle Older Browsers


Browsers that do not support scripts will display the script as page content. To prevent them from doing this, we may use the HTML comment tag:

<script type="text/javascript"> <!-some statements

//--> </script>
The two forward slashes at the end of comment line (//) are a JavaScript comment symbol. This prevents the JavaScript compiler from compiling the line. Note: You cannot put // in front of the first comment line (like //<!--), because older browsers will display it. Strange? Yes! But that's the way it is.

JavaScript Where To ...


Scripts in the body section will be executed WHILE the page loads. Scripts in the head section will be executed when CALLED.

Examples
Head section Scripts that contain functions go in the head section of the document. Then we can be sure that the script is loaded before the function is called. <html> <head> <script type="text/javascript"> function message() {

alert("This alert box was called with the onload event") } </script> </head> <body onload="message()"> </body> </html> Body section Execute a script that is placed in the body section. <html> <head> </head> <body> <script type="text/javascript"> document.write("This message is written when the page loads") </script> </body> </html> External script How to access an external script. <html> <head> </head> <body> <script src="xxx.js"> </script> <p> The actual script is in an external script file called "xxx.js". </p> </body>

</html>

Where to Put the JavaScript


Scripts 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">
some statements

</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">
some statements

</script>
</body>
Scripts in both the body and the head section: You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.

<html> <head>

<script type="text/javascript">
some statements

</script>
</head> <body>

<script type="text/javascript">
some statements

</script>
</body>

How to Run an External JavaScript


Sometimes you might want to run the same script on several pages, without writing the script on each and every page. To simplify this you can write a script in an external file, and save it with a .js file extension, like this:

document.write("This script is external")


Save the external file as xxx.js.

10

Note: The external script cannot contain the <script> tag Now you can call this script, using the "src" attribute, from any of your pages:

<html> <head> </head> <body>

<script src="xxx.js"></script>
</body> </html>

Remember to place the script exactly where you normally would write the script.

JavaScript Variables
A variable is a "container" for information you want to store.

Examples
Variable Variables are used to store data. This example will show you how.

Variables
A variable is a "container" for information you want to store. A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value. Rules for Variable names:

Variable names are case sensitive They must begin with a letter or the underscore character

Declare a Variable
You can create a variable with the var statement:

var strname = some value


You can also create a variable without the var statement:

strname = some value

Assign a Value to a Variable


You assign a value to a variable like this:

var strname = "Hege"

11

Or like this:

strname = "Hege"
The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the variable "strname" has the value "Hege".

Lifetime of Variables
When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.

JavaScript Operators
Operators are used to operate on values.

Arithmetic Operators
Operator + * / % Description Addition Subtraction Multiplication Division Modulus (division remainder) Example x=2 x+2 x=2 5-x x=4 x*5 15/5 5/2 5%2 10%8 10%2 x=5 x++ x=5 x-Result 4 3 20 3 2.5 1 2 0 x=6 x=4

++ --

Increment Decrement

Assignment 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

12

Operator == != > < >= <=

Description is equal to is not equal is greater than is less than is greater than or equal to is less than or equal to

Example 5==8 returns false 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 Example x=6 y=3 (x < 10 && y > 1) returns true || or x=6 y=3 (x==5 || y==5) returns false ! not x=6 y=3 !(x==y) returns true

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" txt2="nice day!" txt3=txt1+txt2


The variable txt3 now contains "What a verynice day!". To add a space between two string variables, insert a space into the expression, OR in one of the strings.

txt1="What a very" txt2="nice day!" txt3=txt1+" "+txt2 or txt1="What a very " txt2="nice day!" txt3=txt1+txt2
The variable txt3 now contains "What a very nice day!".

13

JavaScript Functions
A function is a reusable code-block that will be executed by an event, or when the function is called.

Examples
Function How to call a function. <html> <head> <script type="text/javascript"> function myfunction() { alert("HELLO") } </script> </head> <body> <form> <input type="button" onclick="myfunction()" value="Call function"> </form> <p>By pressing the button, a function will be called. The function will alert a message.</p> </body> </html>

Function with arguments How to pass a variable to a function, and use the variable value in the function.

14

<html> <head> <script type="text/javascript"> function myfunction(txt) { alert(txt) } </script> </head> <body> <form> <input type="button" onclick="myfunction('Hello')" value="Call function"> </form> <p>By pressing the button, a function with an argument will be called. The function will alert this argument.</p> </body> </html> Function with arguments 2 How to pass variables to a function, and use these variable values in the function. Function that returns a value How to let the function return a value. A function with arguments, that returns a value How to let the function find the sum of 2 arguments and return the result. <html> <head> <script type="text/javascript"> function total(numberA,numberB) {

5 The script in the body section calls a function with two arguments, 2 and 3. The function returns the sum of these two arguments. 15

return numberA + numberB } </script> </head> <body> <script type="text/javascript"> document.write(total(2,3)) </script> <p>The script in the body section calls a function with two arguments, 2 and 3.</p> <p>The function returns the sum of these two arguments.</p> </body> </html>

Functions
A function contains some code that will be executed by an event or a call to that function. A function is a set of statements. You can reuse functions within the same script, or in other documents. You define functions at the beginning of a file (in the head section), and call them later in the document. It is now time to take a lesson about the alert-box: This is JavaScript's method to alert the user.

alert("This is a message")

How to Define a Function


To create a function you define its name, any values ("arguments"), and some statements:

function myfunction(argument1,argument2,etc) { some statements }


A function with no arguments must include the parentheses:

function myfunction() { some statements

16

}
Arguments are variables used in the function. The variable values are values passed on by the function call. By placing functions in the head section of the document, you make sure that all the code in the function has been loaded before the function is called. Some functions return a value to the calling expression

function result(a,b) { c=a+b return c }

How to Call a Function


A function is not executed before it is called. You can call a function containing arguments:

myfunction(argument1,argument2,etc)
or without arguments:

myfunction()

The return Statement


Functions that will return a result must use the "return" statement. This statement specifies the value which will be returned to where the function was called from. Say you have a function that returns the sum of two numbers:

function total(a,b) { result=a+b return result }


When you call this function you must send two arguments with it:

sum=total(2,3)
The returned value from the function (5) will be stored in the variable called sum.

17

JavaScript Conditional Statements


Conditional statements in JavaScript are used to perform different actions based on different conditions.

Examples
If statement How to write an If statement. Use this statement if you want to execute a set of code if a specified condition is true. If...else statement How to write an If...Else statement. Use this statement if you want to execute one set of code if the condition is true and another set of code if the condition is false. <html> <body> <script type="text/javascript"> var d = new Date() var time = d.getHours() if (time < 10) { document.write("<b>Good morning</b>") } else { document.write("<b>Good day</b>") } </script> <p> This example demonstrates the If...Else statement. </p> <p> If the time on your browser is less than 10, you will get a "Good morning" greeting. Otherwise you will get a "Good day" greeting.

Good morning This example demonstrates the If...Else statement. If the time on your browser is less than 10, you will get a "Good morning" greeting. Otherwise you will get a "Good day" greeting.

18

</p> </body> </html> Random link This example demonstrates a link, when you click on the link it will take you to W3Schools.com OR to RefsnesData.no. There is a 50% chance for each of them. <html> <body> <script type="text/javascript"> var r=Math.random() if (r>0.5) { document.write("<a href='http://www.w3schools.com'>Learn Web Development! </a>") } else { document.write("<a href='http://www.refsnesdata.no'>Visit Refsnes Data!</a>") } </script> </body> </html> Switch statement How to write a switch statement. Use this statement if you want to select one of many blocks of code to execute. <html> <body> <script type="text/javascript"> var d = new Date() theDay=d.getDay()

I'm really looking forward to this weekend! This example demonstrates the switch statement. You will receive a different greeting based on what day it is. 19

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 really looking forward to this weekend!") } </script> <p>This example demonstrates the switch statement.</p> <p>You will receive a different greeting based on what day it is.</p> <p>Note that Sunday=0, Monday=1, Tuesday=2, etc.</p> </body> </html>

Note that Sunday=0, Monday=1, Tuesday=2, etc.

Conditional 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 three conditional statements:

if statement - use this statement if you want to execute a set of code when a condition is true if...else statement - use this statement if you want to select one of two sets of lines to execute switch statement - use this statement if you want to select one of many sets of lines to execute

If and If...else Statement

20

You should use the if statement if you want to execute some code if a condition is true.

Syntax if (condition) { code to be executed if condition is true } Example <script type="text/javascript"> //If the time on your browser is less than 10, //you will get a "Good morning" greeting. var d=new Date() var time=d.getHours() if (time<10) { document.write("<b>Good morning</b>") } </script>
Notice that there is no ..else.. in this syntax. You just tell the code to execute some code if the condition is true. If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.

Syntax if (condition) { code to be executed if condition is true } else { code to be executed if condition is false } Example <script type="text/javascript"> //If the time on your browser 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>

Switch Statement

21

You should use the Switch statement if you want to select one of many blocks of code to be executed.

Syntax switch (expression) { case label1: code to be executed if expression = label1 break case label2: code to be executed if expression = label2 break default: code to be executed if expression is different from both label1 and label2 }
This is how it works: First we have a single expression (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>

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 "

22

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.

JavaScript Looping
Looping statements in JavaScript are used to execute the same block of code a specified number of times.

Examples
For loop How to write a For loop. Use a For loop to run the same block of code a specified number of times <html> <body> <script type="text/javascript"> for (i = 0; i <= 5; i++) { document.write("The number is " + i) document.write("<br>") } </script> <p>Explanation:</p> <p>The for loop sets <b>i</b> equal to 0.</p> <p>As long as <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> </body> </html> Looping through HTML headers How to use the For loop to write the HTML headers. While loop How to write a While loop. Use a While loop to run the same block of code while or until a condition is true <html>

The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 Explanation: The for loop sets i equal to 0. As long as i is less than , or equal to, 5, the loop will continue to run. i will increase by 1 each time the loop runs.

The number is 0 The number is 1 The number is 2 23

<body> <script type="text/javascript"> i=0 while (i <= 5) { document.write("The number is " + i) document.write("<br>") i++ } </script> <p>Explanation:</p> <p><b>i</b> equal to 0.</p> <p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> </body> </html>

The number is 3 The number is 4 The number is 5 Explanation: i equal to 0. While i is less than , or equal to, 5, the loop will continue to run. i will increase by 1 each time the loop runs.

Do while loop How to write a Do While loop. Use a Do While loop to run the same block of code while or until a condition is true. This loop will always be executed once, even if the condition is false, because the statements are executed before the condition is tested <html> <body> <script type="text/javascript"> i=0 do { document.write("The number is " + i) document.write("<br>") i++

The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 Explanation: i equal to 0. The loop will run i will increase by 1 each time the loop runs. 24

} while (i <= 5) </script> <p>Explanation:</p> <p><b>i</b> equal to 0.</p> <p>The loop will run</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> <p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p> </body> </html>

While i is less than , or equal to, 5, the loop will continue to run.

Looping
Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to do this. In JavaScript we have the following looping statements:

while

while - loops through a block of code while a condition is true do...while - loops through a block of code once, and then repeats the loop while a condition is true for - run statements a specified number of times

The while statement will execute a block of code while a condition is true..

while (condition) { code to be executed }

do...while
The do...while statement will execute a block of code once, and then it will repeat the loop while a condition is true

do { code to be executed } while (condition)

for

25

The for statement will execute a block of code a specified number of times

for (initialization; condition; increment) { code to be executed }

JavaScript Guidelines
Some things to know about JavaScript.

JavaScript is Case Sensitive


A function named "myfunction" is not the same as "myFunction". Therefore watch your capitalization when you create or call variables, objects and functions.

Symbols
Open symbols, like ( { [ " ', must have a matching closing symbol, like ' " ] } ).

White Space
JavaScript ignores extra spaces. You can add white space to your script to make it more readable. These lines are equivalent:

name="Hege" name = "Hege"

Break up a Code Line


You can break up a code line within a text string with a backslash. The example below will be displayed properly:

Document.write("Hello \ World!")
Note: You can not break up a code line like this:

Document.write \ ("Hello World!")


The example above will cause an error.

Insert Special Characters


You can insert special characters (like " ' ; &) with the backslash:

document.write ("You \& I sing \"Happy Birthday\".")

26

The example above will produce this output:

You & I sing "Happy Birthday".

Comments
You can add a comment to your JavaScript code starting the comment with two slashes "//":

sum=a + b

//calculating the sum

You can also add a comment to the JavaScript code, starting the comment with "/*" and ending it with "*/"

sum=a + b

/*calculating the sum*/

Using "/*" and "*/" is the only way to create a multi-line comment:

/* This is a comment block. It contains several lines*/

27

JavaScript Object
JavaScript Array Object
The Array object is used to store a set of values in a single variable name.

Examples
Create an array with a numeric parameter and assign data to it Create an array and assign data to it. <html> <body> <script type="text/javascript"> var famname = new Array(6) famname[0] = "Jan Egil" famname[1] = "Tove" famname[2] = "Hege" famname[3] = "Stale" famname[4] = "Kai Jim" famname[5] = "Borge" for (i=0; i<6; i++) { document.write(famname[i] + "<br>") } </script> </body> </html> Create a literal array Create a literal array. Note that the length method is used to find out how many elements the array contains. <html> <body> <script type="text/javascript">

Jan Egil Tove Hege Stale Kai Jim Borge

28

var famname = new Array("Jan Egil","Tove","Hege","Stale","Kai Jim","Borge") for (i=0; i<famname.length; i++) { document.write(famname[i] + "<br>") } </script> </body> </html> Array - some properties and methods Some properties and methods to use with the Array object. <html> <body> <script type="text/javascript"> var famname = new Array(3) famname[0] = "Jani" famname[1] = "Tove" famname[2] = "Hege" document.write(famname.length + "<br>") document.write(famname.join(".") + "<br>") document.write(famname.reverse() + "<br>") document.write(famname.push("Ola","Jon") + "<br>") document.write(famname.length + "<br>") document.write(famname.pop() + "<br>") document.write(famname.shift() + "<br>") </script> </body> </html> Array - sort() The sort() method. What happens if we want to sort an array that consists of numbers? What is the sort order? <html>

3 Jani.Tove.Hege Hege,Tove,Jani 5 Jon Hege

Note: If we do not use a compareFunction 29

<body> <p> <b>Note:</b> If we do not use a compareFunction to define the sort order, the array is always sorted lexicographically. "500" comes before "7" in lexicographic order, but in a numeric sort 7 comes before 500. This example shows how to use a compare function - which will sort correctly whether the elements in the array are numbers or numeric strings. </p> <script type="text/javascript"> array1=new Array("Red","Blue","Green") array2=new Array("70","9","800") array3=new Array(50,10,2,300) array4=new Array("70","8","850",30,10,5,400) function compareNum(a,b) { return a-b } document.write("Sorted: " + array1.sort()) document.write("<br /><br />") document.write("Sorted without compareNum: " + array2.sort()) document.write("<br />") document.write("Sorted with compareNum: " + array2.sort(compareNum)) document.write("<br /><br />") document.write("Sorted without compareNum: " + array3.sort()) document.write("<br />") document.write("Sorted with compareNum: " + array3.sort(compareNum)) document.write("<br /><br />") document.write("Sorted without compareNum: " + array4.sort())

to define the sort order, the array is always sorted lexicographically. "500" comes before "7" in lexicographic order, but in a numeric sort 7 comes before 500. This example shows how to use a compare function which will sort correctly whether the elements in the array are numbers or numeric strings. Sorted: Blue,Green,Red Sorted without compareNum: 70,800,9 Sorted with compareNum: 9,70,800 Sorted without compareNum: 10,2,300,50 Sorted with compareNum: 2,10,50,300 Sorted without compareNum: 10,30,400,5,70,8,850 Sorted with compareNum: 5,8,10,30,70,400,850

30

document.write("<br />") document.write("Sorted with compareNum: " + array4.sort(compareNum)) </script> </body> </html> Array - concat() and slice() How to use concat() and slice(). <html> <body> <script type="text/javascript"> var famname = new Array(3) famname[0] = "Jani" famname[1] = "Tove" famname[2] = "Hege" var famname2 = new Array(3) famname2[0] = "John" famname2[1] = "Andy" famname2[2] = "Wendy" var famname3 = new Array("Stale","Borge") document.write(famname.join() + "<br>") document.write(famname.concat(famname2) + "<br>") document.write(famname.concat(famname2,famname3) + "<br>") document.write(famname.slice(1) + "<br>") </script> </body> </html> Array - splice() How to use the splice() method.

Jani,Tove,Hege Jani,Tove,Hege,John,Andy,Wendy Jani,Tove,Hege,John,Andy,Wendy,Stale,Borge Tove,Hege

31

<html> <body> <script type="text/javascript"> myCars=["BMW","Volvo","Saab","Ford"] document.write("myCars: " + myCars) document.write("<br /><br />") removed=myCars.splice(2,0,"Wolksvagen") document.write("After adding 1: " + myCars) document.write("<br /><br />") removed=myCars.splice(3,1) document.write("After removing 1: " + myCars) document.write("<br /><br />") removed=myCars.splice(2,1,"Seat") document.write("After replacing 1: " + myCars) document.write("<br /><br />") removed=myCars.splice(0,2,"Peugot","Honda","Toyota") document.write("After replacing 2 and adding 1: " + myCars) </script> </body> </html>

myCars: BMW,Volvo,Saab,Ford After adding 1: BMW,Volvo,Wolksvagen,Saab,Ford After removing 1: BMW,Volvo,Wolksvagen,Ford After replacing 1: BMW,Volvo,Seat,Ford After replacing 2 and adding 1: Peugot,Honda,Toyota,Seat,Ford

Array Object
The Array object is used to store a set of values in a single variable name. Each value is an element of the array and has an associated index number. You create an instance of the Array object with the "new" keyword. The following example creates two arrays, both of three elements:

var family_names=new Array(3) var family_names=new Array("Tove","Jani","Stale")


You can refer to a particular element in the array by using the name of the array and the index number. The index number starts at 0.

32

If you create an array with a single numeric parameter, you can assign data to each of the elements in the array like this:

family_names[0]="Tove" family_names[1]="Jani" family_names[2]="Stale"


And the data can be retrieved by using the index number of the particular array element you want, like this:

mother=family_names[0] father=family_names[1]
The Array object's properties and methods are described below: NN: Netscape, IE: Internet Explorer

Properties
Syntax: object.property_name Property constructor Length prototype Description Contains the function that created an object's prototype Returns the number of elements in the array Allows you to add properties to an array NN 4 3 3 IE 4 4 4

Methods
Syntax: object.method_name() Method concat() join(delimiter) pop() push("element1","element2") Reverse() shift() slice(begin[,end]) sort() splice(index,howmany[,el1,el2]) toSource() toString() unshift("element1","element2") valueOf() Description Joins two or more arrays and returns a new array Puts all the elements of an array into a string separated by a specified delimiter (comma is default) Removes and returns the last element of an array NN 4 3 4 IE 4 4 5.5 5.5 4 5.5 4 4 5.5 4 5.5 3

Adds one or more elements to the end of an array and returns 4 the new length Reverses the order of the elements in an array Removes and returns the first element of an array Creates a new array from a selected section of an existing array Sorts the elements of an array Adds and/or removes elements of an array Returns a string that represents the source code of the array Returns a string that represents the specified array and its elements Adds one or more elements to the beginning of an array and returns the new length Returns the primitive value of an array 3 4 4 3 4 3 4 4

4.06 4

33

JavaScript Boolean Object


The Boolean object is an object wrapper for a Boolean value and it is used to convert a non-Boolean value to a Boolean value.

Examples
Boolean Check if the Boolean object is true or false. <html> <body> <script type="text/javascript"> var b1=new Boolean( 0) var b2=new Boolean(1) var b3=new Boolean("") var b4=new Boolean(null) var b5=new Boolean(NaN) var b6=new Boolean("false") document.write("0 is boolean "+ b1 +"<br />") document.write("1 is boolean "+ b2 +"<br />") document.write("An empty string is boolean "+ b3 + "<br />") document.write("null is boolean "+ b4+ "<br />") document.write("NaN is boolean "+ b5 +"<br />") document.write("The string 'false' is boolean "+ b6 +"<br />") </script> </body> </html>

0 is boolean false 1 is boolean true An empty string is boolean false null is boolean false NaN is boolean false The string 'false' is boolean true

Boolean Object
The Boolean object is an object wrapper for a Boolean value and it is used to convert a non-Boolean value to a Boolean value, either true or false.

34

If the Boolean object has no initial value or if it is 0, null, "", false, or NaN, the initial value is false. Otherwise it is true (even with the string "false"). All the following lines of code create Boolean objects with an initial value of false:

var var var var var var

b1=new b2=new b3=new b4=new b5=new b6=new

Boolean() Boolean(0) Boolean(null) Boolean("") Boolean(false) Boolean(NaN)

All the following lines of code create Boolean objects with an initial value of true:

var var var var

b1=new b2=new b3=new b4=new

Boolean(true) Boolean("true") Boolean("false") Boolean("Richard")

The Boolean object's properties and methods are described below: NN: Netscape, IE: Internet Explorer

Properties
Syntax: object.property_name Property constructor prototype Description Contains the function that created an object's prototype Allows addition of properties and methods to the object NN 4 3 IE 4 4

Methods
Syntax: object.method_name() Method toString() Description Converts a Boolean value to a string. This method is called by JavaScript automatically whenever a Boolean object is used in a situation requiring a string Returns a primitive value ("true" or "false") for the Boolean object NN 4 IE 4

valueOf()

35

JavaScript Date Object


The Date object is used to work with dates and times.

Examples
Date Returns today's date including date, month, and year. Note that the getMonth method returns 0 in January, 1 in February etc. So add 1 to the getMonth method to display the correct date. <html> <body> <script type="text/javascript"> var d = new Date() document.write(d.getDate()) document.write(".") document.write(d.getMonth() + 1) document.write(".") document.write(d.getFullYear()) </script> </body> </html> Time Returns the current local time including hour, minutes, and seconds. To return the GMT time use getUTCHours, getUTCMinutes etc. <html> <body> <script type="text/javascript"> var d = new Date() document.write(d.getHours()) document.write(".") document.write(d.getMinutes()) document.write(".")

3.9.2004

8.21.29

36

document.write(d.getSeconds()) </script> </body> </html> Set date You can also set the date or time into the date object, with the setDate, setHour etc. Note that in this example, only the FullYear is set. <html> <body> <script type="text/javascript"> var d = new Date() d.setFullYear("1990") document.write(d) </script> </body> </html> UTC time The getUTCDate method returns the Universal Coordinated Time which is the time set by the World Time Standard. <html> <body> <script type="text/javascript"> var d = new Date() document.write(d.getUTCHours()) document.write(".") document.write(d.getUTCMinutes()) document.write(".") document.write(d.getUTCSeconds()) </script> </body> </html>

Mon Sep 3 08:22:58 UTC+0700 1990

1.23.35

37

Display weekday A simple script that allows you to write the name of the current day instead of the number. Note that the array object is used to store the names, and that Sunday=0, Monday=1 etc. <html> <body> <script type="text/javascript"> var d=new Date() var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" ) document.write("Today is " + weekday[d.getDay()]) </script> </body> </html> Display full date How to write a complete date with the name of the day and the name of the month. <html> <body> <script type="text/javascript"> var d=new Date() var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" ) var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") document.write(weekday[d.getDay()] + " ") document.write(d.getDate() + ". ") document.write(monthname[d.getMonth()] + " ") document.write(d.getFullYear()) </script> </body> </html>

Today is Friday

Friday 3. Sep 2004

38

Display time How to display the time on your pages. Note that this script is similar to the Time example above, only this script writes the time in an input field. And it continues writing the time one time per second. <html> <head> <script type="text/javascript"> var timer = null function stop() { clearTimeout(timer) } function start() { var time = new Date() var hours = time.getHours() var minutes = time.getMinutes() minutes=((minutes < 10) ? "0" : "") + minutes var seconds = time.getSeconds() seconds=((seconds < 10) ? "0" : "") + seconds var clock = hours + ":" + minutes + ":" + seconds document.forms[0].display.value = clock timer = setTimeout("start()",1000) } </script> </head> <body onload="start()" onunload="stop()"> <form> <input type="text" name="display" size="20"> </form> </body>

39

</html>

Date Object
The Date object is used to work with dates and times. To create an instance of the Date object and assign it to a variable called "d", you do the following:

var d=new Date()


After creating an instance of the Date object, you can access all the methods of the Date object from the "d" variable. To return the current day in a month (from 1-31) of a Date object, write the following:

d.getDate()
The Date object can also have the following parameters:

new Date(milliseconds) new Date(dateString) new Date(yr_num, mo_num, day_num [, hr_num, min_num, sec_num, ms_num])

milliseconds - the number of milliseconds since 01 January, 1970 00:00:00 dateString - the date in a format that is recognized by the Date.parse method yr_num, mo_num, day_num - the year, month or day of the date hr_num, min_num, sec_num, ms_num - the hours, minutes, seconds and milliseconds

If you only use Date(), JavaScript creates an object for today's date according to the time on the local machine. Here are some examples on how to create Date objects:

var var var var var

d=new d=new d=new d=new d=new

Date("October 12, 1988 13:14:00") Date("October 12, 1988") Date(88,09,12,13,14,00) Date(88,09,12) Date(500)

The Date object's properties and methods are described below: NN: Netscape, IE: Internet Explorer

Properties
Syntax: object.property_name Property Constructor Prototype Description Contains the function that created an object's prototype Allows addition of properties to a date NN 4 3 IE 4 4

Methods

40

Syntax: object.method_name() Method Date() getDate() getDay() getMonth() getFullYear() getYear() getHours() getMinutes() getSeconds() getMilliseconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCMonth() getUTCFullYear() getUTCHours() getUTCMinutes() getUTCSeconds() getUTCMilliseconds() parse() setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime() setYear() setUTCDate() setUTCDay() setUTCMonth() setUTCFullYear() setUTCHours() setUTCMinutes() setUTCSeconds() setUTCMilliseconds() toGMTString() toLocaleString() toString() Description Returns a Date object Returns the date of a Date object (from 1-31) Returns the day of a Date object (from 0-6. 0=Sunday, 1=Monday, etc.) Returns the month of a Date object (from 0-11. 0=January, 1=February, etc.) Returns the year of a Date object (four digits) Returns the year of a Date object (from 0-99). Use getFullYear instead !! Returns the hour of a Date object (from 0-23) Returns the minute of a Date object (from 0-59) Returns the second of a Date object (from 0-59) Returns the millisecond of a Date object (from 0-999) Returns the number of milliseconds since midnight 1/1-1970 Returns the time difference between the user's computer and GMT Returns the date of a Date object in universal (UTC) time Returns the day of a Date object in universal time Returns the month of a Date object in universal time Returns the four-digit year of a Date object in universal time Returns the hour of a Date object in universal time Returns the minutes of a Date object in universal time Returns the seconds of a Date object in universal time Returns the milliseconds of a Date object in universal time Returns a string date value that holds the number of milliseconds since January 01 1970 00:00:00 Sets the date of the month in the Date object (from 1-31) Sets the year in the Date object (four digits) Sets the hour in the Date object (from 0-23) Sets the millisecond in the Date object (from 0-999) Set the minute in the Date object (from 0-59) Sets the month in the Date object (from 0-11. 0=January, 1=February) Sets the second in the Date object (from 0-59) Sets the milliseconds after 1/1-1970 Sets the year in the Date object (00-99) Sets the date in the Date object, in universal time (from 1-31) Sets the day in the Date object, in universal time (from 0-6. Sunday=0, Monday=1, etc.) Sets the month in the Date object, in universal time (from 0-11. 0=January, 1=February) Sets the year in the Date object, in universal time (four digits) Sets the hour in the Date object, in universal time (from 0-23) Sets the minutes in the Date object, in universal time (from 0-59) Sets the seconds in the Date object, in universal time (from 0-59) Sets the milliseconds in the Date object, in universal time (from 0-999) Converts the Date object to a string, set to GMT time zone Converts the Date object to a string, set to the current time zone Converts the Date object to a string NN 2 2 2 2 4 2 2 2 2 4 2 2 4 4 4 4 4 4 4 4 2 2 4 2 4 2 2 2 2 2 4 4 4 4 4 4 4 4 2 2 2 IE 3 3 3 3 4 3 3 3 3 4 3 3 4 4 4 4 4 4 4 4 3 3 4 3 4 3 3 3 3 3 4 4 4 4 4 4 4 4 3 3 4

41

JavaScript Math Object


The built-in Math object includes mathematical constants and functions.

Examples
Round How to round a specified number to the nearest whole number <html> <body> <script type="text/javascript"> document.write(Math.round(7.25)) </script> </body> </html> Random number The random method returns a random number between 0 and 1 <html> <body> <script type="text/javascript"> document.write(Math.random()) </script> </body> </html> Random number from 0 to 10 How to find a random number from 0 to 10 using the random() and round() methods. Max number How to test which of two numbers, has the higher value. <html> <body> <script type="text/javascript"> document.write(Math.max(2,4))

0.4625827174121425

42

</script> </body> </html> Min number How to test which of two numbers, has the lower value. <html> <body> <script type="text/javascript"> document.write(Math.min(2,4)) </script> </body> </html>

Math Object
The built-in Math object includes mathematical constants and functions. You do not need to create the Math object before using it. To store a random number between 0 and 1 in a variable called "r_number":

r_number=Math.random()
To store the rounded number of 8.6 in a variable called "r_number":

r_number=Math.round(8.6)
The Math object's properties and methods are described below: NN: Netscape, IE: Internet Explorer

Properties
Syntax: object.property_name Property E LN2 LN10 LOG2E LOG10E PI SQRT1_2 SQRT2 Description Returns the base of a natural logarithm Returns the natural logarithm of 2 Returns the natural logarithm of 10 Returns the base-2 logarithm of E Returns the base-10 logarithm of E Returns PI Returns 1 divided by the square root of 2 Returns the square root of 2 NN 2 2 2 2 2 2 2 2 IE 3 3 3 3 3 3 3 3

43

Methods
Syntax: object.method_name() Method abs(x) acos(x) asin(x) atan(x) atan2(y,x) ceil(x) cos(x) exp(x) floor(x) log(x) max(x,y) min(x,y) pow(x,y) random() round(x) sin(x) sqrt(x) tan(x) Description Returns the absolute value of x Returns the arccosine of x Returns the arcsine of x Returns the arctangent of x Returns the angle from the x axis to a point Returns the nearest integer greater than or equal to x Returns the cosine of x Returns the value of E raised to the power of x Returns the nearest integer less than or equal to x Returns the natural log of x Returns the number with the highest value of x and y Returns the number with the lowest value of x and y Returns the value of the number x raised to the power of y Returns a random number between 0 and 1 Rounds x to the nearest integer Returns the sine of x Returns the square root of x Returns the tangent of x NN 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 IE 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

JavaScript String Object


The String object is used to work with text.

Examples
The length property This example returns the number of characters in a string. The fontcolor() method This example returns a string in a specified color. <html> <body> <script type="text/javascript">

W3Schools is great!! W3Schools is great!! W3Schools is great!! W3Schools is great!!

var txt="W3Schools is great!!" document.write("<p>" + txt.fontcolor() + "</p>")

44

document.write("<p>" + txt.fontcolor('red') + "</p>") document.write("<p>" + txt.fontcolor('blue') + "</p>") document.write("<p>" + txt.fontcolor('green') + "</p>") </script> </body> </html> The indexOf() method This example tests if a string contains a specified text and returns the position of where the text was found. <html> <body <script type="text/javascript"> var str="W3Schools is great!" var pos=str.indexOf("School") if (pos>=0) { document.write("School found at position: ") document.write(pos + "<br />") } else { document.write("School not found!") } </script> <p>This example tests if a string contains a specified word. If the word is found it returns the position of the first character of the word in the original string. Note: The first position in the string is 0!</p> </body> </html>

School found at position: 2 This example tests if a string contains a specified word. If the word is found it returns the position of the first character of the word in the original string. Note: The first position in the string is 0!

45

The match() method This example tests if a string contains a specified text and returns the text if it was found. <html> <body> <script type="text/javascript"> var str = "W3Schools is great!" document.write(str.match("great")) </script> <p>This example tests if a string contains a specified word. If the word is found it returns the word.</p> </body> </html> The substr() and substring() methods This example returns a specified part of a string. <html> <body> <script type="text/javascript"> var str="W3Schools is great!" document.write(str.substr(2,6)) document.write("<br /><br />") document.write(str.substring(2,6)) </script> <p> The substr() method returns a specified part of a string. If you specify (2,6) the returned string will be from the second character (start at 0) and 6 long. </p> <p> The substring() method also returns a specified part of a string. If you specify (2,6) it returns all characters from the second character (start at 0) and up to, but not including, the sixth character. </p>

great This example tests if a string contains a specified word. If the word is found it returns the word.

School Scho The substr() method returns a specified part of a string. If you specify (2,6) the returned string will be from the second character (start at 0) and 6 long. The substring() method also returns a specified part of a string. If you specify (2,6) it returns all characters from the second character (start at 0) and up to, but not including, the sixth character.

46

</body> </html> The toLowerCase() and toUpperCase() methods This example converts a string to lowercase and uppercase. <html> <body> <script type="text/javascript"> var str=("Hello JavaScripters!") document.write(str.toLowerCase()) document.write("<br>") document.write(str.toUpperCase()) </script> </body> </html>

hello javascripters! HELLO JAVASCRIPTERS!

String object
The String object is used to work with text. The String object's properties and methods are described below: NN: Netscape, IE: Internet Explorer

Properties
Syntax: object.property_name Property constructor length Returns the number of characters in a string Description NN 4 2 IE 4 3

Methods
Syntax: object.method_name() Method anchor("anchorname") big() blink() bold() charAt(index) Description Returns a string as an anchor Returns a string in big text Returns a string blinking Returns a string in bold Returns the character at a specified position NN 2 2 2 2 2 3 3 IE 3 3

47

charCodeAt(i) concat() fixed() fontcolor() fontsize() fromCharCode() indexOf() italics() lastIndexOf()

Returns the Unicode of the character at a specified position Returns two concatenated strings Returns a string as teletype Returns a string in a specified color Returns a string in a specified size Returns the character value of a Unicode Returns the position of the first occurrence of a specified string inside another string. Returns -1 if it never occurs Returns a string in italic

4 4 2 2 2 4 2 2

4 4 3 3 3 4 3 3 3

Returns the position of the first occurrence of a specified string inside another 2 string. Returns -1 if it never occurs. Note: This method starts from the right and moves left! Returns a string as a hyperlink Similar to indexOf and lastIndexOf, but this method returns the specified string, or "null", instead of a numeric value Replaces some specified characters with some new specified characters Returns an integer if the string contains some specified characters, if not it returns -1 Returns a string containing a specified character index Returns a string as small text Splits a string into an array of strings Returns a string strikethrough Returns a string as subscript Returns the specified characters. 14,7 returns 7 characters, from the 14th character (starts at 0) Returns the specified characters. 7,14 returns all characters from the 7th up to but not including the 14th (starts at 0) Returns a string as superscript Converts a string to lower case Converts a string to upper case 2 4 4 4 4 2 4 2 2 4 2 2 2 2

link() match() replace() search() slice() small() split() strike() sub() substr() substring() sup() toLowerCase() toUpperCase()

3 4 4 4 4 3 4 3 3 4 3 3 3 3

JavaScript HTML DOM Objects


With JavaScript you can access and manipulate all of the HTML DOM objects. (See HTML DOM Syllabus for more details)

HTML DOM Objects


Follow the links to learn more about the objects and their collections, properties, methods and events. Object Anchor Applet Area Base Basefont Body Description Represents an HTML a element (a hyperlink) Represents an HTML applet element. The applet element is used to place executable content on a page Represents an area of an image-map. An image-map is an image with clickable regions Represents an HTML base element Represents an HTML basefont element Represents the body of the document (the HTML body)

48

Button Checkbox Document Event FileUpload Form Frame Frameset Hidden History

Represents a push button on an HTML form. For each instance of an HTML <input type="button"> tag on an HTML form, a Button object is created Represents a checkbox on an HTML form. For each instance of an HTML <input type="checkbox"> tag on an HTML form, a Checkbox object is created Used to access all elements in a page Represents the state of an event, such as the element in which the event occurred, the state of the keyboard keys, the location of the mouse, and the state of the mouse buttons For each instance of an HTML <input type="file"> tag on a form, a FileUpload object is created Forms are used to prompt users for input. Represents an HTML form element Represents an HTML frame Represents an HTML frameset Represents a hidden field on an HTML form. For each instance of an HTML <input type="hidden"> tag on a form, a Hidden object is created A predefined object which can be accessed through the history property of the Window object. This object consists of an array of URLs. These URLs are all the URLs the user has visited within a browser window Represents an HTML inline-frame Represents an HTML img element Represents an HTML link element. The link element can only be used within the <head> tag Contains information about the current URL Represents an HTML meta element Contains information about the client browser Represents an option in a selection list on an HTML form. For each instance of an HTML <option> tag in a selection list on a form, an Option object is created Represents a password field on an HTML form. For each instance of an HTML <input type="password"> tag on a form, a Password object is created Represents radio buttons on an HTML form. For each instance of an HTML <input type="radio"> tag on a form, a Radio object is created Represents a reset button on an HTML form. For each instance of an HTML <input type="reset"> tag on a form, a Reset object is created Automatically created by the JavaScript runtime engine and it contains information about the client's display screen Represents a selection list on an HTML form. For each instance of an HTML <select> tag on a form, a Select object is created Represents an individual style statement. This object can be accessed from the document or from the elements to which that style is applied Represents a submit button on an HTML form. For each instance of an HTML <input type="submit"> tag on a form, a Submit object is created Represents an HTML table element Represents an HTML td element Represents an HTML th element Represents an HTML tr element Represents a text field on an HTML form. For each instance of an HTML <input type="text"> tag on a form, a Text object is created Represents an HTML textarea element Corresponds to the browser window. A Window object is created automatically with every instance of a <body> or <frameset> tag

Iframe Image Link Location Meta Navigator Option Password Radio Reset Screen Select Style Submit Table TableData TableHeader TableRow Text Textarea Window

49

JavaScript HTML DOM Objects EXAMPLES


Anchor Object
Change URL and text of a hyperlink <html> <head> <script type="text/javascript"> function myHref() { document.getElementById('myAnchor').innerText="Visit W3Schools" document.getElementById('myAnchor').href="http://www.w3schools.com " } </script> </head> <body> <a id="myAnchor" href="http://www.microsoft.com">Visit Microsoft</a> <form> <input type="button" onclick="myHref()" value="Change URL and text"> </form> </body> </html> Change the target attribute of a link <html> <head> <script type="text/javascript"> function myTarget() { document.getElementById('myAnchor').target="_blank

50

" } </script> </head> <body> <a name="myAnchor" href="http://www.w3schools.com">Visit W3Schools</a> <form> <input type="button" onclick="myTarget()" value="Make the link open in a new window!"> </form> <p>Try the link before and after you have pressed the button!</p> </body> </html> Using focus() and blur() <html> <head> <style type="text/css"> a:active {color:blue} </style> <script type="text/javascript"> function getfocus() { document.getElementById('w3s').focus() } function losefocus() { document.getElementById('w3s').blur()

51

} </script> </head> <body> <a name="w3s" href="http://www.w3schools.com">Visit W3Schools.com</a> <form> <input type="button" onclick="getfocus()" value="Get Focus"> <input type="button" onclick="losefocus()" value="Lose Focus"> </form> </body> </html>

Anchors array This example opens two windows. The first window contains four buttons and the second window defines four anchors from 0 to 3. When a button is pressed in the first window, the onClick event handler sets win2.location.hash to the specified anchor name. <html> <body> <script type="text/javascript"> function linkToAnchor(num) { var win2=open("tryjs_anchor2.htm","secondLinkWindow","scrollbars=yes,width=250, height=200") win2.location.hash=num } </script> <h3>Links and Anchors</h3> <p>Click on a button to display that anchor in window 2!</p>

52

<form> <input type="button" value="0" onClick="linkToAnchor(this.value)"> <input type="button" value="1" onClick="linkToAnchor(this.value)"> <input type="button" value="2" onClick="linkToAnchor(this.value)"> <input type="button" value="3" onClick="linkToAnchor(this.value)"> </form> </body> </html>

Button Object
Create a button <html> <head> <script type="text/javascript"> function show_alert() { alert("Hello World!") document.all("myButton").focus() } </script> </head> <body> <form> <input type="button" value="Click me!" name="myButton" onClick="show_alert()" /> </form> </body> </html>

Click on a button and display the name of the form

53

<html> <body> <form name="myForm"> The form's name is: <input type="text" name="text1" size="20"> <br /><br /> <input type="button" value="Show the form's name" onClick="this.form.text1.value=this.form.name"> </form> </body> </html>

Click on a button and display the names of all the elements in a form <html> <head> <script type="text/javascript"> function showFormElements(theForm) { str="Form Elements: " for (i=0; i<theForm.length; i++) str+=" \n " + theForm.elements[i].name alert(str) } </script> </head> <body> <form> First name: <input type="text" name="fname" size="20"> <br /> Last name: <input type="text" name="lname" size="20"> <br /><br /> <input type="button" name="button1" value="Display name of form elements" onClick="showFormElements(this.form)"> </form> </body> </html>

Checkbox Object
Check and uncheck a checkbox <html> <head> <script type="text/javascript">

54

function check() { var x=document.forms.myForm x[0].checked=true } function uncheck() { var x=document.forms.myForm x[0].checked=false } </script> </head> <body> <form name="myForm"> <input type="checkbox" value="on"> <input type="button" onclick="check()" value="Check Checkbox"> <input type="button" onclick="uncheck()" value="Uncheck Checkbox"> </form> </body> </html> Checkboxes in a form <html> <head> <script type="text/javascript"> function check() { coffee=document.forms[0].coffee

55

answer=document.forms[0].answer txt="" for (i=0;i<coffee.length;++ i) { if (coffee[i].checked) { txt=txt + coffee[i].value + " " } } answer.value="You ordered a coffee with " + txt } </script> </head> <body> <form> How would you like your coffee?<br /><br /> <input type="checkbox" name="coffee" value="cream">With cream<br /> <input type="checkbox" name="coffee" value="sugar">With sugar<br /> <br /> <input type="button" name="test" onclick="check()" value="Send order"> <br /><br /> <input type="text" name="answer" size="50"> </form> </body> </html>

Checkbox Two text boxes and one checkbox. If the user clicks in the checkbox all text fields are converted to uppercase.

56

<html> <body> <script type="text/javascript"> function convertField(field) { if (document.form1.convertUpper.checked) { field.value=field.value.toUpperCase() } } function convertAllFields() { document.form1.fname.value=document.form1.fname.value.toUpperCase( ) document.form1.lname.value=document.form1.lname.value.toUpperCase() } </script> <form name="form1"> First name: <input type="text" name="fname" onChange="convertField(this)" size="20" /> <br /> Last name: <input type="text" name="lname" onChange="convertField(this)" size="20" /> <br /> Convert fields to upper case <input type="checkBox" name="convertUpper" onClick="if (this.checked) {convertAllFields()}" value="ON"> </form> </body> </html>

Document Object
Write text to the output <html> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html> Write text with formatting to the output <html> <body>

Hello World!

Hello World!
57

<script type="text/javascript"> document.write("<h1>Hello World!</h1>") </script> </body> </html>

Return the number of anchors in a document <html> <body> <a name="A">First anchor</a><br /> <a name="B">Second anchor</a><br /> <a name="C">Third anchor</a><br /> <br /> Number of anchors in this document: <script type="text/javascript"> document.write(document.anchors.length) </script> </body> </html> Return the domain name of the document's server <html> <body> The domain name for this site is: <script type="text/javascript"> document.write(document.domain) </script> </body> </html> Return the referrer of a document

First anchor Second anchor Third anchor Number of anchors in this document: 3

The domain name for this site is: www.w3schools.com

58

<html> <body>

The referrer of a document is the URL of the document that linked to a document. The referrer of this document is: http://www.w3schools.com/js/tryit.asp? filename=try_dom_document_referrer In this case it is a frame page that is linking to this document. IE returns the URL of the frame page and Netscape returns the URL of the document linking to this document.

<p>The referrer of a document is the URL of the document that linked to a document.</p> The referrer of this document is: <script type="text/javascript"> document.write(document.referrer ) </script> <p>In this case it is a frame page that is linking to this document. IE returns the URL of the frame page and Netscape returns the URL of the document linking to this document.</p> </body> </html>

Return the title of a document <html> <head> <title>MY TITLE</title> </head> <body> The title of the document is: <script type="text/javascript"> document.write(document.title) </script> </body> </html> Return the URL of a document

The title of the document is:

MY TITLE

59

<html> <head> <script type="text/javascript"> function showURL() { alert(document.URL) } </script> </head> <body> <form> <input type="button" onclick="showURL()" value="Show URL"> </form> </body> </html>

Return a specified element, using getElementById() <html> <head> <script type="text/javascript"> function getElement() { var x=document.getElementById("myHeader") alert("I am a " + x.tagName + " element") } </script> </head> <body> <h1 id="myHeader" onclick="getElement()">Click to see

Click to see what element I am!

60

what element I am!</h1> </body> </html> Return the number of elements with equal names, using getElementsByName() <html> <head> <script type="text/javascript"> function getElements() { var x=document.getElementsByName("myInput") alert(x.length + " elements!") } </script> </head> <body> <form > <input name="myInput" type="text" size="20"><br /> <input name="myInput" type="text" size="20"><br /> <input name="myInput" type="text" size="20"><br /> <br /> <input name="mybutton" type="button" onclick="getElements()" value="Show how many elements named 'myInput'"> </form> </body> </html> Open a new document and add some text <html>

61

<head> <script type="text/javascript"> function docOpen() { document.open() document.write("<h3>Hello World!</h3>") } </script> </head> <body> <form> <input type="button" onclick="docOpen()" value="Open a new document"> </form> </body> </html> Open a new document specifying mime type and replace <html> <head> <script> function replace() { var newDoc=document.open("text/html","replace") var txt="<html><body>FUN!!!!</body></html>" newDoc.write(txt) newDoc.close() }

62

</script> </head> <body> <h1>Learning how to access the DOM is....</h1><br /> <Input type ="button" value = "Finish Sentence" onclick="replace()"> </body> </html> Count forms in a document <html> <body> <form name="Form1"> Name: <input type="text" size="20"> </form> <form name="Form2"> Age: <input type="text" size="3"> </form> <script type="text/javascript"> txt="This document contains: " + document.forms.length + " forms." document.write(txt) </script> </body> </html> Count images in a document

63

<html> <body> <img border="0" src="hackanm.gif" width="48" height="48"> <br /> <img border="0" src="compman.gif" width="107" height="98">

<p> <script type="text/javascript"> document.write("This document contains: " + document.images.length + " images.") </script> </p> </body> </html> Access an item in a collection <html> <body> <form name="Form1"> Name: <input type="text" size="20"> </form> <form name="Form2"> Age: <input type="text" size="3"> </form> <p><b>You can use the form's number:</b></p> <script type="text/javascript"> document.write("<p>The first form's name is: ") document.write(document.forms[0].name + "</p>") document.write("<p>The second form's name is: ")

64

document.write(document.forms[1].name + "</p>") </script> <p><b>Or, the form's name (will not work in Netscape):</b></p> <script type="text/javascript"> document.write("<p>The first form's name is: ") document.write(document.forms("Form1").name + "</p>") document.write("<p>The second form's name is: ") document.write(document.forms("Form2").name + "</p>") </script> </body> </html>

Event Object
Which mouse button was clicked? <html> <head> <script type="text/javascript"> function whichButton() { if (event.button==1) { alert("You clicked the left mouse button!") } else { alert("You clicked the right mouse button!") } }

65

</script> </head> <body onmousedown="whichButton()"> <p>Click in the document. An alert box will alert which mouse button you clicked.</p> </body> </html> What are the coordinates of the cursor? <html> <head> <script type="text/javascript"> function show_coords() { x=event.clientX y=event.clientY alert("X coords: " + x + ", Y coords: " + y) } </script> </head> <body onmousedown="show_coords()"> <p>Click in the document. An alert box will alert the x and y coordinates of the cursor.</p> </body> </html> What is the unicode of the key pressed? <html> <head> <script type="text/javascript"> function whichButton()

66

{ alert(event.keyCode) } </script> </head> <body onkeyup="whichButton()"> <p><b>Note:</b> Make sure the right frame has focus when trying this example!</p> <p>Press a key on your keyboard. An alert box will alert the unicode of the key pressed.</p> </body> </html>

What are the coordinates of the cursor, relative to the screen? <html> <head> <script type="text/javascript"> function coordinates() { x=event.screenX y=event.screenY alert("X=" + x + " Y=" + y) } </script> </head> <body onmousedown="coordinates()"> <p> Click somewhere in the document. An alert box will alert the x and y coordinates of the cursor, relative to the screen. </p> </body>

67

</html> What are the coordinates of the cursor? <html> <head> <script type="text/javascript"> function coordinates() { x=event.x y=event.y alert("X=" + x + " Y=" + y) } </script> </head> <body onmousedown="coordinates()"> <p> Click somewhere in the document. An alert box will alert the x and y coordinates of the cursor. </p> </body> </html>

Was the shift key pressed? <html> <head> <script type="text/javascript"> function isKeyPressed() { if (event.shiftKey==1) {

68

alert("The shift key was pressed!") } else { alert("The shift key was NOT pressed!") } } </script> </head> <body onmousedown="isKeyPressed()"> <p> Click somewhere in the document. An alert box will tell you if you pressed the shift key or not. </p> </body> </html>

Which element was clicked? <html> <head> <script type="text/javascript"> function whichElement() { var tname tname=event.srcElement.tagName alert("You clicked on a " + tname + " element.") } </script> </head>

69

<body onmousedown="whichElement()"> <p>Click somewhere in the document. An alert box will alert the tag name of the element you clicked on.</p> <h3>This is a header</h3> <p>This is a paragraph</p> <img border="0" src="/images/ball16.gif" width="29" height="28" alt="Ball"> </body> </html>

Which eventype occured? <html> <head> <script type="text/javascript"> function whichType() { alert(event.type) } </script> </head> <body onmousedown="whichType()"> d <p> Click on the document. An alert box will alert which type of event occurred. </p> </body> </html>

Form Object
View and change the action URL of a form

70

<html> <head> <script type="text/javascript"> function getAction() { var x=document.forms.myForm alert(x.action) } function changeAction() { var x=document.forms.myForm x.action="default.asp" alert(x.action) } </script> </head> <body> <form name="myForm" action="js_examples.asp"> <input type="button" onclick="getAction()" value="View value of action attribute"> <br /><br /> <input type="button" onclick="changeAction()" value="Change value of action attribute"> </form> </body> </html>

Return the method used when sending form data

71

<html>

<head> <script type="text/javascript"> function formMethod() { var x=document.forms.myForm alert(x.method) } </script> </head> <body> <form name="myForm" method="post"> Name: <input type="text" size="20"><br /><br /> <input type="button" onclick="formMethod()" value="Show method"> </form> </body> </html> Reset the fields in a form <html> <head> <script type="text/javascript"> function formReset() { var x=document.forms.myForm x.reset() } </script>

72

</head> <body> <form name="myForm"> <p>Enter some text in the text fields and then press the "Reset form" button</p> <input type="text" size="20"><br /> <input type="text" size="20"><br /> <br /> <input type="button" onclick="formReset()" value="Reset form"> </form> </body> </html> Submitting a form <html> <head> <script type="text/javascript"> function formSubmit() { document.forms.myForm.submit() } </script> </head> <body> <form name="myForm" action="js_form_action.asp" method="get"> Firstname: <input type="text" name="firstname" size="20"><br /> Lastname: <input type="text" name="lastname" size="20"><br /><br /> <input type="button" onclick="formSubmit()"

73

value="Submit"> </form> </body> </html> Validate an e-mail address in a form <html> <head> <script type="text/javascript"> function validate() { x=document.myForm at=x.email.value.indexOf("@") if (at == -1) { alert("Not a valid e-mail") return false } } </script> </head> <body> <form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()"> Enter your E-mail: <input type="text" name="email" size="20"> <input type="submit" value="Submit"> </form> <p><b>Note:</b> This example ONLY tests if the e-mail address contains an "@" character.

74

A "real-life" code would have to test for punctuations, spaces and other things as well.</p> </body> </html> Validate an input field with minimum and maximum values <html> <head> <script type="text/javascript"> function validate() { x=document.myForm txt=x.myInput.value if (txt>=1 && txt<=5) { return true } else { alert("Must be between 1 and 5") return false } } </script> </head> <body> <form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()"> Enter a value from 1 to 5: <input type="text" name="myInput" size="20">

75

<input type="submit" value="Submit"> </form> </body> </html> Validate an input field with a maximum number of characters <html> <head> <script type="text/javascript"> function validate() { x=document.myForm input=x.myInput.value if (input.length>5) { alert("The field cannot contain more than 5 characters!") return false } else { return true } } </script> </head> <body> <form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()"> Enter some text (you will get a message if you

76

add more than 5 characters): <input type="text" name="myInput" size="20"> <input type="submit" value="Submit"> </form> </body> </html> Set focus to an input field <html> <head> <script type="text/javascript"> function setfocus() { document.forms[0].field.focus() } </script> </head> <body> <form> <input type="text" name="field" size="30"> <input type="button" value="Set focus" onclick="setfocus()"> </form> </body> </html> Select the content of an input field <html> <head> <script type="text/javascript">

77

function setfocus() { document.forms[0].txt.select() document.forms[0].txt.focus() } </script> </head> <body> <form> <input type="text" name="txt" size="30" value="Hello World!"> <input type="button" value="Select text" onclick="setfocus()"> </form> </body> </html> Radio buttons in a form <html> <head> <script type="text/javascript"> function check(browser) { document.forms[0].answer.value=browser } </script> </head> <body> <form> Select which browser is your favorite:<br /><br /> <input type="radio" name="browser"

78

onclick="check(this.value)" value="Internet Explorer">Internet Explorer<br /> <input type="radio" name="browser" onclick="check(this.value)" value="Netscape">Netscape<br /> <input type="radio" name="browser" onclick="check(this.value)" value="Opera">Opera<br /> <br /> <input type="text" name="answer" size="20"> </form> </body> </html> Checkboxes in a form <html> <head> <script type="text/javascript"> function check() { coffee=document.forms[0].coffee answer=document.forms[0].answer txt="" for (i=0;i<coffee.length;++ i) { if (coffee[i].checked) { txt=txt + coffee[i].value + " " } } answer.value="You ordered a coffee with " + txt }

79

</script> </head> <body> <form> How would you like your coffee?<br /><br /> <input type="checkbox" name="coffee" value="cream">With cream<br /> <input type="checkbox" name="coffee" value="sugar">With sugar<br /> <br /> <input type="button" name="test" onclick="check()" value="Send order"> <br /><br /> <input type="text" name="answer" size="50"> </form> </body> </html> Dropdown list in a form <html> <head> <script type="text/javascript"> function put() { txt=document.forms[0].myList.options[document.forms[0]. myList.selectedIndex].text document.forms[0].favorite.value=txt } </script> </head> <body>

80

<form> Select your favorite browser: <select name="myList" onchange="put()"> <option>Internet Explorer</option> <option>Netscape</option> <option>Opera</option> </select> <br /><br /> Your favorite browser is: <input type="text" name="favorite" size="20"> </form> </body> </html> Another dropdown list <html> <head> <script type="text/javascript"> function put() { option=document.forms[0].dropdown.options[document.forms[0]. dropdown.selectedIndex].text txt=document.forms[0].number.value txt=txt + option document.forms[0].number.value=txt } </script> </head> <body>

81

<form> Select numbers:<br /> <select name="dropdown"> <option>0</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> <option>7</option> <option>8</option> <option>9</option> </select> <input type="button" onclick="put()" value="-->"> <input type="text" name="number" size="20"> </form> </body> </html> A select-menu in a form <html> <head> <script type="text/javascript"> function go(form) { location=form.selectmenu.value } </script>

82

</head> <body> <form> <select name="selectmenu" onchange="go(this.form)"> <option>--Select page--</option> <option value="http://www.microsoft.com">Microsoft</option> <option value="http://www.altavista.com">AltaVista</option> <option value="http://www.w3schools.com">W3Schools</option> </select> </form> </body> </html> Jump to the next field when the current field's maxlength has been reached <html> <head> <script type="text/javascript"> function toUnicode(elmnt,content) { if (content.length==elmnt.maxLength) { next=elmnt.tabIndex if (next<document.forms[0].elements.length) {

document.forms[0].elements[next].focus() }

83

} } </script> </head> <body> <p>This script automatically jumps to the next input field when the current field's maxlength has been reached.</p> <form> <input size="3" tabindex="1" maxlength="3" onkeyup="toUnicode(this,this.value)"> <input size="3" tabindex="2" maxlength="3" onkeyup="toUnicode(this,this.value)"> <input size="3" tabindex="3" maxlength="3" onkeyup="toUnicode(this,this.value)"> </form> </body> </html>

Frame, Frameset, and IFrame Objects


Make the frames resizable and not resizable <html> <frameset id="myFrameset" cols="50%,50%"> <frame id="leftFrame" src="frame_a_noresize.htm"> <frame id="rightFrame" src="frame_a.htm"> </frameset> </html> <!-- leftFrame --> <html> <head> <script type="text/javascript">

84

function disableResize() { parent.document.getElementById("leftFrame").noResize=true parent.document.getElementById("rightFrame").noResize=true } function enableResize() { parent.document.getElementById("leftFrame").noResize=false parent.document.getElementById("rightFrame").noResize=false } </script> </head> <body bgcolor="#EFE7D6"> <form> <input type="button" onclick="disableResize()" value="No resize"> <input type="button" onclick="enableResize()" value="Resize"> </form> <p>Try to resize the frame.</p> <p>Right-click inside the two frames and select "View Source" to see the source code.</p> </body> </html> <!-- rightFrame --> <html> <body bgcolor="#66CCFF"> <h3>Frame A</h3> </body> </html> Frames with and without scrollbars

85

<html> <frameset id="myFrameset" cols="50%,50%"> <frame id="leftFrame" src="frame_a_scrolling.htm"> <frame id="rightFrame" src="frame_a.htm"> </frameset> </html> <!-- leftFrame --> <html> <head> <script type="text/javascript"> function enableScrolling() { parent.document.getElementById("leftFrame").scrolling="yes" parent.document.getElementById("rightFrame").scrolling="yes" } function disableScrolling() { parent.document.getElementById("leftFrame").scrolling="no" parent.document.getElementById("rightFrame").scrolling="no" } </script> </head> <body bgcolor="#EFE7D6"> <form> <input type="button" onclick="enableScrolling()" value="Scroll bars"> <input type="button" onclick="disableScrolling()" value="No scroll bars"> </form> <p>Right-click inside the frames and select "View Source" to see the source code.</p> </body>

86

</html>

Change the source of frames <html> <frameset id="myFrameset" cols="50%,50%"> <frame id="leftFrame" src="frame_a_src.htm"> <frame id="rightFrame" src="frame_a.htm"> </frameset> </html> <!-- leftFrame --> <html> <head> <script type="text/javascript"> function newSrc() { parent.document.getElementById("leftFrame").src="default.asp" parent.document.getElementById("rightFrame").src="http://www.w3schools.com" } </script> </head> <body bgcolor="#EFE7D6"> <form> <input type="button" onclick="newSrc()" value="Change frame source"> </form> <p>Right-click inside the two frames and select "View Source" to see the source code.</p> </body> </html>

Break out of a frame

87

<html> <head> <script type="text/javascript"> function breakout() { if (window.top!=window.self) { window.top.location="tryjs_breakout.htm" } } </script> </head> <body> <form> Click the button to break out of the frame: <input type="button" onclick="breakout()" value="Break out!"> </form> </body> </html> Update two other frames <html> <frameset cols="70%,*" frameborder="1"> <frame src="frames_sourcepage2.htm"> <frameset rows="30%,*" frameborder="1"> <frame name="uframe" src="frame_a.htm"> <frame name="lframe" src="frame_b.htm"> </frameset> </frameset>

88

</html> <!-- leftFrame --> <html> <head> <script type="text/javascript"> function changeurl() { parent.uframe.location.href="frame_c.htm" parent.lframe.location.href="frame_d.htm" } </script> </head> <body> <form> <input type="button" value="Change url" onclick="changeurl()"> </form> <p>Right-click inside the three frames and select "View Source" to see the source code.</p> </body> </html>

Update two iframes IE and Opera only

89

<html> <head> <script type="text/javascript"> function twoframes() { document.all("frame1").src="frame_c.htm" document.all("frame2").src="frame_d.htm" } </script> </head> <body> <iframe src="frame_a.htm" name="frame1"></iframe> <iframe src="frame_b.htm" name="frame2"></iframe> <br /> <form> <input type="button" onclick="twoframes()" value="Change url of the two iframes"> </form> </body> </html>

Image Object
Change the height of an image <html> <head> <script type="text/javascript"> function setHeight() { var x=document.images x[0].height="250" } </script> </head> <body> <img src="compman.gif" width="107" height="98" /> <form> <input type="button" onclick="setHeight()" value="Change height of image">

90

</form> </body> </html> Change image <html> <head> <script type="text/javascript"> function setSrc() { var x=document.images x[0].src="hackanm.gif" } </script> </head> <body> <img src="compman.gif" width="107" height="98" /> <form> <input type="button" onclick="setSrc()" value="Change image"> </form> </body> </html> Change the width of an image

Location Object
Send the client to a new location (URL/page) <html> <head> <script type="text/javascript">

91

function curr_Location() { alert(location) } function change_Location() { window.location="http://www.w3schools.com" } </script> </head> <body> <form> <input type="button" onclick="curr_Location()" value="Show current URL"> <input type="button" onclick="change_Location()" value="Change URL"> </form> </body> </html> Refresh a document <html> <head> <script type="text/javascript"> function refresh() { window.location.reload() } </script> </head>

92

<body> <form> <input type="button" value="Refresh page" onclick="refresh()"> </form> </body> </html>

Navigator Object
How to detect the client's browser <html> <body> <script type="text/javascript"> document.write("You are browsing this site with: "+ navigator.appName) </script> </body> </html>

You are browsing this site with: Microsoft Internet Explorer

More details about the client's browser <html> <body> <script type="text/javascript"> document.write("<p>Browser: ") document.write(navigator.appName + "</p>") document.write("<p>Browserversion: ") document.write(navigator.appVersion + "</p>") document.write("<p>Code: ") document.write(navigator.appCodeName + "</p>") document.write("<p>Platform: ")

Browser: Microsoft Internet Explorer Browserversion: 4.0 (compatible; MSIE 6.0; Windows NT 5.1) Code: Mozilla Platform: Win32 Cookies enabled: true Browser's user agent header: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

93

document.write(navigator.platform + "</p>") document.write("<p>Cookies enabled: ") document.write(navigator.cookieEnabled + "</p>") document.write("<p>Browser's user agent header: ") document.write(navigator.userAgent + "</p>") </script> </body> </html>

All details about the client's browser <html> <body> <script type="text/javascript"> var x = navigator document.write("CodeName=" + x.appCodeName) document.write("<br />") document.write("MinorVersion=" + x.appMinorVersion) document.write("<br />") document.write("Name=" + x.appName) document.write("<br />") document.write("Version=" + x.appVersion) document.write("<br />") document.write("CookieEnabled=" + x.cookieEnabled) document.write("<br />") document.write("CPUClass=" + x.cpuClass) document.write("<br />") document.write("OnLine=" + x.onLine) document.write("<br />")

CodeName=Mozilla MinorVersion=;SP1; Name=Microsoft Internet Explorer Version=4.0 (compatible; MSIE 6.0; Windows NT 5.1) CookieEnabled=true CPUClass=x86 OnLine=true Platform=Win32 UA=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) BrowserLanguage=en-us SystemLanguage=en-us UserLanguage=en-us

94

document.write("Platform=" + x.platform) document.write("<br />") document.write("UA=" + x.userAgent) document.write("<br />") document.write("BrowserLanguage=" + x.browserLanguage) document.write("<br />") document.write("SystemLanguage=" + x.systemLanguage) document.write("<br />") document.write("UserLanguage=" + x.userLanguage) </script> </body> </html> Redirect user depending on browser <html> <head> <script type="text/javascript"> function redirectme() { bname=navigator.appName if (bname.indexOf("Netscape")!=-1) { window.location="tryjs_netscape.htm" return } if (bname.indexOf("Microsoft")!=-1) { window.location="tryjs_microsoft.htm" return

You are using a Microsoft Internet Explorer browser. You have been redirected to this page by the browser detection.

95

} window.location="tryjs_other.htm" } </script> </head> <body onload="redirectme()"> </body> </html>

Option and Select Objects


Disable and enable a dropdown list <html> <head> <script type="text/javascript"> function makeDisable() { var x=document.getElementById("mySelect") x.disabled=true } function makeEnable() { var x=document.getElementById("mySelect") x.disabled=false } </script> </head> <body> <form>

96

<select id="mySelect"> <option>Apple</option> <option>Banana</option> <option>Orange</option> </select> <input type="button" onclick="makeDisable()" value="Disable list"> <input type="button" onclick="makeEnable()" value="Enable list"> </form> </body> </html> Return the name of the form that contains the dropdown list <html> <head> <script type="text/javascript"> function formAction() { var x=document.getElementById("mySelect") alert(x.form.name) } </script> </head> <body> <form name="myForm"> <select id="mySelect"> <option>Apple</option> <option>Banana</option> <option>Orange</option>

97

</select> <input type="button" onclick="formAction()" value="Show name of the form"> </form> </body> </html> Return the number of options in the dropdown list <html> <head> <script type="text/javascript"> function formAction() { var x=document.getElementById("mySelect") alert(x.length) } </script> </head> <body> <form> <select id="mySelect"> <option>Apple</option> <option>Banana</option> <option>Orange</option> </select> <input type="button" onclick="formAction()" value="How many options in the list?"> </form> </body> </html>

98

Change the size of a dropdown list <html> <head> <script type="text/javascript"> function formAction() { var x=document.getElementById("mySelect") x.size="3" } </script> </head> <body> <form> <select name="mySelect"> <option>Apple</option> <option>Banana</option> <option>Orange</option> <option>Melon</option> </select> <input type="button" onclick="formAction()" value="Change size of list"> </form> </body> </html>

Select multiple options in a dropdown list

99

<html> <head> <script type="text/javascript"> function formAction() { var x=document.getElementById("mySelect") x.multiple=true } </script> </head> <body> <p> Before you click on the "Select multiple" button, try to select more than one option (by holding down the shift or Ctrl key). Click on the "Select multiple" button and try again. </p> <form> <select name="mySelect" size="3"> <option>Apple</option> <option>Banana</option> <option>Orange</option> </select> <input type="button" onclick="formAction()" value="Select multiple"> </form> </body> </html>

Return the selected option as text

100

<html> <head> <script type="text/javascript"> function getText() { var x=document.getElementById("mySelect") alert(x.options[x.selectedIndex].text) } </script> </head> <body> <form> Select your favorite fruit: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <br /><br /> <input type="button" onclick="getText()" value="Show text of selected fruit"> </form> </body> </html>

Return the selected option as a number <html> <head> <script type="text/javascript">

101

function getIndex() { var x=document.getElementById("mySelect") alert(x.options[x.selectedIndex].index) } </script> </head> <body> <form> Select your favorite fruit: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <br /><br /> <input type="button" onclick="getIndex()" value="Show index of selected fruit"> </form> </body> </html>

Change the option text <html> <head> <script type="text/javascript"> function changeText() {

102

var x=document.getElementById("mySelect") x.options[x.selectedIndex].text="Melon" } </script> </head> <body> <form> Select your favorite fruit: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <br /><br /> <input type="button" onclick="changeText()" value="Change text of selected fruit"> </form> </body> </html>

Remove an option from a dropdown list <html> <head> <script type="text/javascript"> function formAction() { var x=document.getElementById("mySelect") x.remove(x.selectedIndex)

103

} </script> </head>

<body> <form> <select name="mySelect"> <option>Apple</option> <option>Banana</option> <option>Orange</option> </select> <input type="button" onclick="formAction()" value="Remove option"> </form> </body> </html>

Screen Object
Detect details about the client's screen <html> <body> <script type="text/javascript"> document.write("Screen resolution: ") document.write(screen.width + "*" + screen.height) document.write("<br />") document.write("Available view area: ") document.write(screen.availWidth + "*" + screen.availHeight) document.write("<br />")

Screen resolution: 1024*768 Available view area: 1024*738 Color depth: 32

104

document.write("Color depth: ") document.write(screen.colorDepth) document.write("<br />") </script> </body> </html>

Table Object
Change the width of a table border <html> <head> <script type="text/javascript"> function changeBorder() { document.getElementById('myTable').border="10" } </script> </head> <body> <table border="1" id="myTable"> <tr> <td>100</td> <td>200</td> </tr> <tr> <td>300</td> <td>400</td> </tr>

105

</table> <form> <input type="button" onclick="changeBorder()" value="Change Border"> </form> </body> </html>

Change the cellPadding and cellSpacing of a table <html> <head> <script type="text/javascript"> function padding() { document.getElementById('myTable').cellPadding="15" } function spacing() { document.getElementById('myTable').cellSpacing="15" } </script> </head> <body> <table id="myTable" border="1"> <tr> <td>100</td> <td>200</td> </tr> <tr>

106

<td>300</td> <td>400</td> </tr> </table> <form> <input type="button" onclick="padding()" value="Change Cellpadding"> <input type="button" onclick="spacing()" value="Change Cellspacing"> </form> </body> </html>

Specify frames of a table <html> <head> <script type="text/javascript"> function aboveFrames() { document.getElementById('myTable').frame="above" } function belowFrames() { document.getElementById('myTable').frame="below" } </script> </head> <body> <table id="myTable"> <tr>

107

<td>100</td> <td>200</td> </tr> <tr> <td>300</td> <td>400</td> </tr> </table> <form> <input type="button" onclick="aboveFrames()" value="Show above frames"> <input type="button" onclick="belowFrames()" value="Show below frames"> </form> </body> </html>

Change height of a row <html> <head> <script type="text/javascript"> function specifyRow() { var x=document.getElementById('myTable').rows x[2].height="100" } </script> </head> <body> <table id="myTable" border="1">

108

<tr> <td>Row1 cell1</td> <td>Row1 cell2</td> </tr> <tr> <td>Row2 cell1</td> <td>Row2 cell2</td> </tr> <tr> <td>Row3 cell1</td> <td>Row3 cell2</td> </tr> <tr> <td>Row4 cell1</td> <td>Row4 cell2</td> </tr> <tr> <td>Row5 cell1</td> <td>Row5 cell2</td> </tr> </table> <form> <input type="button" onclick="specifyRow()" value="Change height of third row"> </form> </body> </html>

Specify rules for a table Create a caption for a table

109

<html> <head> <script type="text/javascript"> function caption() { var x=document.getElementById('myTable').createCaption() x.innerHTML="<b>My table caption</b>" } </script> </head> <body> <table id="myTable" border="1"> <tr> <td>Row1 cell1</td> <td>Row1 cell2</td> </tr> <tr> <td>Row2 cell1</td> <td>Row2 cell2</td> </tr> <tr> <td>Row3 cell1</td> <td>Row3 cell2</td> </tr> </table> <form> <input type="button" onclick="caption()" value="Create caption"> </form>

110

</body> </html>

Deleting rows in a table <html> <head> <script type="text/javascript"> function deleteRow(i) { document.getElementById('myTable').deleteRow(i) } </script> </head> <body> <table id="myTable" border="1"> <tr> <td>Row 1</td> <td><input type="button" value="Delete" onclick="deleteRow(this.rowIndex)"></td> </tr> <tr> <td>Row 2</td> <td><input type="button" value="Delete" onclick="deleteRow(this.rowIndex)"></td> </tr> <tr> <td>Row 3</td> <td><input type="button" value="Delete" onclick="deleteRow(this.rowIndex)"></td> </tr>

111

</table> </body> </html>

Adding rows to a table <html> <head> <script type="text/javascript"> function insRow() { var x=document.getElementById('myTable').insertRow(2) var y=x.insertCell(0) var z=x.insertCell(1) y.innerHTML="NEW CELL1" z.innerHTML="NEW CELL2" } </script> </head> <body> <table id="myTable" border="1"> <tr> <td>Row1 cell1</td> <td>Row1 cell2</td> </tr> <tr> <td>Row2 cell1</td> <td>Row2 cell2</td> </tr>

112

<tr> <td>Row3 cell1</td> <td>Row3 cell2</td> </tr> <tr> <td>Row4 cell1</td> <td>Row4 cell2</td> </tr> <tr> <td>Row5 cell1</td> <td>Row5 cell2</td> </tr> </table> <form> <input type="button" onclick="insRow()" value="Insert row"> </form> </body> </html>

Align the cell content in a table row <html> <head> <script type="text/javascript"> function alignRow() { var x=document.getElementById('myTable').rows x[0].align="right" }

113

</script> </head> <body> <table width="60%" id="myTable" border="1"> <tr> <td>Row1 cell1</td> <td>Row1 cell2</td> </tr> <tr> <td>Row2 cell1</td> <td>Row2 cell2</td> </tr> <tr> <td>Row3 cell1</td> <td>Row3 cell2</td> </tr> </table> <form> <input type="button" onclick="alignRow()" value="Align first row"> </form> </body> </html>

Change the cell content in a table row <html> <head> <script type="text/javascript"> function changeContent()

114

{ var x=document.getElementById('myTable').rows var y=x[0].cells y[0].innerHTML="NEW CONTENT" } </script> </head> <body> <table id="myTable" border="1"> <tr> <td>Row1 cell1</td> <td>Row1 cell2</td> </tr> <tr> <td>Row2 cell1</td> <td>Row2 cell2</td> </tr> <tr> <td>Row3 cell1</td> <td>Row3 cell2</td> </tr> </table> <form> <input type="button" onclick="changeContent()" value="Change content"> </form> </body> </html>

Vertical align the cell content in a table row

115

<html> <head> <script type="text/javascript"> function valignRow() { var x=document.getElementById('myTable').rows x[0].vAlign="top" } </script> </head> <body> <table width="50%" id="myTable" border="1"> <tr> <td height="50">Row1 cell1</td> <td height="50">Row1 cell2</td> </tr> <tr> <td height="50">Row2 cell1</td> <td height="50">Row2 cell2</td> </tr> <tr> <td height="50">Row3 cell1</td> <td height="50">Row3 cell2</td> </tr> </table> <form> <input type="button" onclick="valignRow()" value="Vertical align row"> </form>

116

</body> </html>

Align the cell content in a single cell <html> <head> <script type="text/javascript"> function alignCell() { var x=document.getElementById('myTable').rows[0].cells x[0].align="center" } </script> </head>

<body> <table id="myTable" border="1" width="100%"> <tr> <td>First cell</td> <td>Second cell</td> </tr> <tr> <td>Third cell</td> <td>Fourth cell</td> </tr> </table> <form> <input type="button" onclick="alignCell()" value="Align cell content">

117

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

Vertical align the cell content in a single cell

: Make it as the same above

Adding cells to a table row <html> <head> <script type="text/javascript"> function addCell() { var x=document.getElementById('myTable').rows(0) var y=x.insertCell(2) y.innerHTML="NEW CELL" } </script> </head> <body> <table id="myTable" border="1"> <tr> <td>Row1 cell1</td> <td>Row1 cell2</td> </tr> <tr> <td>Row2 cell1</td> <td>Row2 cell2</td> </tr> <tr>

118

<td>Row3 cell1</td> <td>Row3 cell2</td> </tr> </table> <form> <input type="button" onclick="addCell()" value="Add cell"> </form> </body> </html>

Change the colspan of a table row <html> <head> <script type="text/javascript"> function setColSpan() { var x=document.getElementById('myTable').rows[0].cells x[0].colSpan="2" x[1].colSpan="6" } </script> </head> <body> <table id="myTable" border="1"> <tr> <td colspan="4">cell 1</td> <td colspan="4">cell 2</td> </tr>

119

<tr> <td>cell 3</td> <td>cell 4</td> <td>cell 5</td> <td>cell 6</td> <td>cell 7</td> <td>cell 8</td> <td>cell 9</td> <td>cell 10</td> </tr> </table> <form> <input type="button" onclick="setColSpan()" value="Change colspan"> </form> </body> </html>

Window Object
Display an alert box : See above Alert box with line-breaks <html> <head> <script type="text/javascript"> function disp_alert() { alert("Hello again! This is how we" + '\n' + "add line breaks to an alert box!") } </script>

120

</head> <body> <form> <input type="button" onclick="disp_alert()" value="Display alert box"> </form> </body> </html> Display a confirm box <html> <head> <script type="text/javascript"> function disp_confirm() { var name=confirm("Press a button") if (name==true) { document.write("You pressed the OK button!") } else { document.write("You pressed the Cancel button!") } } </script> </head> <body> <form>

121

<input type="button" onclick="disp_confirm()" value="Display a confirm box"> </form> </body> </html> Display a prompt box <html> <head> <script type="text/javascript"> function disp_prompt() { var name=prompt("Please enter your name","") if (name!=null && name!="") { document.write("Hello " + name + "! How are you today?") } } </script> </head> <body> <form> <input type="button" onclick="disp_prompt()" value="Display a prompt box"> </form> </body> </html> Open a new window when clicking on a button <html> <head>

122

<script type="text/javascript"> function open_win() { window.open("http://www.w3schools.com") } </script> </head> <body> <form> <input type=button value="Open Window" onclick="open_win()"> </form> </body> </html> Open a new window and control its appearance <html> <head> <script type="text/javascript"> function open_win() { window.open("http://www.w3schools.com","my_new_window","toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=400, height=400") } </script> </head> <body> <form> <input type="button" value="Open Window" onclick="open_win()"> </form>

123

</body> </html> Open multiple windows with one click : See above : See above

Send the client to a new location (URL/page) Refresh a document : See abov

Write some text in the windows status bar <html> <head> <script type="text/javascript"> function load() { window.status="Some text in the status bar" } </script> </head> <body onload="load()"> <p>Look at the text in the statusbar</p> </body> </html> Print a page <html> <head> <script type="text/javascript"> function printpage() { window.print() } </script>

Look at the text in the statusbar

124

</head> <body> <form> <input type="button" value="Print this page" onclick="printpage()"> </form> </body> </html> Trapped in a frame? This is how you break out of frames : See above

Update 2 frames with one click : See above Update 2 other frames : See above Resize a window : See above, use top.resizeBy instead of top.resizeTo Resize a window to a specified size <html> <head> <script type="text/javascript"> function resizeWindow() { top.resizeTo(500,300) } </script> </head> <body> <form> <input type="button" onclick="resizeWindow()" value="Resize window"> </form> <p><b>Note:</b> We have used the <b>top</b> element instead of the <b>window</b> element, to represent the top frame. If you do not use frames, use the <b>window</b> element instead.</p> </body> </html>

125

Scroll the window <html> <head> <script type="text/javascript"> function scrollWindow() { window.scrollBy(50,50) } </script> </head> <body> <form> <input type="button" onclick="scrollWindow()" value="Scroll"> </form> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br />

126

<br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br />

127

<br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br />

128

<br /> <br /> <br /> <br /> <br /> </body> </html>

Scroll the window to a specified position : see above, use window.scrollTo(50,50) instead of window.scrollBy(50,50)

The setInterval() and clearInterval() methods <html> <head> <script type="text/javascript"> var intval="" function start_Int() { if(intval=="") { intval=window.setInterval("start_clock()",1000) } else { stop_Int() } } function stop_Int() { if(intval!="")

129

{ window.clearInterval(intval) intval="" myTimer.innerHTML="Interval Stopped" } } function start_clock() { var d=new Date() var sw="am" var h=d.getHours() var m=d.getMinutes() + "" var s=d.getSeconds() + "" if(h>12) { h-=12 sw="pm" } if(m.length==1) { m="0" + m } if(s.length==1) { s="0" + s } myTimer.innerHTML=h + ":" + m + ":" + s + " " + sw }

130

</script> </head> <body> <span id="myTimer" style="font-size:16pt; fontweight:bold; color:#FF0000">Interval Stopped</span> <br /><br /> <input type="button" value="Start" onclick="start_Int()"> <input type="button" value="Stop" onclick="stop_Int()"> <p>This example updates the innerHTML of a span element every second. Click "Start" to start the setInterval method. Click "Stop" to stop the interval with the clearInterval method.</p> </body> </html> The setTimeout() method <html> <head> <script type="text/javascript"> function timeout() { setTimeout("alert('This alert box popped up 1 second after you clicked the button')", 1000) } </script> </head> <body> <form> <input type="button" onclick="tcamimeout()" value="Count down"> </form>

131

</body> </html> The setTimeout() method with a pointer to a function <html> <head> <script type="text/javascript"> function timeout() { window.setTimeout("show_alert()",2000) } function show_alert() { alert("This alert box popped up 2 seconds after clicking the button") } </script> </head> <body> <form> <input type="button" onclick="timeout()" value="Count down"> </form> </body> </html> The setTimeout() method with a pointer to a function 2 <html> <head> <script type="text/javascript"> function timeout()

132

{ window.setTimeout("change_text(document.all('t'))",3000) } function change_text(tid) { tid.style.color="red" } </script> </head> <body> <form> <input id="t" name="t" type="text" value="Mickey Mouse" size="20"> <input type="button" onclick="timeout()" value="Count down"> </form> <p>3 secunds after you click the "Count down" button, the color of the text inside the input field will change.</p> </body> </html> Create a pop-up <html> <head> <script type="text/javascript"> function show_popup() { var p=window.createPopup() var pbody=p.document.body pbody.style.backgroundColor="lime" pbody.style.border="solid black 1px"

133

pbody.innerHTML="This is a pop-up! Click outside the pop-up to close." p.show(150,150,200,50,document.body) } </script> </head> <body> <button onclick="show_popup()">Show pop-up!</button> </body> </html>

134

HTML DOM Objects Overview

HTML DOM Anchor Object


The Anchor object represents an HTML a element (a hyperlink)

Examples
Change URL and text of a hyperlink Change the target attribute of a link Using focus() and blur() Anchors array This example opens two windows. The first window contains four buttons and the second window defines four anchors from 0 to 3. When a button is pressed in the first window, the onClick event handler sets win2.location.hash to the specified anchor name. <html> <body> <script type="text/javascript"> function linkToAnchor(num) { var win2=open("tryjs_anchor2.htm","secondLinkWindow","scrollbars=yes,width=250,height=200") win2.location.hash=num } </script> <h3>Links and Anchors</h3> <p>Click on a button to display that anchor in window 2!</p> <form> <input type="button" value="0" onClick="linkToAnchor(this.value)"> <input type="button" value="1" onClick="linkToAnchor(this.value)"> <input type="button" value="2" onClick="linkToAnchor(this.value)"> <input type="button" value="3" onClick="linkToAnchor(this.value)">

135

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

Anchor Object
The Anchor object represents an HTML a element (a hyperlink). For each instance of an HTML <a> tag in a document, an Anchor object is created. An anchor can be used in two ways: 1. 2. To create a link to another document by using the href attribute To create a bookmark inside a document, by using the name attribute

All Anchor objects in a document can be found in the Document object's anchors array. The Anchor object's properties and methods are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property accessKey charset coords href hreflang id name rel rev shape tabIndex target type Description Sets or returns the keyboard key to access the hyperlink Sets or returns the character set of the linked resource Sets or retrieves a comma-separated list with coordinates, defining an active region geometry Sets or returns the URL of the linked resource Sets or returns the language code of the linked resource Sets or returns the id of the hyperlink (In IE 4 this property is read-only) Sets or returns the name of the hyperlink Sets or returns the relationship between the current document and the target URL Sets or returns the relationship between the current document and the target URL Sets or returns the active area. Coordinates are given by coords Sets or returns the index that defines the tab order for the hyperlink Sets or returns the window/frame where to open the target URL Sets or returns the MIME type of the linked resource 4 6 6 6 6 6 6 N 6 6 6 6 6 IE 5 6 6 5 6 4 4 5 5 6 5 5 6 W3C Yes Yes Yes Yes Yes No Yes Yes Yes Yes Yes Yes Yes

Methods
Syntax: object.method_name() Method blur() focus() Description Removes focus from the link Gives focus to the link N 6 6 IE 5 5 W3C Yes Yes

136

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onFocus Description Executes some code when the link loses focus Executes some code when the link gets focus N 2 2 IE 3 3 W3C

HTML DOM Applet Object


Applet Object
The Applet object represents an HTML applet element. The applet element is used to place executable content on a page. The Applet object's properties are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property align alt archive border code codeBase codeType contentDocument data declare form height hspace id name standby tabIndex type useMap vspace Sets or returns the vertical margin of the applet object Returns a reference to the applet object's parent form Sets or returns the height of the applet object Sets or returns the horizontal margin of the applet object Sets or returns the id of the applet object (In IE 4 this property is read-only) Sets or returns the name of the applet object Sets or returns a message when loading the applet Sets or returns the tab order of the applet object Sets or returns the content type for data downloaded via the data attribute 6 6 6 6 6 6 Returns 6 Description Sets or returns the alignment of the applet object (according to the surrounding text) Sets or returns a text alternative to the applet object Sets or returns a string that can be used to implement your own archive functionality for the applet object Sets or returns the width of the border around the applet object Sets or returns the URL of the file that contains the compiled Java class Sets or returns the URL of the component 6 6 N 6 6 6 IE 5 6 6 5 5 5 4 5 5 5 W3C Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes No Yes Yes Yes Yes Yes Yes

137

width

Sets or returns the width of the applet object

Yes

HTML DOM Area Object


Area Object
The Area object defines an area of an image-map. An image-map is an image with clickable regions. The Area object's properties and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property accessKey alt coords hash host hostname href id noHref pathname port protocol search shape tabIndex target Description Sets or returns the keyboard key to access the area object Sets or returns an alternate text for browsers that cannot show an area Sets or returns the anchor part of the URL (begins with a #) Sets or returns the hostname and port of the URL Sets or returns the server name and domain name/IP address of the URL Sets or returns the entire URL Sets or returns the id of the area object (In IE 4 this property is read-only) Sets or returns if the area should be inactive Sets or returns the pathname of the URL Sets or returns the URL port the server uses Sets or returns the URL protocol (including the first colon) e.g "http:", "https:" Sets or returns the URL query string section (including the question mark (?)) Sets or returns the shape of the area Sets or returns the tab order of the area object Sets or returns URL link's target name 3 6 3 3 3 3 6 6 3 3 3 3 Sets or returns a comma-separated list of lengths that defines the clickable area 6 N IE 4 5 5 4 4 4 4 4 5 4 4 4 4 5 5 4 W3C Yes Yes Yes No No No Yes No Yes No No No No Yes Yes Yes

Events
Syntax: object.event_name="someJavaScriptCode" Event onClick onDblClick onMouseOut onMouseOver Description Executes some code when a Click event occurs Executes some code when a Doubleclick event occurs Executes some code when a Mouseout event occurs Executes some code when a Mouseover event occurs N 3 3 3 3 IE 4 4 4 4 W3C

HTML DOM Base Object


138

Base Object
The Base object represents an HTML base element. For each instance of an HTML <base> tag in a document, a Base object is created. The Base object's properties are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property href id target Description Sets or returns the base URL for the document Sets or returns the id of the base object (In IE 4 this property is read-only) Sets or returns the default target frame or window 6 N 6 IE 5 4 5 W3C Yes No Yes

HTML DOM Basefont Object


Basefont Object
The Basefont object represents an HTML basefont element. For each instance of an HTML <basefont> tag in a document, a Basefont object is created. The Basefont object's properties are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property color face id size Description Sets or returns the font color to be used Sets or returns the font face to be used Sets or returns the id of the basefont object (In IE 4 this property is read-only) Sets or returns the font size to be used 6 N 6 6 IE 5 5 4 5 W3C Yes Yes No Yes

HTML DOM Body Object


Body Object
The Body object represents the body of the document (the HTML body). The Body object's properties are described below:

139

N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property accessKey aLink background bgColor id link scrollLeft scrollTop text vLink Description Sets or returns the keyboard key to access the body object Sets or returns the color of active links in the document Sets or returns the URL of the background image of the document Sets or returns the background color of the document Sets or returns the id of the body (In IE 4 this property is read-only) Sets or returns the color of links in the document Sets or returns the distance between the left edge of the body and the leftmost portion of the content visible in the window Sets or returns the distance between the top edge of the body and the topmost portion of the content visible in the window Sets or returns the color of text in the document Sets or returns the color of visited links in the document 6 7 7 6 6 6 6 6 N IE 5 5 5 5 4 5 5 5 5 5 W3C No Yes Yes Yes No Yes No No Yes Yes

HTML DOM Button Object


The Button object represents a push button on an HTML form.

Examples
Create a button Click on a button and display the name of the form Click on a button and display the names of all the elements in a form

Button Object
The button object represents a push button on an HTML form. For each instance of an HTML <input type="button"> tag on an HTML form, a Button object is created. The Button objects are stored in the elements array of the corresponding form. You can access a Button object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute. The Button object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property Description N IE W3C

140

accessKey disabled form id name tabIndex type value

Sets or returns the keyboard key to access the Button object Sets or returns whether or not the Button should be disabled Returns a reference to the form that contains the Button object Sets or returns the id of the button (In IE 4 this property is read-only) Sets or returns the name of the button Sets or returns the index that defines the tab order for the button Returns the type of the form element. For a Button object it will be "button" Sets or returns the text that is displayed on the button 3 2 2 2

5 5 3 4 3 5 4 3

Yes Yes Yes No Yes Yes Yes Yes

Methods
Syntax: object.method_name() Method blur() click() focus() Description Removes focus from the button Simulates a mouse-click on the button Gives focus to the button N 2 2 2 IE 3 3 3 W3C

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onClick onFocus onMouseDown onMouseUp Description Executes some code when the button loses focus Executes some code when the button is clicked Executes some code when the button gets focus Executes some code when a mouse button is pressed Executes some code when a mouse button is released N 2 2 2 4 4 IE 3 3 3 4 4 W3C

HTML DOM Checkbox Object


The Checkbox object represents a checkbox in an HTML form.

Examples
Check and uncheck a checkbox Checkboxes in a form Checkbox Two text boxes and one checkbox. If the user clicks in the checkbox all text fields are converted to uppercase.

Checkbox Object
The Checkbox object represents a checkbox on an HTML form. For each instance of an HTML <input type="checkbox"> tag on an HTML form, a Checkbox object is created.

141

All Checkbox objects are stored in the elements array of the corresponding form. You can access a Checkbox object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute. The Checkbox object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property accept accessKey align alt checked defaultChecked disabled form id name tabIndex type value Description Sets or returns a list of content types that the server that processes this form will handle correct Sets or returns the keyboard key to access the checkbox Sets or returns the alignment of the checkbox according to the surrounding text Sets or returns an alternate text to display if the browser does not support checkboxes Sets or returns the current state of the checkbox (true if checked and false 2 if not) Sets or returns the default value of the checked attribute (true if checked by default and false if not) Sets or returns whether or not the checkbox should be disabled Returns a reference to the form that contains the checkbox Sets or returns the id of the checkbox (In IE 4 this property is read-only) Sets or returns the name of the checkbox Sets or returns the index that defines the tab order for the checkbox Returns the type of the form element. For a checkbox it will be "checkbox" 3 Sets or returns the value of the value attribute of the checkbox 2 2 2 2 N IE 4 3 3 3 3 4 3 4 4 3 W3C Yes Yes Yes Yes Yes Yes Yes Yes No Yes Yes Yes Yes

Methods
Syntax: object.method_name() Method blur() click() focus() Description Removes focus from the checkbox Simulates a mouse-click in the checkbox Gives focus to the checkbox N 2 2 2 IE 3 3 3 W3C Yes Yes Yes

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onClick onFocus onMouseDown onMouseUp Description Executes some code when the checkbox loses focus Executes some code when the checkbox is clicked Executes some code when the checkbox gets focus Executes some code when a mouse button is pressed Executes some code when a mouse button is released N 2 2 2 4 4 IE 3 3 3 4 4 W3C

142

HTML DOM Document Object


The Document object is used to access all elements in a page.

Examples
Write text to the output Write text with formatting to the output Return the number of anchors in a document Return the domain name of the document's server Return the referrer of a document Return the title of a document Return the URL of a document Return a specified element, using getElementById() Return the number of elements with equal names, using getElementsByName() Open a new document and add some text Open a new document specifying mime type and replace Count forms in a document Count images in a document Access an item in a collection

Document Object
The Document object is used to access all elements in a page. The Document object's collections, properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard), D: Deprecated

Collections
Collection anchors[] applets[] attributes[] childNodes[] embeds[] forms[] images[] Returns a reference to all embedded objects in the document Returns a reference to all Form objects in the document Returns a reference to all Image objects in the document Description Returns a reference to all Anchor objects in the document Returns a reference to all Applet objects in the document N 2 3 6 6 3 2 3 IE 3 4 5 4 3 4 W3C Yes Yes No No No Yes Yes

143

links[] plugins[] stylesheets[]

Returns a reference to all Link objects in the document

2 6 6

3 5

Yes No No

Properties
Syntax: document.property_name Property alinkColor bgColor body cookie documentElement domain fgColor lastModified linkColor referrer title URL vlinkColor Description Sets or returns the color of the active links in the document Sets or returns the background-color of the document Specifies the beginning and end of the document body Sets or returns all cookies associated with the document Returns a reference to the root node of the document Returns the document server's domain name Sets or returns the text-color of the document Returns the date and time the document was last modified Sets or returns the color of the links in the document Returns the title of the document (text inside the HTML title element) Returns the URL of the current document Sets or returns the color of the visited links in the document N 2 2 6 2 6 3 2 2 2 2 3 2 IE 3 3 5 3 5 4 3 3 3 3 3 4 3 W3C D D Yes Yes No Yes D No D Yes Yes Yes D

Returns the URL of the document that loaded the current document 2

Methods
Syntax: document.method_name() Method clear() close() createAttribute("name") createElement("tag") createTextNode("txt") focus() getElementById("id") getElementsByName("name") getElementsByTagName("tag") open("mimetype"[,replace]) Description Clears all elements in the document Closes the output stream and displays the sent data Creates an attribute with a specified name Creates an element Creates a text string Gives the document focus Returns a reference to the first object with the specified ID Returns a collection of objects with the specified NAME Returns a collection of objects with the specified TAGNAME N 2 2 6 6 6 6 6 6 6 IE 3 6 5 5 5 5 5 5 3 W3C No Yes No No No No No Yes No Yes

Opens a document for writing. If a document exists in the target it 2 will be cleared. If this method has no arguments, a new window with about:blank is displayed Writes a text string to a document opened by open() Writes a text string followed by a new line character to a document opened by open() 2 2

write("str") writeln("str")

3 3

Yes Yes

Events
Syntax: document.event_name="someJavaScriptCode" Event onClick Description Executes some code when a Click event occurs NN 6 IE 5 W3C

144

onDblClick onFocus onKeyDown onKeyPress onKeyUp onMouseDown onMouseMove onMouseOut onMouseOver onMouseUp onResize

Executes some code when a Doubleclick event occurs Executes some code when a Focus event occurs Executes some code when a Keydown event occurs Executes some code when a Keypress event occurs Executes some code when a Keyup event occurs Executes some code when a Mousedown event occurs Executes some code when a Mousemove event occurs Executes some code when a Mouseout event occurs Executes some code when a Mouseover event occurs Executes some code when a Mouseup event occurs Executes some code when a Resize event occurs

6 6 6 6 6 6 6 6 6 6 6

5 5 5 5 5 5 5 5 5 5 5

HTML DOM Event Object


The event object gives you information about what event that occurs.

Examples
Which mouse button was clicked? What are the coordinates of the cursor? What is the unicode of the key pressed? What are the coordinates of the cursor, relative to the screen? What are the coordinates of the cursor? Was the shift key pressed? Which element was clicked? Which eventype occured?

Event Object
The Event object represents the state of an event, such as the element in which the event occurred, the state of the keyboard keys, the location of the mouse, and the state of the mouse buttons. The event object is available only during an event - that is, you can use it in event handlers but not in other code. In VBScript, you must access the event object through the window object. The Event object's collections, properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Collections

145

Collection bookmarks[] boundElements[]

Description Returns a collection of bookmarks connected to the rows effected by the events Returns a collection of all elements on a page which are bound to a data test

IE

W3C

Properties
Syntax: event.property_name Property Abstract altKey altLeft banner button Description Returns the Abstract content in an Advanced Stream Redirector (ASX) file Sets or returns a Boolean value that indicates the state of the ALT key Returns a Boolean value that indicates the state of the left ALT key Returns the Banner content in an ASX file Sets or returns the mouse button pressed by the user N IE 6 4 5.5 6 4 W3C


cancelBubble clientX clientY contentOverflow ctrlKey ctrlLeft dataFld fromElement keyCode MoreInfo nextPage offsetX offsetY propertyName qualifier reason

0 1 2 3 4 5 6

Default. No button pressed Left button pressed Right button pressed Left and right buttons pressed Middle button pressed Left and middle buttons pressed Right and middle buttons pressed

7 - All three buttons are pressed 4 4 4 5.5

Sets or returns a Boolean value that indicates whether or not the current event should bubble up the hierarchy of event handlers Sets or returns the x-coordinate of the mouse pointer - relative to the screen, excluding decorations and scroll bars Sets or returns the y-coordinate of the mouse pointer - relative to the screen, excluding decorations and scroll bars Sets or returns a Boolean value that indicates the state of the CTRL key Sets or returns a Boolean value that indicates the state of the left CTRL key Sets or returns the data column affected by the oncellchange event Sets or returns the object from which activation or the mouse pointer is exiting during the event Sets or returns the UNICODE of the key pressed Returns the MoreInfo content in an ASX file Returns the position of the next page within a print template Sets or returns the x-coordinate of the mouse pointer relative to the object firing the event Sets or returns the y-coordinate of the mouse pointer relative to the object firing the event Sets or returns the name of the property that has changed on the object Sets or returns the result of a data transfer for a data source

4 5.5 5 4 4 6 5.5 4 4 5 5 4

146


recordset repeat returnValue saveType screenX screenY shiftKey shiftLeft srcElement srcFilter srcUrn toElement type userName wheelDelta x y

0 - Successfully 1 - Aborted 2 - Error 4 5 4 5.5 4 4 4 5.5 4 4 5 4 4 5 5.5 4 4

Sets or returns a reference to the default record set in a data source Returns a Boolean value that indicates whether the ONKEYDOWN event is being repeated Sets or returns the return value from an event Returns the clipboard type when ONCONTENTSAVE fires Sets or returns the x-coordinate of the mouse pointer - relative to the screen Sets or returns the y-coordinate of the mouse pointer - relative to the screen Returns a Boolean value that indicates the state of the SHIFT key Returns a Boolean value that indicates the state of the left SHIFT key Sets or returns the object that fired the event Sets or returns the filter object that fired the ONFILTERCHANGE event Sets or returns the Universal Resource Name (URN) of the behavior that fired the event Sets or returns a reference to the object toward which the user is moving the mouse pointer Sets or returns the event name Returns the distance and the direction the wheel button has rolled Sets or returns the x-coordinate (in px) of the mouse pointer relative to a relatively positioned parent element Sets or returns the y-coordinate (in px) of the mouse pointer relative to a relatively positioned parent element

HTML DOM FileUpload Object


FileUpload Object
For each instance of an HTML <input type="file"> tag on a form, a FileUpload object is created. All FileUpload objects are stored in the elements array of the corresponding form. You can access a FileUpload object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute. The FileUpload object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property accept Description Sets or returns a list of content types that the server that processes this form will N IE W3C Yes

147

handle correct accessKey align alt defaultValue disabled form id name tabIndex type value Sets or returns the keyboard key to access the FileUpload object Sets or returns the alignment of the FileUpload object according to the surrounding text Sets or returns an alternate text to display if the browser does not support <input type="file"> Sets or returns the initial value of the FileUpload object Sets or returns whether or not the FileUpload object should be disabled Returns a reference to the form that contains the FileUpload object Sets or returns the id of the FileUpload object (In IE 4 this property is read-only) Sets or returns the name of the FileUpload object Sets or returns the index that defines the tab order for the FileUpload object Returns the type of the form element. For a FileUpload object it will be "file" Returns the file name of the FileUpload object after the text is set by user input 3 3 3 3 3 4 4 4 4 4 4 4 4 4 Yes Yes Yes Yes Yes Yes No Yes Yes Yes Yes

Methods
Syntax: object.method_name() Method blur() click() focus() select() Description Removes focus from the FileUpload object Simulates a mouse-click on the FileUpload object Gives focus to the FileUpload object Selects the FileUpload object 3 N 3 IE 4 4 4 4 W3C Yes No Yes Yes

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onClick onFocus onSelectStart Description Executes some code when the FileUpload object loses focus Executes some code when the FileUpload object gets a mouse click Executes some code when the FileUpload object gets focus Executes some code when the FileUpload object gets selected NN 3 3 3 IE 4 4 4 4 W3C

HTML DOM Form Object


Forms are used to prompt users for input.

Examples
View and change the action URL of a form Return the method used when sending form data Reset the fields in a form Submitting a form Validate an e-mail address in a form

148

Validate an input field with minimum and maximum values Validate an input field with a maximum number of characters Form validation Set focus to an input field Select the content of an input field Radio buttons in a form Checkboxes in a form Dropdown list in a form Another dropdown list A select-menu in a form Jump to the next field when the current field's maxlength has been reached

Form Object
Forms are used to prompt users for input. We may use form elements such as text fields, radio buttons, checkboxes and selection lists. The input data is normally posted to a server for processing. The Form object's collections, properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Collections
Collection elements[] Description Returns an array containing each element in the form N 2 IE 3 W3C Yes

Properties
Syntax: object.property_name Property acceptCharset action encoding enctype id length method name tabIndex target Description Sets or returns a list of character encodings for form data that must be accepted by the server processing the form Sets or returns the URL of where the input data will be submitted Sets or returns the MIME encoding for the form Sets or returns the MIME encoding for the form Sets or returns the id of the form (In IE 4 this property is read-only) Returns the number of elements in a form Sets or returns how form data is submitted to the server ("get" or "post") Sets or returns the name of the form Sets or returns the index that defines the tab order for the form Sets or returns the target window or frame that responses are sent to after submission of a form 2 2 2 2 2 2 6 N IE 3 3 3 5 4 3 3 3 5 3 W3C Yes Yes No Yes No Yes Yes Yes No Yes

149

Methods
Syntax: object.method_name() Method reset() submit() Description N IE 4 3 W3C Yes Yes

Resets the default values of all elements in the form (same as clicking the Reset 3 button) Submits the form (same as clicking the Submit button) 2

Events
Syntax: object.event_name="someJavaScriptCode" Event onReset onSubmit Description Executes some code when a Reset event occurs Executes some code when a Submit event occurs N 3 2 IE 4 3 W3C

HTML DOM Frame Object


The Frame object represents an HTML frame.

Examples
Make the frames resizable and not resizable Frames with and without scrollbars Change the source of frames Break out of a frame Update two frames Update two other frames Update two iframes IE and Opera only

Frame Object
The Frame object represents an HTML frame. The Frame object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property Description N IE W3C

150

contentDocument frameBorder id longDesc marginHeight marginWidth name noResize scrolling src

Returns the document the frame contains Sets or returns whether to display a border for the frame Sets or returns the id of the frame (In IE 4 this property is read-only) Sets or returns a URL to a long description of the frame Sets or returns the top and bottom margins of the frame Sets or returns the left and right margins of the frame Sets or returns the name of the frame Sets or returns whether the frame can be resized Sets or returns whether the frame can be scrolled Sets or returns the URL to be loaded by the frame 6 6 6 6 6 6 6

5 4 6 5 5 5 5 5 5

Yes Yes No Yes Yes Yes Yes Yes Yes Yes

Methods
Syntax: object.method_name() Method blur() focus() Description Removes focus from the frame Gives focus to the frame N IE 5 5 W3C No No

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onFocus Description Executes some code when the frame loses focus Executes some code when the frame gets focus N IE 5 5 W3C No No

HTML DOM Frameset Object


The Frameset object represents an HTML frameset.

Examples
Make the frames resizable and not resizable Frames with and without scrollbars Change the source of frames Break out of a frame Update two frames Update two other frames Update two iframes IE and Opera only

Frameset Object
The Frameset object represents an HTML frameset.

151

The Frameset object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property cols id rows Description Sets or returns the number of columns of frames in the frameset Sets or returns the id of the frameset (In IE 4 this property is read-only) Sets or returns the number of rows of frames in the frameset 6 N 6 IE 5 4 5 W3C Yes No Yes

Methods
Syntax: object.method_name() Method blur() focus() Description Removes focus from the frameset Gives focus to the frameset N IE 5 5 W3C No No

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onFocus Description Executes some code when the frameset loses focus Executes some code when the frameset gets focus N IE 5 5 W3C No No

HTML DOM Hidden Object


Hidden Object
For each instance of an HTML <input type="hidden"> tag on a form, a Hidden object is created. All Hidden objects are stored in the elements array of the corresponding form. You can access a Hidden object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute. The Hidden object's properties are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property defaultValue form Description Sets or returns the initial value of the hidden field Returns a reference to the hidden field's parent form N 2 2 IE 3 3 W3C Yes Yes

152

id name type value

Sets or returns the id of the hidden field (In IE 4 this property is read-only) Sets or returns the name of the hidden field Returns the type of the form element. For a hidden object it will always be "hidden" Sets or returns the value of the value attribute of the hidden field 2 3 2

4 3 4 3

No Yes Yes Yes

HTML DOM History Object


History Object
The History object is a predefined object which can be accessed through the history property of the Window object. The History object consists of an array of URLs. These URLs are the URLs the user has visited within a browser window. Note: The History object is not a W3C standard. The History object's properties and methods are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: history.property_name Property length Description Returns the number of elements in the history list N 2 IE 3 W3C No

Methods
Syntax: history.method_name() Method back() forward() go(number|"URL") Description N IE 3 3 3 W3C No No No

Loads the previous URL in the history list (same as clicking the Back button 2 and to history.go(-1)) Loads the next URL in the history list (same as clicking the Forward button 2 and to history.go(1)) Loads a specified URL from the history list 2

HTML DOM IFrame Object


The IFrame object represents an HTML inline-frame.

Examples
Make the frames resizable and not resizable Frames with and without scrollbars Change the source of frames

153

Break out of a frame Update two frames Update two other frames Update two iframes IE and Opera only

IFrame Object
The IFrame object represents an HTML inline-frame. The IFrame object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property align contentDocument frameBorder height id longDesc marginHeight marginWidth name scrolling src tabIndex width Description Sets or returns how to align the iframe according to the surrounding text Returns the document the iframe contains Sets or returns whether to display a border for the iframe Sets or returns the height of the iframe Sets or returns the id of the iframe (In IE 4 this property is read-only) Sets or returns a URL to a long description of the iframe Sets or returns the top and bottom margins of the iframe Sets or returns the left and right margins of the frame Sets or returns the name of the iframe Sets or returns whether the iframe can be scrolled Sets or returns the URL to be loaded by the iframe Sets or returns the index that defines the tab order for the iframe Sets or returns the width of the iframe 6 6 6 6 N 6 IE 5 5 5 4 6 5 5 5 5 5 5 5 W3C Yes Yes Yes Yes No Yes Yes Yes Yes Yes Yes No Yes

Methods
Syntax: object.method_name() Method blur() focus() Description Removes focus from the iframe Gives focus to the iframe N IE 5 5 W3C No No

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onFocus Description Executes some code when the iframe loses focus Executes some code when the iframe gets focus N IE 5 5 W3C No No

154

HTML DOM Image Object


The Image object represents an HTML img element.

Examples
Change the height of an image Change image Change the width of an image

Image Object
The Image object represents an HTML img element. For each instance of an HTML <img> tag in a document, an Image object is created. The Image object's properties and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property align alt border complete height hspace id isMap longDesc lowsrc name src Description Sets or returns how to align the image according to the surrounding text Sets or returns an alternate text to write if the image cannot be displayed Sets or returns the width of the border of the image in pixels Returns a Boolean value that indicates whether or not the browser is finished loading the image N 6 6 3 3 IE 5 5 4 4 4 4 4 5 6 3 3 4 4 4 W3C Yes Yes Yes No Yes Yes No Yes Yes No Yes Yes

Sets or returns the value of the height attribute of the <img> tag in pixels 3 Sets or returns the value of the hspace attribute of the <img> tag in pixels 3 Sets or returns the id of the image (In IE 4 this property is read-only) Sets or returns a Boolean value that specifies if the image is a server-side 6 image map Sets or returns a URL for a long description of the image Sets or returns a URL to a low-resolution version of the image (for clients with low-resolution) Sets or returns the value of the name attribute of the <img> tag

Sets or returns the URL of the image (This property can be changed at any 3 time. However, the new image is scaled to fit the height and width attributes of the first image) Sets or returns a URL (often with a bookmark extension - #name) to use as a client-side image map Sets or returns the value of the width attribute of the <img> tag in pixels 6

useMap vspace width

5 4 4

Yes Yes Yes

Sets or returns the value of the vspace attribute of the <img> tag in pixels 3 3

Methods

155

Syntax: object.method_name() Method blur() click() focus() Description Removes focus from the image Simulates a mouse-click on the image Gives focus to the image N IE 4 4 4 W3C No No No

Events
Syntax: object.event_name="someJavaScriptCode" Event onAbort onBlur onClick onError onFocus onLoad Description Executes some code when a user aborts the download of an image Executes some code when the image loses focus Executes some code when a user clicks on the image Executes some code when an Error occurs Executes some code when the image gets focus Executes some code when the image loads 3 3 N 3 IE 4 4 4 4 4 4 W3C

HTML DOM Link Object


Link Object
The Link object represents the HTML link element. The link element can only be used within the <head> tag. The Link object's properties and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property charset disabled href hreflang id media name rel rev target type Sets or returns the name of the link object Sets or returns the relationship between the current document and the target URL Sets or returns the relationship between the current document and the target URL Sets or returns the window/frame where to open the target URL Sets or returns the MIME type of the linked resource 2 Description Sets or returns the character set of the linked resource Sets or returns whether or not the link object should be disabled Sets or returns the URL of the linked resource Sets or returns the language code of the linked resource Sets or returns the id of the link (In IE 4 this property is read-only) 2 N IE 4 4 4 4 4 4 4 4 4 4 W3C Yes Yes Yes Yes No Yes No Yes Yes Yes Yes

Events

156

Syntax: object.event_name="someJavaScriptCode" Event onLoad Description Executes some code after the browser loads the link object N 2 IE 4 W3C

HTML DOM Location Object


The Location object contains information about the current URL.

Examples
Send the client to a new location (URL/page) Refresh a document

Location Object
The Location object contains information about the current URL. Note: The Location object is not a W3C standard. The Location object's properties and methods are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property hash host hostname href pathname port protocol search Description Sets or returns the hostname and port number of the location or URL Sets or returns the hostname of the location or URL Sets or returns the entire URL Sets or returns the file name or path specified by the location object Sets or returns the port number associated with the URL Sets or returns the protocol part of the URL N 2 2 2 2 2 2 IE 3 3 3 3 3 3 3 3 W3C No No No No No No No No

Sets or returns the part of the href property that follows the hash sign (#) 2

Sets or returns the part of the href property that follows the question mark 2 (?)

Methods
Syntax: object.method_name() Method assign("URL") reload(false|true) replace("URL") Description Loads a new document Reloads the current document Replaces the current document with the one specified N 2 2 3 IE 4 4 4 W3C No No No

157

HTML DOM Meta Object


Meta Object
The Meta object represents an HTML meta element. The Meta object's properties are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property charset content disabled httpEquiv name scheme Description Sets or returns the character set used to encode the meta object Sets or returns meta-information associated with httpEquiv or name Sets or returns whether or not the meta object should be disabled Sets or returns information used to bind the content of the meta element to an HTTP response header Sets or returns the value of the content attribute of the meta object 6 6 N 6 6 IE 5 5 5 5 5 6 W3C No Yes No Yes Yes Yes

Sets or returns the scheme to be used in interpreting the value of a property for 6 the meta object

HTML DOM Navigator Object


The Navigator object contains information about the client browser.

Examples
How to detect the client's browser More details about the client's browser All details about the client's browser Redirect user depending on browser Different messages depending on browser

Navigator Object
The Navigator object contains information about the client browser. Note: The Navigator object is not a W3C standard. The Navigator object's collections, properties and methods are described below:

158

N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, MO: Mac only, W3C: World Wide Web Consortium (Internet Standard)

Collections
Collection plugins[] Description Returns a reference to all embed objects in the document N 3 IE 4 (MO) W3C No

Properties
Syntax: object.property_name Property appCodeName appMinorVersion appName appVersion browserLanguage cookieEnabled cpuClass onLine Description Returns the code name of the browser Returns the minor version of the browser Returns the name of the browser Returns the platform and version of the browser Returns the current browser language Returns a Boolean value that specifies whether cookies are enabled in the browser Returns the CPU class of the browser's system Returns a Boolean value that specifies whether the system is in offline mode (In IE 4+ the user can choose to work offline by selecting File/Work Offline in the browser. When Work Offline is selected, the system enters an offline state, and content is read from the cache) Returns the operating system platform Returns the default language used by the OS Returns the value of the user-agent header sent by the client to the 2 server Returns the OS' natural language setting 4 6 2 2 N 2 IE 3.02 4 3.02 3.02 4 4 4 4 W3C No No No No No No No No

platform systemLanguage userAgent userLanguage

4 4 3.02 4

No No No No

Methods
Syntax: object.method_name() Method javaEnabled() taintEnabled() Description N IE 4 (MO) 4 W3C No No

A Boolean value that specifies whether the browser has Java enabled 3 A Boolean value that specifies whether the browser has data tainting 3 enabled

HTML DOM Option Object


The Option object represents an HTML option element.

Examples
Disable and enable a dropdown list Return the name of the form that contains the dropdown list

159

Return the number of options in the dropdown list Change the size of a dropdown list Select multiple options in a dropdown list Return the selected option as text Return the selected option as a number Change the option text Remove an option from a dropdown list

Option Object
For each instance of an HTML <option> tag in a selection list on a form, an Option object is created. An option in a selection list can be created either with the HTML <option> tag:

<option>Wolksvagen</option>
OR by using the option constructor and assign it to an index of the relevant Select object:

document.myForm.cartypes[3]=new Option("Wolksvagen")
Tip: Refresh the document by using history.go(0) at the end of the code to make the new option visible. To specify a value to be returned to the server when an option is selected and the form submitted:

document.myForm.cartypes[3]=new Option("Wolksvagen","WV")
To make the option selected by default in the selection list:

document.myForm.cartypes[3]=new Option("Wolksvagen","WV",true)
The Option object's properties and methods are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property defaultSelected disabled form id index label Description Sets or returns the value of the selected attribute of the option N 6 IE 5.5 W3C Yes

3.02 Yes

Sets or returns a Boolean value that specifies whether the option should be 6 disabled Returns a reference to the form that contains the option object Sets or returns the id of the option (In IE 4 this property is read-only) Sets or returns the position of the option in the select box Sets or returns a label for the option object 6

3.02 Yes 4 6 No Yes 3.02 Yes

160

selected text value

Sets or returns the current state of the option Sets or returns the text value for the <option> tag Sets or returns the value to be returned to the server when an option is selected and the form is submitted

6 6 6

3.02 Yes 3.02 Yes 3.02 Yes

Methods
Syntax: object.method_name() Method click() Description Simulates a mouse-click on the option N IE 4 W3C No

HTML DOM Password Object


Password Object
For each instance of an HTML <input type="password"> tag on a form, a Password object is created. All Password objects are stored in the elements array of the corresponding form. You can access a Password object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute. The Password object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property accept accesskey defaultValue disabled form id maxLength name readOnly size tabIndex type value Description Sets or returns a list of content types that the server that processes this form will handle correct Sets or returns the keyboard key to access the password field Sets or returns the initial value of the password field Sets or returns whether or not the password field should be disabled Returns a reference to the password field's parent form Sets or returns the id of the password field (In IE 4 this property is readonly) Sets or returns the maximum number of characters the user can enter in the password field Sets or returns the name of the password field Sets or returns whether the content of the password field is read-only Sets or returns the size of the password field Sets or returns the index that defines the tab order for the password field The type of the form element. For a password object it will always be "password" Sets or returns the value of the value attribute of the password field 3 2 6 2 6 6 2 6 2 N IE 4 5.5 4 4 W3C Yes Yes Yes No Yes

3.02 Yes 3.02 Yes

3.02 Yes 4 4 Yes Yes 3.02 Yes 3.02 Yes 3.02 Yes

Methods
Syntax: object.method_name()

161

Method blur() click() focus() select()

Description Removes focus from the password field Simulates a mouse-click on the password field Sets focus on the password field Selects and highlights the entire text that is in the password field

N 2 2 2

IE 4 4 4

W3C Yes No Yes

3.02 Yes

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onClick onFocus onKeyDown onKeyPress onKeyUp onSelectStart Description Executes some code when the password field loses focus Executes some code when the user clicks in the password field Executes some code when the password field gets focus Executes some code when a key is pressed down in the password field 2 4 N 2 IE 4 4 3.02 4 4 4 4 W3C

Executes some code when an alphanumeric key is pressed in the password 4 field Executes some code when a key is released in the password field Executes some code when some text in the password field is selected 4

HTML DOM Radio Object


Examples
Radio buttons

Radio Object
For each instance of an HTML <input type="radio"> tag on a form, a Radio object is created. All Radio objects are stored in the elements array of the corresponding form. You can access a Radio object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute. The Radio object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property accept accesskey align alt checked Description Sets or returns a list of content types that the server that processes this form will handle correct Sets or returns the keyboard key to access the radio button Sets or returns the alignment of the radio button according to the surrounding text Sets or returns an alternate text to display if the browser does not support radio buttons Sets or returns the current state of the radio button (true if selected and 2 N IE 4 W3C Yes Yes Yes Yes

3.02 Yes

162

false if not selected) defaultChecked disabled form id name size tabIndex type value Sets or returns the default value of the checked attribute (true if checked by default and false if not) Sets or returns whether or not the radio button should be disabled Returns a reference to the radio button's parent form Sets or returns the id of the radio button (In IE 4 this property is readonly) Sets or returns the name of the radio button Sets or returns the size of the radio button Sets or returns the tab order for the radio button The type of the form element. For a radio object it will always be "radio" Sets or returns the value of the value attribute of the radio button 3 2 2 2 2 3.02 Yes 5.5 4 Yes No

3.02 Yes

3.02 Yes 3.02 Yes 4 Yes 3.02 Yes 3.02 Yes

Methods
Syntax: object.method_name() Method blur() click() focus() select() Description Removes focus from the radio button Simulates a mouse-click on the radio button Sets focus on the radio button Selects the radio button 2 2 N 2 IE 4 4 4 W3C Yes Yes No

3.02 Yes

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onClick onFocus onSelectStart Description Executes some code when the radio button loses focus Executes some code when the user clicks on the radio button Executes some code when the radio button gets focus Executes some code when the radio button is selected 2 N 2 IE 4 4 3.02 4 W3C

HTML DOM Reset Object


Reset Object
For each instance of an HTML <input type="reset"> tag on a form, a Reset object is created. All Reset objects are stored in the elements array of the corresponding form. You can access a Reset object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute. The Reset object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name

163

Property accept accesskey align alt defaultValue disabled form id name size tabIndex type value

Description Sets or returns a list of content types that the server that processes this form will handle correct Sets or returns the keyboard key to access the reset button Sets or returns the alignment of the reset button according to the surrounding text Sets or returns an alternate text to display if the browser does not support reset buttons Sets or returns the default value of the reset button Sets or returns whether or not the reset button should be disabled Returns a reference to the reset button's parent form Sets or returns the id of the reset button (In IE 4 this property is readonly) Sets or returns the name of the reset button Sets or returns the size of the reset button Sets or returns the tab order for the reset button Returns the type of the form element. For a reset object it will always be "reset" Sets or returns the value of the value attribute of the reset button

IE 4 -

W3C Yes Yes Yes Yes

3.02 Yes 5.5 2 4 2 Yes No 3.02 Yes

3.02 Yes 3.02 Yes 4 Yes

3 2

3.02 Yes 3.02 Yes

Methods
Syntax: object.method_name() Method blur() click() focus() select() Description Removes focus from the reset button Simulates a mouse-click on the reset button Sets focus on the reset button Selects the reset button 2 2 N 2 IE 4 4 4 W3C Yes Yes No

3.02 Yes

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onClick onFocus onSelectStart Description Executes some code when the reset button loses focus Executes some code when the user clicks on the reset button Executes some code when the reset button gets focus Executes some code when the reset button is selected 2 N 2 IE 4 4 3.02 4 W3C

HTML DOM Screen Object


The Screen object contains information about the client's display screen.

Examples
Detect details about the client's screen

Screen Object

164

The Screen object is automatically created by the JavaScript runtime engine and it contains information about the client's display screen. Its properties are described below: Note: The Screen object is not a W3C standard. The Screen object's properties are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: screen.property_name Property availHeight availWidth bufferDepth colorDepth deviceXDPI deviceYDPI fontSmoothingEnabled height logicalXDPI logicalYDPI pixelDepth updateInterval width Description Returns the height of the display screen - excluding the Windows Taskbar Returns the width of the display screen - excluding the Windows Taskbar Sets or returns the bit depth of the color palette in the off-screen bitmap buffer Returns the bit depth of the color palette on the destination device or buffer Returns the number of horizontal dots per inch of the display screen Returns the number of vertical dots per inch of the display screen Returns whether the user has enabled font smoothing in the display control panel The height of the display screen Returns the normal number of horizontal dots per inch of the display screen Returns the normal number of vertical dots per inch of the display screen Returns the color resolution (in bits per pixel) of the display screen Sets or returns the update interval for the screen Returns width of the display screen 4 4 4 4 4 4 N 4 4 IE 4 4 4 4 6 6 4 4 6 6 W3C No No No No No No No No No No No No No

HTML DOM Select Object


For each instance of an HTML <select> tag on a form, a Select object is created.

Examples
Disable and enable a dropdown list Return the name of the form that contains the dropdown list Return the number of options in the dropdown list Change the size of a dropdown list Select multiple options in a dropdown list Return the selected option as text

165

Return the selected option as a number Change the option text Remove an option from a dropdown list

Select Object
For each instance of an HTML <select> tag on a form, a Select object is created. All Select objects are stored in the elements array of the corresponding form. You can access a Select object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute. The Select object's collections, properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Collections
Collection options Description N IE W3C

Returns an array of all the options in a dropdown list (one element for each 2 <option> tag - starting at 0)

3.02 Yes

Properties
Syntax: object.property_name Property accessKey align disabled form id length multiple name selectedIndex Description Sets or returns the keyboard key to access the dropdown list Sets or returns the alignment of the dropdown list according to the surrounding text Sets or returns whether or not the dropdown list should be disabled Returns a reference to the dropdown list's parent form Sets or returns the id of the dropdown list (In IE 4 this property is readonly) Sets or returns the number of options in the dropdown list 2 Sets or returns the Boolean value indicating whether multiple items can be 6 selected Sets or returns the name of the dropdown list 2 Sets or returns the index of the selected option in the dropdown list. Note: 2 If the dropdown list allows for multiple selections it will only return the index of the first option selected Sets or returns the number of rows in the dropdown list Sets or returns the tab order for the dropdown list Returns the type of the form element. For a dropdown list it will be "select- 3 one" or "select-multiple" Sets or returns the value to be returned to the server when the form is submitted 6 6 6 2 N IE 4 4 5.5 4 W3C No No Yes No

3.02 Yes

3.02 Yes 3.02 Yes 3.02 Yes 3.02 Yes

size tabIndex type value

3.02 Yes 5 4 Yes Yes

3.02 Yes

Methods
Syntax: object.method_name()

166

Method add() blur() focus() remove()

Description Adds an option to the dropdown list Removes focus from the dropdown list Sets focus on the dropdown list Removes an option from the dropdown list

N 3 3 6

IE 4 4 4 4

W3C Yes Yes Yes Yes

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onChange onClick onFocus Description Executes some code when the dropdown list loses focus Executes some code when the dropdown list loses focus and its value has altered Executes some code when the user clicks the left mouse button in the dropdown list Executes some code when the dropdown list gets focus 2 N 2 2 IE 3.02 3.02 4 4 W3C

HTML DOM Style Object


Style object
The Style object represents an individual style statement. The Style object can be accessed from the document or from the elements to which that style is applied. The Style object's properties are described below:

Background Border and Margin Layout List Misc Positioning Printing Scrollbar Table Text

N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, M: Mac IE only, W: Windows IE only

Background properties
Property background Description Sets or returns all background properties in one Values backgroundColor backgroundImage backgroundRepeat backgroundAttachment backgroundPosition scroll fixed N 6 IE 4

backgroundAttachment

Sets or returns whether a background image is fixed or scrolls with the rest of the page

backgroundColor

Sets or returns the background color color-rgb of the element color-hex

167

color-name transparent backgroundImage backgroundPosition Sets or returns the background image of the element Sets or returns the starting position of the background image url("URL") none top left top center top right center left center center center right bottom left bottom center bottom right x-% y-% x-pos y-pos left center right x-% x-pos top center bottom y-% y-pos 6 6 6 4 4

backgroundPositionX

Sets or returns the x-coordinates of the backgroundPosition property

backgroundPositionY

Sets or returns the y-coordinates of the backgroundPosition property

backgroundRepeat

Sets or returns if/how a background repeat image will be repeated repeat-x repeat-y no-repeat

Border and Margin properties


Property border Description Values N 6 IE 4

Sets or returns all properties for the borderWidth four borders in one borderStyle borderColor Sets or returns all properties for the borderWidth bottom border in one borderStyle borderColor Sets or returns all property for the left border in one Sets or returns all property for the right border in one Sets or returns all property for the top border in one Sets or returns the color of the bottom border Sets or returns the color of the left border borderWidth borderStyle borderColor borderWidth borderStyle borderColor borderWidth borderStyle borderColor borderColor borderColor

borderBottom

borderLeft

borderRight

borderTop

borderBottomColor borderLeftColor borderRightColor borderTopColor borderBottomStyle borderLeftStyle

6 6 6 6 6 6

4 4 4 4 4 4

Sets or returns the color of the right borderColor border Sets or returns the color of the top border Sets or returns the style of the bottom border Sets or returns the style of the left borderColor borderStyle borderStyle

168

border borderRightStyle borderTopStyle borderBottomWidth borderLeftWidth borderRightWidth borderTopWidth borderColor Sets or returns the style of the right borderStyle border Sets or returns the style of the top border Sets or returns the width of the bottom border Sets or returns the width of the left border borderStyle borderWidth borderWidth 6 6 6 6 6 6 6 4 4 4 4 4 4 4

Sets or returns the width of the right borderWidth border Sets or returns the width of the top border borderWidth

Sets or returns the color of all four color-rgb borders (can have up to four colors) color-hex color-name Sets or returns the style of all four borders none dotted dashed solid double groove ridge inset outset thin medium thick length marginTop marginRight marginBottom marginLeft

borderStyle

borderWidth

Sets or returns the width of all four borders

margin

Sets or returns the top, right, bottom, and left margins of the element

marginBottom

Sets or returns the bottom margin of auto the element length % Sets or returns the left margin of the auto element length % Sets or returns the right margin of the element auto length %

marginLeft

marginRight

marginTop

Sets or returns the top margin of the auto element length % Sets or returns the color, style, and width of the outline around the element Sets or returns the color of the outline around the element outlineColor outlineStyle outlineWidth color-rgb color-hex color-name invert none dotted dashed solid double groove ridge inset

outline

5 (M)

outlineColor

5 (M)

outlineStyle

Sets or returns the style of the outline around the element

5 (M)

169

outset outlineWidth Sets or returns the width of the outline around the element thin medium thick length paddingTop paddingRight paddingBottom paddingLeft length % length % length % length % 6 5 (M)

padding

Sets or returns the top, right, bottom, and left padding of the element Sets or returns the bottom padding of the element Sets or returns the left padding of the element Sets or returns the right padding of the element Sets or returns the top padding of the element

paddingBottom paddingLeft paddingRight paddingTop

6 6 6 6

4 4 4 4

Layout properties
Property clear Description Sets or returns which sides of an element other floating elements are not allowed Values left right both none N 6 IE 4

clip

Sets or returns the shape of an auto element. What if an image is larger rect(top right bottom than the element it goes inside? left) This property lets you specify the dimensions of an element that should be visible, and the element is clipped into this shape, and displayed Returns the bottom coordinate of the auto clipping region length Returns the left coordinate of the clipping region Returns the right coordinate of the clipping region Returns the top coordinate of the clipping region Sets or returns meta-information auto length auto length auto length

clipBottom clipLeft clipRight clipTop content counterIncrement counterReset cssFloat cursor

6 6 6 6 6 6 6 6

5 (W) 5 (W) 5 (W) 5 (W) 5 (M) 5 (M) 5 (M) 5 (M) 4

Sets or returns the type of cursor to auto be displayed when the mouse pointer crosshair moves over the element default hand pointer move e-resize ne-resize nw-resize n-resize se-resize sw-resize s-resize w-resize text

170

wait help all-scroll (IE6+) col-resize (IE6+) no-drop (IE6+) not-allowed (IE6+) pointer (IE6+) progress (IE6+) row-resize (IE6+) url(uri) (IE6+) vertical-text (IE6+) direction display Sets or returns the reading order ltr rtl 6 6 5 4

Sets or returns how/if an element is block displayed none inline inline-block list-item (IE6+) table-header-group table-footer-group Sets or returns the filter/filters applied to the element

filter layoutGrid layoutGridChar layoutGridLine layoutGridMode layoutGridType markerOffset marks maxHeight maxWidth minHeight minWidth MozOpacity overflow overflowX overflowY styleFloat verticalAlign visibility width zoom

4 (W) 5 (W) 5 (W) 5 (W) 5 (W) 5 (W) 6 6 6 6 6 6 6 6 6 6 6 6 6 4 5 (W) 5 (W) 4 4 4 4 5.5 (W) 5 (M) 5 (M) 5 (M) 5 (M) 6 5 (M)

List properties
Property listStyle Description Values N 6 IE 4

Sets or returns all the properties for listStyleType a list in one listStylePosition listStyleImage Sets or returns the value of the image that is the list-item marker Sets or returns where the list-item marker is placed in the list Sets or returns the type of the listitem marker none url(url) outside inside disc circle

listStyleImage listStylePosition listStyleType

6 6 6

4 4 4

171

square decimal lower-roman upper-roman lower-alpha upper-alpha none

Misc properties
Property accelerator Description Sets or returns a Boolean value indicating whether the element contains an accelerator key Values false true N IE 5 (W)

behavior cssText imeMode 6

5 (W) 4 5 (W)

Positioning properties
Property bottom height left pixelBottom pixelHeight pixelLeft pixelRight pixelTop pixelWidth posBottom posHeight posLeft posRight posTop posWidth position right top width zIndex 6 6 6 6 6 Description Values N 6 6 6 IE 5 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 4 4 4

Printing properties
Property orphans widows page pageBreakAfter pageBreakBefore pageBreakInside Description Values N 6 6 6 6 6 6 IE 5 (M) 5 (M) 5 (M) 4 4 5 (M)

172

size

Scrollbar properties
Property scrollbar3dLightColor scrollbarArrowColor scrollbarBaseColor scrollbarDarkShadowColor scrollbarFaceColor scrollbarHighlightColor scrollbarShadowColor scrollbarTrackColor Description Values N IE 5.5 (W) 5.5 (W) 5.5 (W) 5.5 (W) 5.5 (W) 5.5 (W) 5.5 (W) 5.5 (W)

Table properties
Property borderCollapse borderSpacing captionSide emptyCells tableLayout Description Values N 6 6 6 6 6 IE 5 (M) 5 (M) 5 (M) 5 (M) 5

Text properties
Property color font fontFamily fontSize fontSizeAdjust fontStretch fontStyle fontVariant fontWeight letterSpacing lineBreak lineHeight quotes rubyAlign rubyOverhang rubyPosition textAlign textAlignLast textAutospace textDecoration textDecorationBlink textDecorationLineThrough 6 6 6 6 Description Values N 6 6 6 6 6 6 6 6 6 6 IE 4 4 4 4 5 (M) 5 (M) 4 4 4 4 5 4 5 (M) 5 5 5 4 5.5 5 (W) 4 4 4

173

textDecorationLineNone textDecorationLineOverline textDecorationLineUnderline textIndent textJustify textJustifyTrim textKashidaSpace textOverflow textShadow textTransform textUnderlinePosition unicodeBidi whiteSpace wordBreak wordSpacing wordWrap writingMode 6 6 6 6 6 6

4 4 4 4 5 5 5.5 6 (W) 5 (M) 4 5.5 5 4 5 (W) 6 5.5 (W) 5.5 (W)

HTML DOM Submit Object


For each instance of an HTML <input type="submit"> tag on a form, a Submit object is created.

Examples
Submitting a form Validate an e-mail address in a form Validate an input field with minimum and maximum values Validate an input field with a maximum number of characters Form validation

Submit Object
For each instance of an HTML <input type="submit"> tag on a form, a Submit object is created. All Submit objects are stored in the elements array of the corresponding form. You can access a Submit object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute. The Submit object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name

174

Property accept accesskey align alt defaultValue disabled form id name size tabIndex type value

Description Sets or returns a list of content types that the server that processes this form will handle correct Sets or returns the keyboard key to access the submit button Sets or returns the alignment of the submit button according to the surrounding text Sets or returns an alternate text to display if the browser does not support submit buttons Sets or returns the default value of the submit button Sets or returns whether or not the submit button should be disabled Returns a reference to the submit button's parent form Sets or returns the id of the submit button (In IE 4 this property is readonly) Sets or returns the name of the submit button Sets or returns the size of the submit button Sets or returns the tab order for the submit button

IE 4 -

W3C Yes Yes Yes Yes

3.02 Yes 5.5 2 4 2 Yes Yes 3.02 Yes

3.02 Yes 3.02 Yes 4 Yes 3.02 Yes 3.02 Yes

Returns the type of the form element. For a submit object it will always be 3 "submit" Sets or returns the value of the value attribute of the submit button 2

Methods
Syntax: object.method_name() Method blur() click() focus() select() Description Removes focus from the submit button Simulates a mouse-click on the submit button Sets focus on the submit button Selects the submit button 2 N IE 4 4 4 W3C Yes Yes No

3.02 Yes

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onClick onFocus onSelectStart Description Executes some code when the submit button loses focus Executes some code when the user clicks on the submit button Executes some code when the submit button gets focus Executes some code when the submit button is selected 4 2 N IE 4 4 3.02 4 W3C

HTML DOM Table Object


The Table object represents an HTML table element.

Examples
Change the width of a table border Change the cellPadding and cellSpacing of a table

175

Specify frames of a table Change height of a row Specify rules for a table Create a caption for a table Deleting rows in a table Adding rows to a table Align the cell content in a table row Change the cell content in a table row Vertical align the cell content in a table row Align the cell content in a single cell Vertical align the cell content in a single cell Adding cells to a table row Change the colspan of a table row

Table Object
The Table object represents an HTML table element. The Table object's collections, properties, methods and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Collections
Collection cells[] rows[] tBodies[] Description Returns an array containing each columns in the table Returns an array containing each row in the table Returns an array containing each tbody the table 6 N IE 5 4 4 W3C No Yes Yes

Properties
Syntax: object.property_name Property accesskey align background bgColor border borderColor Description Sets or returns the keyboard key to access the table Sets or returns the alignment of the table according to the surrounding text Sets or returns the background image of the table Sets or returns the background color of the table Sets or returns the width of the table border Sets or returns the color of the table border 6 6 6 N IE 4 4 4 4 4 5.5 W3C No Yes No Yes Yes No

176

caption cellPadding cellSpacing cols disabled frame

Sets or returns the caption of the table

4 4 4 4 5.5

Yes Yes Yes No No Yes

Sets or returns the amount of space space between the cell border and cell 6 content Sets or returns the amount of space between cells in the table Sets or returns the number of columns in the table Sets or returns whether or not the table should be disabled Sets or returns which borders to render around the table. Possible values are: 6 6


height id rules

void above below hsides vsides lhs rhs box border 6 6 4 4 4 Yes No Yes

Sets or returns the height of the table Sets or returns the id of the table (In IE 4 this property is read-only) Sets or returns which inner-borders to display. Possible values are:


summary tabIndex tFoot tHead width

none groups rows cols all 6 6 6 6 6 4 4 4 4 Yes No Yes Yes Yes

Sets or returns a description of the table Sets or returns the tab order for the table Returns the TFoot object of the table Returns the THead object of the table Sets or returns the width of the table

Methods
Syntax: object.method_name() Method blur() click() createCaption() createTFoot() createTHead() deleteCaption() deleteRow([i]) deleteTFoot() deleteTHead() focus() insertRow([i]) Description Removes focus from the table Simulates a mouse-click on the table Creates an empty caption element in the table Creates an empty tFoot element in the table Creates an empty tHead element in the table Deletes the caption element and its content from the table Deletes the specified row (tr) from the table Deletes the tFoot element and its content from the table Deletes the tHead element and its content from the table Sets focus on the table Creates a new row in the table 6 6 6 6 6 6 6 6 N IE 4 4 4 4 4 4 4 4 4 4 4 W3C No No Yes Yes Yes Yes Yes Yes Yes No Yes

177

moveRow(from,to) refresh()

Moves a row to a new position Refreshes the content of the table

5 4

No No

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onClick onFocus onSelectStart Description Executes some code when the table loses focus Executes some code when the user clicks on the table Executes some code when the table gets focus Executes some code when the table is selected N IE 4 4 4 4 W3C

HTML DOM TableData Object


The TableData object represents an HTML td element.

Examples
Change the width of a table border Change the cellPadding and cellSpacing of a table Specify frames of a table Change height of a row Specify rules for a table Create a caption for a table Deleting rows in a table Adding rows to a table Align the cell content in a table row Change the cell content in a table row Vertical align the cell content in a table row Align the cell content in a single cell Vertical align the cell content in a single cell Adding cells to a table row Change the colspan of a table row

TableData Object
The TableData object represents an HTML td element.

178

The TableData object's properties, methods and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property abbr accesskey align axis background bgColor borderColor cellIndex ch chOff colSpan disabled headers height id innerHTML innerText noWrap outerHTML outerText rowSpan scope tabIndex vAlign width Sets or returns the tab order for the table cell Sets or returns how cell content are vertically aligned Sets or returns the width of the table cell Description Sets or returns an abbreviated text for the table cell (for non-visual media such as speech or Braille) Sets or returns the keyboard key to access the table cell Sets or returns the horizontal alignment of data within the table cell Sets or returns a comma-delimited list of related table cells (categories) Sets or returns the background image for the table cell Sets or returns the background color for the table cell Sets or returns the border color of the table cell Returns the position of the cell in the cells collection of a row Sets or returns the alignment character for the table cell Sets or returns the offset of alignment character for the table cell Sets or returns the number of columns the table cell should span Sets or returns whether or not the table cell should be disabled Sets or returns a list of space-separated header cell ids Sets or returns the height of the table cell Sets or returns the id of the table cell (In IE 4 this property is read-only) Sets or returns the HTML between the start and end tags of the table cell Sets or returns the text between the start and end tags of the table cell Sets or returns a Boolean value indicating whether or not the browser automatically performs word wrap in the table cell Sets or returns the table data object and its content in HTML Sets or returns the text of the table data object Sets or returns the number of rows the table cell should span N IE 6 4 4 6 4 4 4 4 6 6 4 5.5 6 4 4 4 4 4 4 4 4 6 4 4 4 W3C Yes No Yes Yes No Yes No Yes Yes Yes Yes No Yes No No No No Yes No No Yes Yes No Yes Yes

Methods
Syntax: object.method_name() Method blur() click() focus() Description Removes focus from the table cell Simulates a mouse-click on the table cell Sets focus on the table cell N IE 4 4 4 W3C No No No

Events
Syntax: object.event_name="someJavaScriptCode"

179

Event onBlur onClick onFocus onSelectStart

Description Executes some code when the table cell loses focus Executes some code when the user clicks on the table cell Executes some code when the table cell gets focus Executes some code when the table cell is selected

IE 4 4 4 4

W3C

HTML DOM TableHeader Object


The TableHeader object represents an HTML th element.

Examples
Change the width of a table border Change the cellPadding and cellSpacing of a table Specify frames of a table Change height of a row Specify rules for a table Create a caption for a table Deleting rows in a table Adding rows to a table Align the cell content in a table row Change the cell content in a table row Vertical align the cell content in a table row Align the cell content in a single cell Vertical align the cell content in a single cell Adding cells to a table row Change the colspan of a table row

TableHeader Object
The TableHeader object represents an HTML th element. The TableHeader object's properties, methods and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties

180

Syntax: object.property_name Property abbr accesskey align axis background bgColor borderColor cellIndex ch chOff colSpan headers height id innerHTML innerText noWrap outerHTML outerText rowSpan scope tabIndex vAlign width Sets or returns the tab order for the table header cell Sets or returns how header cell content are vertically aligned Sets or returns the width of the table header cell Description Sets or returns an abbreviated text for the table header cell (for non-visual media such as speech or Braille) Sets or returns the keyboard key to access the table header cell Sets or returns the horizontal alignment of data within the table header cell Sets or returns a comma-delimited list of related table header cells (categories) Sets or returns the background image for the table header cell Sets or returns the background color for the table header cell Sets or returns the border color of the table header cell Returns the position of the cell in the cells collection of a row Sets or returns the alignment character for the table header cell Sets or returns the offset of alignment character for the table header cell Sets or returns the number of columns the table header cell should span Sets or returns a list of space-separated header cell ids Sets or returns the height of the table header cell Sets or returns the id of the table header cell (In IE 4 this property is readonly) Sets or returns the HTML between the start and end tags of the table header cell Sets or returns the text between the start and end tags of the table header cell Sets or returns a Boolean value indicating whether or not the browser automatically performs word wrap in the table header cell Sets or returns the table header object and its content in HTML Sets or returns the text of the table header object Sets or returns the number of rows the table header cell should span N IE 6 5 4 6 4 4 4 4 6 6 4 6 4 4 4 4 4 4 4 4 6 5 4 4 W3C Yes No Yes Yes No Yes No Yes Yes Yes Yes Yes No No No No Yes No No Yes Yes No Yes Yes

Methods
Syntax: object.method_name() Method blur() click() focus() Description Removes focus from the table header cell Simulates a mouse-click on the table header cell Sets focus on the table header cell N IE 5 4 5 W3C No No No

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onClick onFocus Description Executes some code when the table header cell loses focus Executes some code when the user clicks on the table header cell Executes some code when the table header cell gets focus N IE 5 4 5 W3C

181

onSelectStart

Executes some code when the table header cell is selected

HTML DOM TableRow Object


The TableRow object represents an HTML tr element.

Examples
Change the width of a table border Change the cellPadding and cellSpacing of a table Specify frames of a table Change height of a row Specify rules for a table Create a caption for a table Deleting rows in a table Adding rows to a table Align the cell content in a table row Change the cell content in a table row Vertical align the cell content in a table row Align the cell content in a single cell Vertical align the cell content in a single cell Adding cells to a table row Change the colspan of a table row

TableRow Object
The TableRow object represents an HTML tr element. The TableRow object's collections, properties, methods and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Collections
Collection cells[] Description Returns an array containing each columns in the table row N IE 4 W3C Yes

Properties

182

Syntax: object.property_name Property accesskey align bgColor borderColor ch chOff disabled height id innerHTML innerText outerHTML outerText rowIndex sectionRowIndex tabIndex vAlign width Description Sets or returns the keyboard key to access the table row Sets or returns the horizontal alignment of data within cells of the table row Sets or returns the background color for the table row Sets or returns the border color of the table row Sets or returns the alignment character for cells in the table row Sets or returns the offset of alignment character for cells in the table row Sets or returns whether or not the table row should be disabled Sets or returns the height of the table row Sets or returns the id of the table row (In IE 4 this property is read-only) Sets or returns the HTML between the start and end tags of the table row Sets or returns the text between the start and end tags of the table row Sets or returns the table row object and its content in HTML Sets or returns the text of the table row object Returns the table row object's position in the rows collection for the table Returns the table rows object's position in the tBody, tHead, or tFoot rows collection Sets or returns the tab order for the table row Sets or returns how cell content are vertically aligned within the table row Sets or returns the width of the table row N IE 5 4 4 4 6 6 5.5 5 4 5 5 4 4 4 4 5 4 4 W3C No Yes Yes No Yes Yes No No No No No No No Yes Yes No Yes No

Methods
Syntax: object.method_name() Method blur() click() deleteCell([i]) focus() insertCell([i]) Description Removes focus from the table row Simulates a mouse-click on the table row Deletes a cell in the table row Sets focus on the table row Creates a new cell in the table row N IE 4 4 4 5 4 W3C No No Yes No Yes

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onClick onFocus onSelectStart Description Executes some code when the table row loses focus Executes some code when the user clicks on the table row Executes some code when the table row gets focus Executes some code when the table row is selected N IE 4 4 4 4 W3C

HTML DOM Text Object


For each instance of an HTML <input type="text"> tag on a form, a Text object is created.

183

Examples
Validate an e-mail address in a form Validate an input field with minimum and maximum values Validate an input field with a maximum number of characters Form validation Set focus to an input field Select the content of an input field Radio buttons in a form Checkboxes in a form Dropdown list in a form Another dropdown list Jump to the next field when the current field's maxlength has been reached

Text Object
For each instance of an HTML <input type="text"> tag on a form, a Text object is created. All Text objects are stored in the elements array of the corresponding form. You can access a Text object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute. The Text object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name Property accept accessKey align alt defaultValue disabled form id maxLength name readOnly Description Sets or returns a list of content types that the server that processes this form will handle correct Sets or returns the keyboard key to access the text field Sets or returns the alignment of the text field according to the surrounding text Sets or returns an alternate text to display if the browser does not support text fields Sets or returns the initial value of the text field Sets or returns whether or not the text field should be disabled Returns a reference to the text field's parent form Sets or returns the id of the text field (In IE 4 this property is read-only) Sets or returns the maximum number of characters in the text field Sets or returns the name of the text field Sets or returns whether or not the text field should be read-only 6 2 6 2 6 2 N IE 4 W3C Yes Yes Yes Yes

3.02 Yes 5.5 4 4 4 Yes No Yes Yes 3.02 Yes

3.02 Yes

184

size tabIndex type value

Sets or returns the size of the text field Sets or returns the tab order for the text field Returns the type of the form element. For a text object it will always be "text" Sets or returns the value of the value attribute of the text field

6 3 2

3.02 Yes 4 Yes 3.02 Yes 3.02 Yes

Methods
Syntax: object.method_name() Method blur() click() focus() select() Description Removes focus from the text field Simulates a mouse-click in the text field Sets focus on the text field Selects and highlights the entire text that is in the text field 2 2 N 2 IE 4 4 4 W3C Yes No Yes

3.02 Yes

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onChange onClick onFocus onKeyDown onKeyPress onKeyUp onSelect onSelectStart Description Executes some code when the text field loses focus Executes some code when the text field loses focus and its value has altered Executes some code when the user clicks the left mouse button in the text field Executes some code when the text field gets focus Executes some code when a key is pressed in the text field Executes some code when a key is released in the text field Executes some code when some text in the text field is selected 2 4 4 N 2 2 IE 4 3.02 4 3.02 4 4 4 3.02 4 W3C

Executes some code when an alphanumeric key is pressed in the text field 4 Executes some code when the current selection is changed in the text field 2

HTML DOM Textarea Object


Textarea Object
For each instance of an HTML <textarea> tag on a form, a Textarea object is created. All Textarea objects are stored in the elements array of the corresponding form. You can access a Textarea object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute. The Textarea object's properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer, W3C: World Wide Web Consortium (Internet Standard)

Properties
Syntax: object.property_name

185

Property accessKey cols defaultValue disabled form id name readOnly rows tabIndex type value

Description Sets or returns the keyboard key to access the textarea Sets or returns the width (in characters) of the textarea Sets or returns the initial contents of the textarea Sets or returns whether or not the textarea should be disabled Returns a reference to the textarea's parent form Sets or returns the id of the textarea (In IE 4 this property is read-only) Sets or returns the name of the textarea Sets or returns whether or not the textarea should be read-only Sets or returns the height (in rows) of the textarea Sets or returns the tab order for the textarea Returns the type of the form element. For a textarea object it will always be "textarea" Sets or returns the text in the textarea

N 6 6 2 2 6 6 3 2

IE 4

W3C Yes

3.02 Yes 3.02 Yes 5.5 4 4 4 Yes No Yes Yes 3.02 Yes 3.02 Yes 3.02 Yes 3.02 Yes 3.02 Yes

Methods
Syntax: object.method_name() Method blur() click() focus() select() Description Removes focus from the textarea Simulates a mouse-click in the textarea Sets focus on the textarea Selects and highlights the entire text that is in the textarea 2 2 N 2 IE 4 4 W3C No Yes

3.02 Yes 3.02 Yes

Events
Syntax: object.event_name="someJavaScriptCode" Event onBlur onChange onClick onFocus onKeyDown onKeyPress onKeyUp onSelect Description Executes some code when the textarea loses focus Executes some code when the textarea loses focus and its value has altered Executes some code when the user clicks the left mouse button in the textarea Executes some code when the textarea gets focus Executes some code when a key is pressed down in the textarea Executes some code when a key is pressed in the textarea Executes some code when a key is released in the textarea Executes some code when some text in the textarea is selected 2 4 4 4 2 N 2 2 IE 3.02 3.02 4 3.02 W3C

HTML DOM Window Object


The Window object corresponds to the browser window.

Examples
Display an alert box

186

Alert box with line-breaks Display a confirm box Display a prompt box Open a new window when clicking on a button Open a new window and control its appearance Open multiple windows with one click Send the client to a new location (URL/page) Refresh a document Write some text in the windows status bar Print a page Trapped in a frame? This is how you break out of frames Update 2 frames with one click Update 2 other frames Resize a window Resize a window to a specified size Scroll the window Scroll the window to a specified position The setInterval() and clearInterval() methods The setTimeout() method The setTimeout() method with a pointer to a function The setTimeout() method with a pointer to a function 2 Create a pop-up

Window Object
The Window object corresponds to the browser window. A Window object is created automatically with every instance of a <body> or <frameset> tag. The Window object's collections, objects, properties, methods, and events are described below: N: Netscape (including Mozilla when N6 or higher), IE: Internet Explorer

Collections
Collection Description N IE

187

frames[]

Returns all named frames in the window

3.02

Objects
Object clientInformation clipboardData document event external history location navigator screen Contains the URLs visited from the window. See History object Contains the current URL of the window. See Location object Contains information about the browser. See Navigator object Contains information about the client's screen. See Screen object Represents the HTML document object in the window. See Document object Represents the state of an event Description Contains information about the browser N IE 4 5 3.02 4 4 3.02 3.02 3.02 4

Properties
Syntax: window.property_name Property closed defaultStatus dialogArguments dialogHeight dialogLeft dialogTop dialogWidth frameElement length name offscreenBuffering opener parent returnValue screenLeft screenTop self status top Description N IE 4 3.02 4 4 4 4 4 5.5 6 2 4 3.02 4 3 2 4 3.02 4 5 5 2 2 2 3.02 3.02 3.02

Returns a Boolean value that specifies whether the referenced window has 3 been closed Sets or returns the default text in the statusbar of the windows (will be displayed when the page loads) Returns all variables passed into the modal dialog window Sets or returns the height of the modal dialog window Sets or returns the left coordinates of the modal dialog window Sets or returns the top coordinates of the modal dialog window Sets or returns the width of the modal dialog window Returns the frame/iframe object that is hosting the window in the parent document Sets or returns the number of frames in the window Sets or returns the name of the window Sets or returns a Boolean value that specifies whether the window is drawn offscreen before being visible to the user Sets or returns a reference to the window that created the window Returns the parent window Sets or returns the value returned from the modal dialog window Returns the x-coordinate of the upper left corner of the browser - relative to the upper left corner of the screen Returns the y-coordinate of the top corner of the browser - relative to the top corner of the screen Returns a reference to the current window Sets or returns the text in the statusbar of the window Returns the topmost ancestor window 2

Methods
Syntax: window.method_name()

188

Method alert("msg") attachEvent("event",pointer) blur() clearInterval(ID) clearTimeout(ID) close() confirm("msg") createPopup([args]) execScript("code", "lang")

Description Displays an alert box with a message and an OK button Removes focus from the current window Cancels a timeout that is set with the setInterval() method Cancels a timeout that is set with the setTimeout() method Closes the current window Displays a dialog box with a message, a Cancel, and an OK button Creates a pop-up window Executes a specified script. The arguments can take the following values: code lang Required. The code to be executed Required. JScript | VBScript | JavaScript

N 2 3 4 2 2 2

IE 3.02 5 4 4 3.02 3.02 3.02 5.5 4

focus() moveBy(x,y) moveTo(x,y) navigate("URL") open(["URL", "name", "specs", replace])

Sets focus on the current window

4 4 4 3.02 3.02

Moves the window a specified number of pixels in relation to its current co- 4 ordinates Moves the window's left and top edge to the specified co-ordinates Loads the specified URL into the window Opens a new browser window. The arguments can take the following values: "URL" - Optional. Specifies the URL of the page to display if no URL is specified, a new window with about:blank is displayed) "name" - Optional. Specifies the value for the target attribute on a form or a link. The following values are supported: _blank URL is loaded into a new window 4

_media URL is loaded into the content area of the Media Bar (IE6+) _parent URL is loaded into the parent frame _search URL is opened in the browser's search pane (IE5+) _self _top URL replaces the current page URL replaces any framesets that may be loaded

"specs" - Optional. A comma-separated list of items. The following values are supported: channelmode = yes whether to display the window in theater mode. | no | 1 | 0 Default is no directories = yes | no | 1 | 0 fullscreen = yes | no | 1 | 0 height = number left = number whether to add directory buttons. Default is yes whether to display the browser in full-screen mode. Default is no. A window in full-screen mode must also be in theater mode the height of the window, in pixels. Min. value is 100 the left position, in pixels

location = yes | no whether to display the address field. Default is yes |1|0 menubar = yes | no whether to display the menu bar. Default is yes |1|0 resizable = yes | no whether the window is resizable. Default is yes |1|0

189

scrollbars = yes | no | 1 | 0

whether to display scroll bars. Default is yes

status = yes | no | whether to add a status bar. Default is yes 1|0 titlebar = yes | no | whether to display the title bar. Ignored unless the 1|0 calling application is an HTML Application or a trusted dialog box. Default is yes toolbar = yes | no | whether to display the browser toolbar. Default is yes 1|0 top = number width = number width = number the top position, in pixels the width of the window, in pixels. Min. value is 100 the width of the window, in pixels. Min. value is 100

replace - Optional.Specifies whether the URL creates a new entry or replaces the current entry in the history list. The following values are supported: true false print() prompt(["msg", "default"]) URL replaces the current document in the history list URL creates a new entry in the history list 4 2 5 3.02

Prints the contents of the current window Displays a dialog box prompting the user for input. The arguments can take the following values: msg Optional. The message to display in the dialog box. Default is ""

default Optional. The default text in the input field resizeBy(x,y) resizeTo(width, height) scroll(x,y) scrollBy(x,y) scrollTo(x,y) setActive() setInterval(code, millisec[, "lang"]) Calls a function / evaluate an expression every time a specified interval (in 4 milliseconds) has been reached. The arguments can take the following values: code lang setTimeout(code, millisec[, "lang"]) Required. A pointer to a function or the code to be executed Optional. JScript | VBScript | JavaScript 3.02 Resizes the window by the specified pixels. Note: This method does not work on dialog windows Resizes the window to the specified width and height. Note: This method does not work on dialog windows Deprecated. Use scrollTo() instead. Scrolls the content by the specified number of pixels. Note: The visible 4 property of the window's scrollbar must be set to true if using this method Scrolls the content to the specified co-ordinates 4 4 4 4 4 4 5.5 4

millisec Required. The number of milliseconds

Calls a function / evaluate an expression after a specified number of milliseconds. The arguments can take the following values: code lang Required. A pointer to a function or the code to be executed Optional. JScript | VBScript | JavaScript

millisec Required. The number of milliseconds

showHelp("URL"[, contextID])

Displays a Help file (must be of type .htm or .chm). When using this method, a second Help box appears when pressing F1 or when clicking Help on the menu bar. To prevent the default Help box from appearing set returnValue to false. The arguments can take the following values:

190

URL

Required. The URL of a Help file

contextID Optional. A string or integer that specifies a context identifier in the Help file showModalDialog("URL"[, args, "list"]) Loads a URL in a modal dialog box. A modal dialog box retains focus while open. The user CANNOT switch windows until the dialog box is closed. The arguments can take the following values: "URL" - Required. The URL of the document to display. args - Optional. The arguments to use when displaying the URL. Use this parameter to pass a value of any type, including an array of values. The dialog box can extract the values from the dialogArguments property of the window object. "list" - Optional. Specifies the window ornaments for the dialog box, using one or more of the following semicolon-delimited values: dialogHeight : number the height* of the dialog window 4

dialogLeft : number the left position of the dialog window dialogTop : number the top position of the dialog window dialogWidth : number the width* of the dialog window

center : yes | no | 1 whether to center the dialog window within the | 0 | on | off desktop. Default is yes dialogHide : yes | whether the dialog window is hidden when printing. no | 1 | 0 | on | off Only available when a dialog box is opened from a trusted application. Default is no edge : sunken | raised the edge style of the dialog window. Default is raised

help : yes | no | 1 | whether the dialog window displays the Help icon. 0 | on | off Default is yes resizable : yes | no whether the dialog window is resizable. Default is no | 1 | 0 | on | off scroll : yes | no | 1 whether the dialog window displays scrollbars. Default | 0 | on | off is yes status : yes | no | 1 whether the dialog window displays a status bar. | 0 | on | off Default is yes for untrusted dialog windows and no for trusted dialog windows unadorned : yes | whether the dialog window displays the border no | 1 | 0 | on | off window chrome. Only available when a dialog window is opened from a trusted application. Default is no showModelessDialog("URL"[, args, "list"]) Loads a URL in a modeless dialog box. The modeless dialog box displays even when the user switches focus to another window (useful for menus and Help systems). The arguments can take the following values: "URL" - Required. The URL of the document to display. args - Optional. The arguments to use when displaying the URL. Use this parameter to pass a value of any type, including an array of values. The dialog box can extract the values from the dialogArguments property of the window object. "list" - Optional. Specifies the window ornaments for the dialog box, using one or more of the following semicolon-delimited values: dialogHeight : the height* of the dialog window 5

191

number dialogLeft : number the left position of the dialog window dialogTop : number the top position of the dialog window dialogWidth : number the width* of the dialog window

center : yes | no | 1 whether to center the dialog window within the | 0 | on | off desktop. Default is yes dialogHide : yes | whether the dialog window is hidden when printing. no | 1 | 0 | on | off Only available when a dialog box is opened from a trusted application. Default is no edge : sunken | raised the edge style of the dialog window. Default is raised

help : yes | no | 1 | whether the dialog window displays the Help icon. 0 | on | off Default is yes resizable : yes | no whether the dialog window is resizable. Default is no | 1 | 0 | on | off scroll : yes | no | 1 whether the dialog window displays scrollbars. Default | 0 | on | off is yes status : yes | no | 1 whether the dialog window displays a status bar. | 0 | on | off Default is yes for untrusted dialog windows and no for trusted dialog windows unadorned : yes | whether the dialog window displays the border no | 1 | 0 | on | off window chrome. Only available when a dialog window is opened from a trusted application. Default is no * The default unit of measure for dialogHeight and dialogWidth in IE4 is em; in IE5 it is px. Other values to use: cm, mm, in, pt, pc, or ex. For consistent results, use px! Note: The min. dialogHeight you can specify is 100px.

Events
Syntax: window.event_name="someJavaScriptCode" Event onBlur onError onFocus onLoad onResize onUnload Description Executes some code when a Blur event occurs Executes some code when an Error event occurs Executes some code when a Focus event occurs Executes some code when an Load event occurs Executes some code when a Resize event occurs Executes some code when an Unload event occurs N 3 3 3 2 4 2 IE

192

Das könnte Ihnen auch gefallen