Vous êtes sur la page 1sur 62

yet another insignificant programming notes...


TABLE OF CONTENTS (HIDE) 1. Introduction

1.1 JavaScript vs. Java 1.2 What JavaScript Cannot Do

2. Preparation 3. Getting Started by Examples

3.1 Example 1: Functions alert() and document.write() 3.2 Example 2: Variable, if-else and Functions prompt(), confirm() 3.3 Example 3: Date Object and Conditional Statement 3.4 Example 4: Loop 3.5 Example 5: User-defined Function and onclick 3.6 Example 6: Event Handlers: onload, onunload, onmouseover, onmouseout 3.7 Example 6a: Separating HTML, CSS and JavaScript 3.8 Example 7: Modifying the Contents of HTML Elements and External Script 3.9 Example 8: Intercepting an Hyperlink 3.10 More Advanced JavaScript Examples

4. Writing and Debugging JavaScripts

4.1 4.2 4.3 4.4 4.5 5.1 5.2 5.3 5.4 Firefox: Firebug add-on for Firefox - ESSENTIAL Other Browsers' add-on Aptana Studio NetBeans Eclipse The <script>...</script> Tags <head> or <body>? External JavaScript The <noscript>...</noscript> Tags

5. JavaScript & HTML

6. JavaScript Basic Syntax

6.1 Comment 6.2 Expression 6.3 Statement & Block 6.4 Variables, Literals & Types 6.5 "Number" Type, Literals & Operations 6.6 "String" Type, Literals & Operations 6.7 "Boolean" Type, Literals & Operations 6.8 Explicit Type Conversion 6.9 Scope of a Variable 6.10 Flow Control 6.11 Loops 6.12 Functions 6.13 Interacting with Users 6.14 Other Top-level Built-in Functions 6.15 An Introduction to Events

7. Objects

7.1 Properties and Methods 7.2 The dot operator 7.3 Constructor & the "new" Operator

8. Built-in JavaScript Objects

8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 9.1 9.2 9.3 9.4 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 11.1 11.2 11.3 11.4

Common Properties and Methods for all JavaScript objects Array Object String Object Number Object Boolean Object Date Object Math Object Function Object Creating new objects via Constructor and "new" operator Creating objects via Object Initializer Property prototype Property constructor Finding and Selecting Elements Manipulating Element's Content thru the "innerHTML" Property DOM Tree & Nodes Text Node Attribute Properties Attribute style (for CSS) Manipulating Nodes The document object Attach Event Handler to an HTML tag Built-in Events and Event Handlers The Event object Adding Event Listener

9. Defining Your Own Objects

10. Document Object Model (DOM) API for JavaScript

11. Event Handling in HTML DOM

12. JavaScript Built-in Browser Objects: navigator, window, screen, history, location
12.1 The navigator object 12.2 The window object

13. Regular Expression

13.1 Examples 13.2 Creating a Regexe in JavaScript 13.3 JavaScript's Methods that use Regular Expression

14. Miscellaneous
14.1 14.2 14.3 14.4 14.5 Task Scheduling via Timeout Bitwise Operators Operator Precedence Try-catch and Exception Handling Execute JavaScript Statement from Browser's Address Bar

1. Introduction
JavaScript is the most widely used client-side programming language on the web. It is: a small, lightweight, object-oriented, cross-platform, special-purpose scripting language meant to be run under a host environment (typically a web browser). a client-side scripting language to enrich web user-interfaces and create dynamic web pages (e.g., form input validation, and immediate response to user's actions). the engine that supports AJAX (Asynchronous JavaScript and XML), which generate renew interest in JavaScript. JavaScript, originally called LiveScript, was created by Brendan Eich at Netscape in 1995. Soon after, Microsoft lanuched its own version of JavaScript called JScript. Subsequently, Netscape submitted it to ECMA (formerly "European Computer Manufacturers Association", now "Ecma International European association for standardizing information and communication systems ") for standardization, together with Microsoft's JScript. The ECMA Specification is called "ECMA-262 ECMAScript Language Specification" (also approved as "ISO/IEC 16262"): First Edition (June 1997) Second Edition (August 1998) Third Edition (December 1999) Forth Edition - abandon due to political differences Fifth Edition, 5.1 Edition (June 2011): not finalized, working draft only. Meanwhile, the Mozilla Project (@ https://developer.mozilla.org/en/JavaScript) continues to upgrade the JavaScript with these major versions: 1.0 (1996) 1.3 (1998): ECMA-262 1st edition compliance 1.5 (1999): ECMA-262 3rd edition compliance 1.6, 1.7: 1.8 (2008), Latest 1.8.5: ECMA-262 5th edition compliance (Firefox 4)

1.1 JavaScript vs. Java

Java is a full-fledge general-purpose programming language created by James Gosling at Sun Microsystems (now part of Oracle), released in Aug 1995. JavaScript is created by Brendan Eich at Netscape in 1995. Originally called LiveScript, it is a small and lightweight special-purpose language for writing client-side program running inside the web browser to create active user-interface and

generate dynamic web pages. Java also supports client-side programming via the so-called Java applets. JavaScript is not a general-purpose nor a stand-alone programming language (it has to be run inside the browser). It was originally called LiveScript and was renamed to JavaScript in an ill-fated marketing decision to try to capitalize on the popularity of Java language, when Netscape released it Navigator 2 in 1996 (Navigator 2 also runs the Java applets). Java and JavaScript are totally different languages for different programming purposes. However, in the early days, some efforts were made to adopt Java syntaxes and conventions into JavaScript, such that JavaScript seems to be a subset of Java. In reality, they have very little in common. But, if you know Java, you should find JavaScript easier to learn because of these common syntaxes.

1.2 What JavaScript Cannot Do

Remember that JavaScript is a client-side program that you downloaded from a server, and run inside the browser of your (client) machine. What to stop someone from writing a JavaScript that wipes out your harddisk, or triggers a denial-of-service attack to another server? As a result, for security purpose, 1. It cannot read file from the client's machine. 2. It can only connect to the server that it come from. It can read file from the server that it come from (Ajax). It cannot write file into the server machine. 3. It cannot connect to another server. 4. It cannot close a window that it does not open.

2. Preparation
I shall assume that you know HTML and CSS (you cannot do JavaScript without understanding HTML/CSS!). I shall also assume that you understanding some programming basics (e.g., if-else, forloop). You need a text editor to write your JavaScript. You could use a plain text editor such as NotePad. But to improve your productivity, a good programming text editor is essential. There are many freeware/shareware available, such as PSPad (www.pspad.com), NotePad++ (http://notepadplus.sourceforge.net), TextPad (www.textpad.com) (Read "Programming Text Editors"). You can also use a full-scale IDE such as NetBeans or Eclipse, which provides content-assist (aka auto-complete) feature that greatly enhances your productivity. JavaScripts run inside a browser. There are many (too many!) standards regarding JavaScript, none of the browser adheres to all the standards strictly. Furthermore, browser often create their own extension. As the behavior of JavaScript could be different in different browsers, I suggest that you have the Internet Explorer (IE), Mozilla Firefox, and Google Chrome for testing.

3. Getting Started by Examples

Let us begin by looking at some simple JavaScripts.

3.1 Example 1: Functions




Let us write our first JavaScript to print the message "Hello, world". Start with a new file and enter the following codes. Do not enter the line numbers, which is used to aid in explanation. Take note that: JavaScript is case sensitive. A rose is NOT a ROSE and is NOT a Rose. "Extra" white spaces (blanks, tabs and newlines) are ignored. That is, multiple white spaces is treated as a single blank character. You could use them liberally to make your program easier to read. Save the file as "JSEx1.html" (or any filename that you prefer, with file extension of ".html" or ".htm"). Run the script by loading the HTML file into a JavaScript-enabled browser.

" JSEx1.html "

1<html> 2<head> 3 4 5 6 <title>JavaScript Example 1: Functions alert() and document.write()</title> <script type="text/javascript"> alert("Hello, world!"); </script>

7</head> 8<body> 9 10 11 12 13 14 15</body> 16</html> <h1>My first JavaScript says:</h1> <script type="text/javascript"> document.write("<h2><em>Hello world, again!</em></h2>"); document.write("<p>This document was last modified on " + document.lastModified + ".</p>"); </script>

Dissecting the Program

1. JavaScripts are programming codes that are embedded inside an HTML document. The codes are contained between a pair of <script> and </script> tags. The attribute type="text/javascript" in the <script> start-tag identifies the scripting language, as follow:
2. <script type="text/javascript"> 3. // Your JavaScript programming codes here! </script>

(You can now omit type="text/javascript". Older versions of JavaScripts use Language="JavaScript". Both type and language are not needed in HTML 5.)

4. You could place the script in either the HEAD section (called header script) or BODY section (called body script) of an HTML document. You are free to embed as many scripts into a single document as you like, using multiple <script>...</script> tags. Lines 4-6 and Line 10-14 are two pieces of JavaScripts, placed in the HEAD and BODY sections, respectively. 5. JavaScript statements are terminated by a semi-colon ';'. 6. The alert(string) function (Line 5) pops out a dialog box displaying the string and a OK button. Strings are enclosed by a pair of double quotes or single quotes. 7. The current web page is represented by the so-called document object in the JavaScript. The document.lastModified (Line 13) property stores the last modified date of the current document. The document.write(string) function (Line 11 to 13) can be used to write the specified string to the current document, as part of the current HTML document. 8. The "+" operator (Line 13) concatenates pieces of the strings, similar to Java language. 9. As the result of the document.write(), the BODY section of this document contains:
10. <h1>My First JavaScript says</h1> <h2><em>Hello world, again!</em></h2><p>This document was last modified on mm/dd/yyyy hh:mm:ss.</p>

11. alert() and document.write() are some of the commonly-used built-in functions provided in JavaScript.

TRY: Print the document's title and the URL location. (Hints: use document.title and
document.location properties.)

Control-Refresh (Control-F5): If you modify the codes and reload the web page, the new
codes may not get executed because the browser caches the previously loaded version. You could use Control-F5 (Control-Refresh) to ask the browser to discard the cached page, and fetch a new page.

3.2 Example 2: Variable, if-else and Functions

prompt() , confirm()

This script prompts the user for his/her name, confirms the name, and prints a greeting message. There are three kinds of pop-up diglog boxes in JavaScript, to interact with the users: 1. The alert(string) function puts the string on a pop-up box with a OK button. User needs to click the OK button to continue. 2. The prompt(string, defaultString) function puts the string on a pop-up box with OK and Cancel buttons. It returns the input entered by the user as a string; or a special value called null if the user hits the Cancel button. 3. The confrim(string) function puts the string on a pop-up box with with OK and Cancel buttons. It returns true if user hits the OK button; or false otherwise.

" JSEx2.html "

1<html> 2<head> 3 4 5 6 7 8 9 10 11 12 } </script> <title>JavaScript Example 2: Variables and function prompt()</title> <script type="text/javascript"> var username; username = prompt("Enter your name: ", ""); if (confirm("Your name is " + username)) { document.write("<p>Hello, " + username + "!</p>"); } else { document.write("<p>Hello, world!</p>");

13</head> 14<body> 15 <p>Welcome to JavaScript!</p> 16</body> 17</html>

Dissecting the Program

1. Line 5 declares a variable called username, via the keyword var. A variable is a named storage location that holds a value. Once the variable is declared, you can assign (and re-assign) a value to that variable, via the assignment operator '=' (Line 6). 2. Line 6 invokes the prompt(string, defaultString) function to pop out a dialog box, and reads in the string entered by the user. The string read is assigned to the variable username. The function prompt() is similar to the alert(), but it accepts a user's input. You can also assign a default value, in this example, an empty string. 3. In Line 7, the confirm(string) function puts up the message and returns either true or false, depending on whether the user hits the OK or Cancel button. 4. If the result is true, Line 8 prints "Hello, username!". Otherwise, Line 10 prints "Hello, world!".

TRY: Instead of printing the greeting message using document.write(), do it via an alert().

3.3 Example 3:
" JSEx3.html "
1<html> 2<head> 3 4 5


Object and Conditional Statement

The following script creates a Date object and prints the current time.

<title>JavaScript Example 3: Date object and Conditional Statement</title> <script type="text/javascript"> var now = new Date(); // current date/time

6 7 8 9 10 11 12 13 14 15 16 17 18

var hrs

= now.getHours();

// 0 to 23

var mins = now.getMinutes(); var secs = now.getSeconds(); document.writeln("<p>It is " + now + "</p>"); document.writeln("<p>Hour is " + hrs + "</p>"); document.writeln("<p>Minute is " + mins + "</p>"); document.writeln("<p>Second is " + secs + "</p>"); if (hrs < 12) { document.writeln("<h2>Good Morning!</h2>"); } else { document.writeln("<h2>Good Afternoon!</h2>"); } </script>

19</head> 20<body></body> 21</html>

Dissecting the Program

Line 5 declares a variable called now. It also creates a Date object (via the new operator), which contains the current date-time stamp, and assign it to now. "//" begins an end-of-line comment (Lines 5 and 6). Comments are ignored by the JavaScript engine but important in explaining your codes to others (and to yourself three days later). Line 6 declares a variable called hrs. It also invokes the function getHours() on object now, in the form of now.getHours(), to retrieve the hour part of object now, and assign it to variable hrs. Lines 7 and 8, similarly, handle the minutes and seconds. Line 9 to 12 use document.writeln() to write to the current document. writeln() (writeline) writes a newline (\n) after the given string. Take note that browser ignores extra white space (newlines, blanks, tabs) in an HTML document; you need to write a <p>...</p> or <br /> tag to ask the browser to display a line break. Lines 13-17 contains a conditional if-then-else statement. Depending on the value of hrs, one of the messages will be displayed.

1. Modify the above script to print the current date, month, year and day of the week. ( Hints: Use functions getDate(), getMonth(), getFullYear() and getDay() of a Date object. getDate() returns 1-31. getMonth() returns 0 to 11 for January to December. getFullYear() returns a 4-digit year. getDay() returns 0 to 6 for Sunday to Saturday). 2. Use a conditional statement to print the day of the week in word (i.e., 0 for Sunday, 1 for Monday and etc.). (Hints: Use the if-elseif-elseif...else construct as follow.)
3. if ( condition-1 ) { 4. statements-1 ;

5. } else if ( condition-2 ) { 6. statements-2 ;

7. } else if ( condition-3 ) { 8. statements-3 ;

9. ..... 10. } else { 11. } statements-n ;

3.4 Example 4: Loop

The following script prompts the user for a multiplier, and prints the multiples of 1 to 100 using a for-loop.

" JSEx4.html "

1<html> 2<head> 3 <title>JavaScript Example 4: Loop</title> 4</head> 5<body> 6 7 8 9 10 11 12 } </script> <h2>Testing Loop</h2> <script type="text/javascript"> var multiplier = prompt("Enter a multiplier: "); for (var number = 1; number <= 100; number++) { document.writeln(number * multiplier);

13</body> 14</html>

Dissecting the Program

Line 8 prompts the user for a number, and assigns it to the variable multiplier. Lines 9-11 contain a for-loop. A for-loop takes the following syntax:
for ( initialization ; test ; post-processing ) { body ;

There are four parts in a for-loop. Three of them, initialization, test and post-processing, are enclosed in brackets () and separated by 2 semi-colons. The body contains the repetitive task to be performed. The initialization statement is first executed. The test is then evaluated. If the test returns true, the body is executed; followed by the post-processing statement. The test is evaluated again and the process repeats until the test returns false. When the test is false, the for-loop completes and program execution continues to the next statement after the for-loop. The following flow chart illustrates the for-loop process: In this example, the variable number is initialized to 1. If number is less than or equal to 100, the body of the loop executes, followed by the post-processing statement, which increment the value of number by 1. The loop repeats until the value of number is NOT less than or equal to 100 (i.e., more than 100).

1. Modify the above script to prompt the user for the multiplier as well as the number of multiples to be printed (in two prompt() statements). 2. Modify the above script to print only multiples that are odd number. ( Hint: The modulo operator "%" can be used to compute the remainder, e.g., x % 2 computes the remainder of x divides by 2, which results in either 0 or 1.)

3.5 Example 5: User-defined Function and onclick

Besides the JavaScript built-in functions such as alert(), prompt(), write(), and writeln(), you can define your own functions. A function has a name and a body consisting of a set of JavaScipt statements that collectively performs a certain task. It may take zero or more argument(s) from the caller and return zero or one value back to the caller.

" JSEx5.html "

1<html> 2<head> 3 4 5 6 7 8 } </script> <title>JavaScript Example 5: User-defined function and Event onclick</title> <script type="text/javascript"> function openNewWindow() { open("JSEx1.html");

9</head> 10<body> 11 12 13 14</body> 15</html> <h2>Example on event and user-defined function</h2> <input type="button" value="Click me to open a new window" onclick="openNewWindow() ">

Dissecting the Program

Lines 5-7 define a function called openNewWindow(), via the keyword function. The function invokes the built-in function open(url), which opens a new browser window (or tab) and loads the page "JSEx1.html". Lines 12-13 create an HTML button. Clicking the button triggers the onclick event handler, i.e., openNewWindow() defined earlier.

TRY: Include another button, which opens "JSEx2.html".

3.6 Example 6: Event Handlers: onload, onunload, onmouseover, onmouseout

JavaScript can be used to handle many types of events, in response to a user's action or browser's action. For example,
onload: fires after browser loaded the page. onunload: fires before the page is removed, e.g. another page is to be loaded, refreshing this

page, or the window is closing. the HTML element.

onmouseover and onmouseout: fires when the user points the mouse pointer at/away from

" JSEx6.html "

1<html> 2<head> 3 4 5 <title>JavaScript Example 6: Events onload and onunload</title> <script type="text/javascript"> var msgLoad = "Hello!";

6 7

var msgUnload = "Bye!"; </script>

8</head> 9<body onload="alert(msgLoad)" onunload="alert(msgUnload)" > 10 11 12 13 <p>"Hello" alert Box appears <em>after</em> the page is loaded.</p> <p onmouseover="this.style.color='red'" onmouseout="this.style.color=''" >Point your mouse pointer here!!!</p> <p>Try closing the window or refreshing the page to activate the "Bye" alert

14box.</p> 15</body> </html>

Dissecting the Program

Line 5 and 6 define two variables, msgLoad and msgUnload, which hold the strings to be displayed in the onload and onunload event handlers. In the <body> start-tag (Line 9), we define the onload and onunload event handlers for the load and unload events. They invoke alert() with the message defined earlier. Line 11 and 12 defines the event handlers onmouseover and onmouseout for the HTML element <p>. The text's color will be changed to red when the user points the mouse pointer at the element (by setting the CSS style property color to red), and revert back to its original color when the mouse pointer is moved away (by resetting the CSS style property color to an empty string). The special keyword this refer to this object.

3.7 Example 6a: Separating HTML, CSS and JavaScript

The previous example works fine. You will find many such example in textbooks, especially the older textbooks. However, it has a big problem. All the HTML contents, CSS presentation styles and JavaScript programming codes are placed in a single file. For a small toy program, the problem is not serious. But when your program grows and if the HTML, CSS and JavaScript are written by different people, you will have a real challenge in maintaining the program. Let's rewrite the example to place the HTML, CSS and JavaScript in three different files.

" JSEx6a.html "

1<html> 2<head> 3 4 5 <title>JavaScript Example 6a: Separating HTML, CSS and JavaScript</title> <link rel="stylesheet" href="JSEx6a.css"> <script type="text/javascript" src="JSEx6a.js"></script>

6</head> 7<body> 8 9 <p>"Hello" alert Box appears <em>after</em> the page is loaded.</p> <p id="magic">Point your mouse pointer here!!!</p>


<p>Try closing the window or refreshing the page to activate the "Bye" alert

11box.</p> 12</body> </html>

" JSEx6a.css "

1.red { 2 3} color:red;

" JSEx6a.js "

1window.onload = function() { 2 3 4} 5 6window.onunload = function() { 7 8} 9 10function init() { 11 12 13 14 15 16 17} } } document.getElementById("magic").onmouseout = function() { this.className = ""; document.getElementById("magic").onmouseover = function() { this.className = "red"; alert("Bye!"); init(); alert("Hello!");

Dissecting the Program

1. Placing the scripting codes inside the HTML page is not a good software engineering practice. Instead, the now-preferred approach is to place the scripts, as well as CSS styles, in external files. 2. Let's begin with the HTML file. Now, the HTML file keeps only the contents, no presentation style and no programming codes. a. <link rel="stylesheet" href="JSEx6a.css"> The CSS style sheet is kept in an external file, refereced via the above <link> tag. b. <script type="text/javascript" src="JSEx6a.js"></script> Also, the JavaScript programming code is kept in an external file, referenced via the above <script> tag.



id="magic">Point your mouse pointer here!!!</p> We provide an unique id to this <p> tag. This id wil be used in the JavaScript to

select this tag. 3. The









color:red; } This define a class-selector called red to display the element with class="red" in color red.

4. In the JavaScript: . window.onload = function() { ... } We attach a so-called inline function as the onload event handler. This function will be invoked after the page is fully loaded. a.
document.getElementById("magic").onmouseover = function() { this.className = "red"; } We use document.getElementById("magic") function to select the <p id="magic"> element. We then attach an inline function as the onmouseover event handler for this <p> element. When the user moves the mouse over this element, this function changes the class attribute to "red". In response, the CSS turns the <p>

element to color red. b.

document.getElementById("magic").onmouseout = function() { this.className = ""; } Similarly, when the user moves the mouse out of the <p id="magic"> element, the event handler changes the class attribute to "". In response, CSS changes the color

to its default.

c. alert("Hello!") This puts up an alert dialog box. d. window.onunload = function() { alert("Bye!"); } Similarly, we attach an inline function as the onunload event handler, which pops up an alert diglog box, before the page is unloaded.

3.8 Example 7: Modifying the Contents of HTML Elements and External Script
You can select HTML element(s) within the current page via these functions: 1. document.getElementById(anId): returns the HTML element with id="anId", or null if the id does not exist. The id attribute should be unique within an HTML document. 2. document.getElementsByName(aName): returns an array of HTML elements with name="aName". Take notes of the plural elements. More than one elements can have the same name attribute. 3. document.getElementsByTagName(aTagName): returns an array of HTML elements with the given HTML tag name. To modify the content of an HTML element, you can assign a new value to the innerHTML property of that element. (The property innerHTML is really useful and is supported in most of the browsers. It is, however, not included in the W3C DOM specification?!)

" JSEx7.html "

1<html> 2<head> 3 4 <title>JavaScript Example 7: Modifying the Content of HTML Elements</title> <script type="text/javascript" src="JSEx7.js" ></script>

5</head> 6<body> 7 8 9 10 11 12 13 14 15 <h1 id="heading1">Heading 1</h1> <h2>Heading 2</h2> <h2>Heading 2</h2> <p name="paragraph">Paragraph 1</p> <p name="paragraph">Paragraph 2</p> <p name="paragraph">Paragraph 3</p> <input type="button" id="btn1" value="Change Heading 1" /> <input type="button" id="btn2" value="Change Heading 2" /> <input type="button" id="btn3" value="Change Paragraph" />

16</body> 17</html>

" JSEx7.js "

1window.onload = init; 2 3function init() { 4 5 6 7} 8 9function changeHeading1() { 10 11} 12 13function changeHeading2() { 14 15 16 17 18} 19 } var elms = document.getElementsByTagName("h2"); for (var i = 0; i < elms.length; i++) { elms[i].innerHTML = "Hello again!"; document.getElementById("heading1").innerHTML = "Hello"; document.getElementById("btn1").onclick = changeHeading1; document.getElementById("btn2").onclick = changeHeading2; document.getElementById("btn3").onclick = changeParagraph;

20function changeParagraph() { 21 22 23 24 25} } var elms = document.getElementsByName("paragraph"); for (var i = 0; i < elms.length; i++) { elms[i].innerHTML = "Hello again and again!";

Dissecting the Program

1. In this example, instead of placing the scripts inside the HTML document, we place the JavaScript in a separate file called "JSEx7.js" and referenced this file in the HTML page via <script src="JSEx7.js">. The external script file shall have the file extension of ".js". External Script is recommended as it separates the HTML content and the programming script (called unobstructive scripting), for ease of maintenance (just like HTML content and CSS presentation should be separated). You can also use the same script in many HTML pages. 2. This HTML document contains a <h1> element with an unique id="heading1" (Line 7), two <h2> elements (Line 8-9), three <p> elements with name="paragraph" (Line 10-12), and three <input type="button"> with unique id (Line 13-15). 3. In the user-defined function changeHeading1(), we use document.getElementById("heading1") to select the <h1> element, and then modify its innerHTML property.

4. In changeHeading2() function, we use document.getElementsByTagName("h2") to select all the <h2> elements in an array elms. We then use a for-loop to iterate thru all the elements in the array. The elms.length property keeps the length of the array. 5. In changeParagraph() function, we use document.getElementsByName("paragraph") to select all the <p> elements. 6. The page contains three buttons to trigger the functions defined (Line 13-15). 7. The script also contain a function init(), which is assigned as the onload handler via window.onload=init. That is, init() will be triggered after the page is loaded. The init() function assigns onclick event handlers to the buttons, selected via document.getElementById(). 8. Take note that there is no script code in the HTML page, except reference to the external script file.


3.9 Example 8: Intercepting an Hyperlink

This example uses a script to intercept an hyperlink to put up a warning message, but proceeding to the link.

" JSEx8.html "


2<head> 3 4 <title>JavaScript Example 8: Intercept an Hyperlink</title> <script type="text/javascript" src="JSEx8.js" ></script>

5</head> 6<body> 7 <a href="JSEx1.html" id="linkEx">JavaScript Example 1</a> 8</body> 9</html>

" JSEx8.js "

1window.onload = init; 2 3function init() { 4 5} 6 7function showWarning() { 8 9} return confirm("Warning! Proceed with care!"); document.getElementById("linkEx").onclick = showWarning;

Dissecting the Program

1. The HTML page has an hyperlink <a> with an unique id. 2. The init() function assigns an onclick handler to the hyperlink, selected via document.getElementById().. 3. When the hyperlink is clicked, the onclick handler showWarning() triggered. If confirm() returns true, the new page will be loaded; otherwise, the current page remains.


3.10 More Advanced JavaScript Examples

More "Advanced JavaScript Examples".

4. Writing and Debugging JavaScripts

A good graphic debugger is a MUST for programming in any language. Programming in JavaScript, in particular, requires a graphic debugger. It is because JavaScripts are interpreted and does not need to be compiled. Hence, there is no compiler to show you the syntax errors. A simple and trivial syntax error (e.g., missing bracket, mis-spelling) will render the entire script not workable. Worst still, most of the times, you cannot see any error message when the script does not work (unless you enable the error console). Can you debug without any error message or clue? Without a graphic debugging, the only mean to debug JavaScript is to insert alert() at strategic locations to print out selected data.

In addtion, a good IDE with content-assist (auto-complete) feature, which provide a list of possible options, would be a great help. After modifying a JavaScript, I recommend that you use Ctrl-F5 to refresh the page, which shall load a fresh copy instead of loading from the cache. You might need to clear the browser's cache or restart the browser, if you modification does not take effect.

4.1 Firefox: Firebug add-on for Firefox - ESSENTIAL

Simply GREAT and MUST HAVE!!! You can install firebug from http://getfirebug.com/. It provides these features: 1. Console: View the JavaScipt error messages. Start the firebug and switch to the "Console" panel. 2. Script: View and debug JavaScipt. Start the firebug. Switch to the "Script" panel. "Enable" or "Reload" if necessary. You can set a breakpoint by clicking on the statement number, single step thru the JavaScript statements, watch the expression, and etc. Read "JavaScript Debugger and Profiler". 3. DOM: View the HTML DOM of the current document. 4. HTML and CSS. Notes: If you get the error "Script Panel was inactive during page load" when swiching into the "script" panel, you need to disable "private browsing" in Firefox's Tools Options Privacy.

4.2 Other Browsers' add-on

Safari: Web Inspector Google Chrome: Developer Tools IE: Internet Explorer Developer Tools Opera: Dragonfly

4.3 Aptana Studio

An open source IDE (based on Eclipse), which supports JavaScript and Ajax.

4.4 NetBeans
You can write JavaScripts by creating a web application under Netbeans (Read "Developing web application under NetBeans"), via new Others In "Categories", select "Other" In "File Types", select "HTML File" or "JavaScript File". NetBeans provides content-assist (aka auto-complete) feature, which greatly improves your productivity. Read "JavaScript Debugger User's Guide" @ http://netbeans.org/kb/67/web/js-debugger-ug.html. But it is no longer available for Netbeans 7.0.1. Use firebug instead.

4.5 Eclipse

5. JavaScript & HTML

As seen from the previous examples, JavaScripts are embedded inside an HTML document, and executed by the browser. There are two occasions on which browser executes JavaScript instructions: 1. JavaScripts enclosed between <script> and </script> runs when the the page is loading. 2. Some JavaScripts run as a result of the user's or browser's action. For example, clicking a button (onclick) or loaded a page (onload). There are, therefore, two places to put your JavaScript: 1. between <script> and </script> container tags; and 2. inside the HTML tags as the event handlers (such as onclick, onmouseover, onload), e.g., onclick="JavaScriptStatements".

5.1 The



The <script>...</script> tags contains the JavaScript programming statements. The attribute type="text/javascript" identifies the scripting language (Older scripts may use Language="JavaScript". Both type and language are not needed in HTML 5). For example,
<script type="text/javascript"> ... Your JavaScript statements here ... </script>

It is a old practice (old and legacy practice?!) to enclose the JavaScript statements by an HTML comments, so that browsers that do not support JavaScript will treat them as comments and will not try to parse and display them. This is really not needed today, as all browsers support JavaScript. For example,
<script type="text/javascript"> <!-... Your JavaScript statements here ... // --> </script>




<body> ?

You can place your JavaScript in either the HEAD section (called Header Script) or BODY section (called Body Script) of an HTML document. Typically, global variables and function definitions are placed in HEAD section, which will always be loaded and available to be used by the scripts in the BODY section. Remember that the HEAD section is loaded before the BODY section. In short, HEAD section is preferred.

5.3 External JavaScript

The now-perferred approach is to keep the JavaScript in an external file with file extension of " .js", and reference it via the scr (source) attribute as follows:
<script type="text/javascript" scr=" JavaScriptFilename.js"></script>

Note: You always need the end-tag </script>. The standalone tag <script ... /> does not work?! The original method of scripting is to place the JavaScript in the HEAD section of the HTML document. But the now-preferred method separate the HTML contents, CSS presentation styles, and JavaScript programming codes in three separate files. You can share the script among many HTML pages, and it is much more easier to maintain.

5.4 The



The <noscript>...</noscript> tags provide an alternate message if scripting is disabled or not supported.

6. JavaScript Basic Syntax

6.1 Comment
Comments are ignored by the JavaScript runtime but greatly useful in explaining your codes to others (and also to yourself three days later). You should use comments liberally to explain or document your codes. A end-of-line comment begins with // and lasts till the end of the current line. A multi-line comment begins with /* and lasts till */. Recall that HTML comments are enclosed inside <!-- and -->.

6.2 Expression
An expression is a combination of variables, literals, operators, and sub-expressions that can be evaluated to produce a single value.

6.3 Statement & Block

A statement is a single instruction consisting of operators, variables and expression. It is strongly recommended to end each statement with a semi-colon (;) (although it is not strictly necessary as the new-line can also serve as the statement terminator in JavaScript). A block consists of zero or more statements enclosed in a pair of curly braces { ... }. No semicolon is needed after the closing brace.

6.4 Variables, Literals & Types

Variables & Assignment Operator '='
A variable is a named storage location that holds a value, e.g., sum, average, name, message. A variable name (aka identifier) consists of letters (a-z, A-Z), digits (0-9), underscore (_); and must begin with a letter or underscore. JavaScript is case sensitive. A ROSE is not a rose and is not a Rose. A variable is declared using keyword var.

You can assign (and re-assign) a value to a variable using the assignment '=' operator.

A literal is a fixed value, e.g., 5566, 3.14, "Hello", true, that can be assigned to a variable or form part of an expression.

JavaScript supports the following primitive types:
String: contains texts. Strings literals are enclosed in a pair of single quotes or double quotes (e.g., "Hello", 'world'). Number: takes an integer (e.g., 5566) or a floating-point number (e.g., 3.14159265). Boolean: takes literal value of either true or false. undefined: takes a special literal value called undefined.

JavaScript is object-oriented and supports the Object type and null. Furthermore, function is also a type in JavaScript. These types will be discussed later. Unlike most of the general programming languages (such as Java, C/C++ and C#) which are strongly type, JavaScript is loosely type (similar to most of the scripting languages such as UNIX Shell Script and Perl). You do not have to explicitly declare the type of a variable (e.g., int, float, string) during declaration. The type is decided when a value is assigned to that variable. If a number is assigned, the variable takes Number type and can perform numeric operations such as addition and subtraction. If a string is assigned, the variable takes String type and can perform string operating such as string concatenation. When a variable is declared without assigning an initial value, it takes the type undefined and holds a special value called undefined (uninitialized is probably more precise?!), As soon as a value is assigned, the variable takes on the type of that value. The act of putting a value into a variable sets its type. You can change the type of a variable by re-assigning a value of another type. Types are converted automatically as needed during execution (known as dynamically-typed).

Operator " typeof "

You can use the operator typeof to check the type of a variable.

var magic; // Declare a variable

document.writeln("<p>Type is " + typeof magic + ", Type is undefined, value=undefined value=" + magic + "</p>"); magic = 55; // Assign an integer Type is number, value=55

document.writeln("<p>Type is " + typeof magic + ", Result=18.333333333333332 value=" + magic + "</p>"); document.writeln("<p>Result=" + (magic / 3) + "</p>"); // Arithmetic operation Type is number, value=55.66

magic = 55.66;

// Assign a floating-point number Result=NaN // String 'Hello' converts to NaN (Not-A-Number) Type is string, value=3.14 Result=1.0466666666666666 // String '3.14' converts to number 3.14 // This is also a string

document.writeln("<p>Type is " + typeof magic + ", Type is string, value=Hello value=" + magic + "</p>"); magic = 'Hello'; // Assign a string document.writeln("<p>Type is " + typeof magic + ", value=" + magic + "</p>"); document.writeln("<p>Result=" + (magic / 3) + "</p>"); magic = "3.14";

document.writeln("<p>Type is " + typeof magic + ", Type is boolean, value=false value=" + magic + "</p>"); document.writeln("<p>Result=" + (magic / 3) + "</p>"); magic = false; // Assign a boolean Type is object

document.writeln("<p>Type is " + typeof magic + ", value=" + magic + "</p>"); magic = new Date(); discussed later) document.writeln("<p>Type is " + typeof magic + "</p>"); // object // Assign an object (to be

You can create a read-only, named constant with the keyword const (in place of var). For example,
const SIZE = 9;

Unfortunately, IE does not support this keyword?! So don't use.

6.5 " Number " Type, Literals & Operations

A variable of type Number holds a number, either an integer (e.g., 5566), or a floating-point number (e.g., 3.1416). Integer literals can be expressed in decimal (begins with a digit 1 to 9), octal (begins with a digit 0, e.g., 0123) or hexadecimal (begins with 0x, e.g., 0xA1B2). Floating-point literals can be expressed in scientific notation (e.g., 1.23e4, 4.56e-7). JavaScript also provides some special Number literals such as infinity (e.g., 1/0), -infinity (e.g., -1/0), NaN (Not-A-Number, e.g., 0/0, or converting the string 'Hello' to a number).

Arithmetic Operations

Arithmetic operations, as tabulated below, can be applied to numbers. The following results are obtained assuming that x=5, y=2 before the operation.

+ * / % ++

Addition Subtraction (or Unary Negation) Multiplication Division Modulus (Division Remainder) Unary Pre- or PostIncrement Unary Pre- or PostDecrement

Example ( x=5, y=2)

z = x + y; z = x - y; z = x * y; z = x / y; z = x % y; y = x++; z = ++x; Same as: y = x; x = x+1; x = x+1; z = x; y = --x; z = x--; Same as: x = x-1; y = x; z = x; x = x-1;

z is 7 z is 3 z is 10 z is 2.5 z is 1 y is 5; z is 7; x is 7 y is 4; z is 4; x is 3


In JavaScript, arithmetic operations are always performed in double-precision floating-point. That is, 1/2 gives 0.5 (instead of 0 in Java/C/C++). You may use the built-in function parseInt() to truncate a floating-point value to an integer, e.g., parseInt(55.66) and parseInt("55.66") gives 55. You may also use the built-in mathematical functions such as Math.round(), Math.floor(), Math.ceil() for converting a floating-point number to an integer.

Arithmetic cum Assignment Operators

These are short-hand operators to combine two operations.

+= -= *= /= %=

Addition cum Assignment Subtraction cum Assignment Multiplication cum Assignment Division cum Assignment Modulus cum Assignment

x += y; x -= y; x *= y; x /= y; x %= y;

Same as: x = x + y; Same as: x = x - y; Same as: x = x * y; Same as: x = x / y; Same as: x = x % y;

6.6 " String " Type, Literals & Operations

A variable of the type String hold a sequence of text characters. A string literal is texts delineated by single quotes or double quotes (e.g., "Hello", 'world', "5566", '3.1416'). You can use an escape sequence to represent special characters (such as \n for new-line, \t for tab, and \uhhhh for Unicode character); and to resolve conflict (e.g., \", \', \\).

JavaScript is dynamically-type, and performs type conversion automatically. When a String value is used in arithmetic operations (such as subtraction or multiplication), JavaScript runtime automatically converts the String to a Number if it represents a valid Number, or a special Number called NaN (NotA-Number) otherwise. For example,
// In arithmetic operation (except addition), strings are converted to number (or NaN) var magic; magic = "55" - "66"; magic = "55" * 2; magic = "Hello" - 1; // gives number -11 (subtraction) // gives number 110 (multiplication) // gives number NaN (subtraction failed)

Operator '+'
If both the operands to a '+' operator are Numbers, it performs the usual addition. However, if one of the operand is a String, the '+' operator is overloaded to perform string concatenation. The other operand will be converted to a String if necessary. For example,
// '+' operator is overloaded to perform string concatenation if one of the operands is a string alert(11 + 22); alert("11" + "22"); alert("11" + 22); alert("Hello" + 22); // gives Number 33 (usual addition) // gives string 1122 (concatenation) // gives string 1122 (concatenation) // gives string Hello22 (concatenation)

Built-in Functions parseInt() and parseFloat()

To convert a numeric String to a Number, you could use the built-in function parseInt() or parseFloat(), which returns a Number if conversion is sucessful, or NaN otherwise. For example,
var magic = "11"; alert(magic + 22); // String // String "1122" // Number 33

alert(parseInt(magic) + 22);

alert(parseInt(magic) + "22"); // String "1122" alert(parseInt(magic) + parseFloat("22.33")); alert(parseInt("abc")); // NaN // Number 33.33

6.7 " Boolean " Type, Literals & Operations

A variable of the type Boolean holds a value of either true of false. true and false are keywords in JavaScript. As mentioned, JavaScript performs automatic type conversion if necessary. During the type conversion, the following values are converted to false: number 0, empty string ("", ''), NaN, null, and undefined. All the other values are converted to true.

Comparison Operators
The following relational operators, which produce a boolean result, are defined in JavaScript. The results are obtained assuming num=8, str='8'.


Equal To

num == 8 str == '8' num == str 8 == '8' num == 8 str == '8' num == str 8 == '8'

true true true true true true false false

!= ===

Not Equal To Strictly Equal To (in Type and Value) Strictly Not Equal To Greater Than Greater Than or Equal To Less Than Less Than or Equal To

!== > >= < <=

Comparison can be applied to two numbers, a number and a string, or two strings: When a number is compared with a string, the string is converted to a number (or NaN if it does not contain a valid number). Hence, (8 == "8") returns true. A strict equal-to operator (===) is introduced in JavaScript, which compares both the value and the type. Hence, (8 === "8") returns false. When two strings are compared, the alphabetic order (ASCII code table) is used. Hence, string "8" is alphabetically greater than string "10".
===, !==, ==, != can be applied to boolean too, e.g., ("" == false) gives true (because empty string is converted to false); but ("" === false) gives true.

<script type="text/javascript">

// Comparing numbers var x = 8; document.writeln(x == 8); document.writeln(x == "8"); document.writeln(x === 8); // true (same value) // true (string converted to number) // true (same type and value)

document.writeln(x === "8"); // false (different type)

document.writeln(x < 10); document.writeln(x < "10");

// true // true (string converted to number)

// Comparing two strings document.writeln("8" < "10"); document.writeln("8" < "9"); // false (comparing two strings alphabetically) // true (comparing two strings, not numbers)

document.writeln("Hello" < "hi"); // true (comparing two strings) </script>

Logical Operators
The following boolean (or logical) operators are provided in JavaScript:

&& || !

Logical AND Logical OR Logical NOT



Evaluation of logical operations are always short-circuited. That is, the operation is terminated as soon as the result is certain, e.g., (false && ...) is short-circuited to give false, (true || ...) gives true, the ... will not be evaluated.

6.8 Explicit Type Conversion

The JavaScript runtime performs type conversion automatically. However, at times, you may need to convert from one type to another explicitly.

Convert a Number to a String : Simply concatenate the number with an empty-string, e.g., "" +
5 gives "5".


String to a Number : Use built-in functions parseInt(string) and parseFloat(string) to convert a string which contains a valid number. For example,

parseInt("55") gives 55, parseInt(55.66) gives 55, parseInt("55.66") parseFloat("55.66") gives 55.66, but parseInt("Hello") gives NaN.



Convert a float to an integer : Use parseInt(), e.g., parseInt(55.66) gives 55, or built-in
mathematical functions such as Math.round(), Math.ceil() or Math.floor().

6.9 Scope of a Variable

When a variable is declared inside a function or block, it is a local variable and its scope is within the function or block. When a variable is declared outside functions, it is a global variable and is available to all the codes in the current document.

6.10 Flow Control

JavaScript provides these flow control construct. The syntax is the same as Java/C/C++.

if (condition) { trueBlock; } if (condition) { trueBlock; } else { falseBlock; } variable = (condition) ? trueValue : falseValue; Same as if (condition) { variable = trueValue; } else { variable = falseValue; } if (condition1) { block1; } elseif (condition2) { block2; } elseif (...) { ...... } else { elseBlock; } switch (expression) { case value1: statements; break; case value2: statements; break; ...... ...... default: statements; }

if (day == 'sat' || day == 'sun') { alert('Super weekend!'); } if (day == 'sat' || day == 'sun') { alert('Super weekend!'); } else { alert('It is a weekday...'); } var max = (a > b) ? a : b; var abs = (a >= 0) ? a : -a;

if (day == 'sat' || day == 'sun') { alert('Super weekend!'); } else if (day == 'fri') { alert("Thank God, it's friday!"); } else { alert('It is a weekday...'); } switch (day) { case 'sat': case 'sun': alert('Super weekend!'); break; case 'mon': case 'tue': case 'wed': case 'thu': alert('It is a weekday...'); break; case 'fri': alert("Thank God, it's friday"); break; default: alert("You are on earth?! Aren't you?"); }

6.11 Loops
JavaScript provides the following loop constructs. The syntax is the same as Java/C/C++.

while (test) { trueBlock; } do { trueBlock; } while (test); for (initialization; test; post-processing) { trueBlock; }

var sum = 0, number = 1; while (number <= 100) { sum += number; } var sum = 0; number = 1; do { sum += number; } var sum = 0; for (var number = 1; number <= 100; number++) { sum += number; }

The following loop-control statements are provided (same syntax as Java/C/C++):

break: exit the innermost loop.

continue: abort the current iteration, and continue to the next iteration. label: provide an identifier for a statement, which can be used by break and continue.

6.12 Functions
Functions are useful: when you have to use the same codes several times. as the JavaScript event handler. make your program easier to read and understood. A function accepts zero or more arguments from the caller, performs the operations defined in the body, and returns zero or a single result to the caller. The syntax for user-defined function is:
function functionName(argument1, argument2, ...) { statements; ...... return value; ...... }

Functions are declared using the keyword function. You do not have to specify the return-type and the types of the arguments because JavaScript is loosely typed. You can use a return statement to return a single piece of result to the caller anywhere inside the function body. If no return statement is used (or a return with no value), JavaScript returns undefined. Functions are generally defined in the HEAD section, so that it is always loaded before being invoked. To invoke a function, use functionName(argument1, argument2, ...). Example:
<html> <head> <title>Function Demo</title> <script type="text/javascript"> function add(item1, item2) { // Take two numbers or strings

return parseInt(item1) + parseInt(item2); // Simply item1 + item2 won't work for strings } </script>

</head> <body> <script type="text/javascript"> var number1 = prompt('Enter the first integer:'); // returns a string

var number2 = prompt('Enter the second integer:'); // returns a string alert('The sum is ' + add(number1, number2)); </script> </body> </html>

Function has access to an additional variable called arguments inside its body, which is an array (to be discussed in full later) containing all the arguments. For example,
<html> <head> <title>Function Demo</title> <script type="text/javascript"> function add() { var sum = 0; for (var i = 0; i < arguments.length; i++) { sum += parseFloat(arguments[i]); } return sum; } </script> </head> <body> <script type="text/javascript"> document.write(add(1, 2, 3, 4, 5) + "<br \>"); document.write(add(1, 2) + "<br \>"); document.write(add(1.1, "2.2") + "<br \>");

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

Primitive arguments are passed by value. That is, a copy of the variable is made and passed into the function.

6.13 Interacting with Users

JavaScript provides these built-in top-level functions for interacting with the user:
alert(string): Pop-up a box to alert user for important information. The user will have to click "OK" to proceed. alert() returns nothing (or undefined). prompt(string, defaultValue): Pop-up a box to prompt user for input, with an optional defaultValue. prompt() returns the user's input as a string. For example, var number1 = prompt('Enter the first integer:'); var number2 = prompt('Enter the second integer:'); alert('The sum is ' + number1 + number2); two strings alert('The sum is ' + (parseInt(number1) + parseInt(number2))); // Add two numbers confirm(string): Pop-up a box and ask user to confirm some information. The user will have to click on "OK" or "Cancel" to proceed. confirm() which returns a boolean value. For // Concatenate

var isFriday = confirm("Is it friday?"); if (isFriday) { alert("Thank God, it's Friday!"); } else { alert('Not a Friday'); } document.write(string) and document.writeln(string): Write the specified string to the current document. writeln() (write-line) writes a newline after the string, while write() // Returns a boolean

does not. Take note that browser ignores extra white spaces (blanks, tabs, newlines) in an HTML document, and treat multiple white spaces as a single blank character. You need to write a <br /> or <p>...</p> tag to ask the browser to display a line break.

6.14 Other Top-level Built-in Functions

JavaScript also pre-defines the following top-level global functions.
parseInt(string), parseFloat(string): parses the given string and returns the numeric value or NaN (Not-A-Number). parseInt(str, radix) accepts an optional radix (or base).

For example,
parseInt("88"); parseInt("88.99"); parseInt("Hello"); // gives number 88 // gives number 88 // gives NaN (Not-A-Number)

parseFloat("88.99"); // gives number 88.99 parseFloat('Hi'); // gives NaN

isFinite(number): returns true if number is not NaN, Infinity or -Infinity. isNaN(number): returns true if number is NaN. Useful for checking the output of parseInt() and parseFloat(). eval(codes): evaluate the given JavaScript codes, which could be an expression or a

sequence of statements.
encodeURI(), decodeURI(), encodeURIComponent(), decodeURIComponent(): encode or decode name-value pairs for the HTTP request, by replacing special characters with %xx.

6.15 An Introduction to Events

JavaScript are often event-driven. That is, a piece of codes (called event handler) fires in response to a certain user's or browser's action, which generates an event. The commonly-used events are:
click: generated when the user clicks on an HTML element. mouseover, mouseout: generated when the user positions the mouse pointer inside/away

from the HTML element.

load, unload: generated after the browser loaded a document, and before the next

document is loaded, respectively.

The event handler, called oneventname (such as onclick, onmousemove, onload), is the codes that responses to an event. The event handler is typically attached to the target HTML tag, e.g.,
<html> <head> <title>Event Demo</title> <script type="text/javascript"> function say(message) {

alert(message); } </script> </head> <body> <h2 onmouseover="this.style.color='red'" onmouseout="this.style.color=''" >Hello</h2> <input type="button" value="click me to say Hello" onclick="say('Hello')"> <p onclick="say('Hi')">This paragraph can say Hi...</p> </body> </html>

More about events in the later sections.

7. Objects
JavaScript is object-oriented. It, however, does not support all the OO features, so as to keep the language simple. JavaScript's OO is prototype-based, instead of class-based. A class-based OO language (such as Java/C++/C#) is founded on concepts of class and instance. A class is a blue-print or prototype of things of the same kind. An instance is a particular realization (instantiation, member) of a class. For example, "Student" is a class; and "Tan Ah Teck" is an instance of the "Student" class. In a class-based OO language, you must first write a class definition, before you can create instances based on the class definition. A prototype-based OO language (such as JavaScript) simply has objects (or instances). It uses a prototype as a template to get the initial properties of a new object. In JavaScript, you do not have to define a class explicitly. Instead, you define a constructor method to create objects (or instances) with a set of initial properties. Furthermore, you can add or remove properties of an object at runtime, which is not permitted in class-based OO languages.

7.1 Properties and Methods

An object is a collection of properties and methods under a common name: Properties (also called variables, attributes): contains values associated with the object. Methods (also called operations, functions): contains actions that the object can perform. For example, a Car object has properties such as make, price, capacity; and methods such as startEngine(), move(), brake(), stopEngine().

7.2 The dot operator

Recall that an object is collection of properties and methods, under a common name. You can use the dot (.) operator to access an underlying property or invoke a method for a particular object, in the form of anObjectName.aPropertyName, or anObjectName.aMethodName(arguments).

7.3 Constructor & the " new " Operator

A constructor is a special method that is used to create and initialize an object. You can invoke the constructor with the operator "new" to create a new object. For example, JavaScript provide a built-in object called Date, having a constructor method called Date(), you can invoke the Date() constructor to create new Date instance as follows:
var now = new Date(); Date() now.getMonth(); now.setYear(8888); // Invoke getMonth() method for the Date object now. // Invoke setMonth() method for the Date object now. // Create a new object called now by calling constructor

8. Built-in JavaScript Objects

JavaScript provides many useful global objects, such as Array, Date, String, and Number. I shall discuss some commonly used objects here. For detailed specification and examples about a built-in object, check "Core JavaScript References".

8.1 Common Properties and Methods for all JavaScript objects

Recall that an object is a collection of properties and methods. The following methods are available to all JavaScript objects:
anObjectName.toString(): returns a string description about this object. anObjectName.valueOf(): converts this object to a primitive value such as number.




An array can be used to store a list of items under a single name. You can reference individual item via an index number in the form of anArrayName[index]. You can conveniently process all the elements in an array collectively via a loop. JavaScript does not have an explicit array type. Instead, a built-in Array object is provided. You can create an Array object in two ways: 1. Invoke the Array constructor with new operator, e.g.,
2. // (1) Create an Array object given the length of the array 3. var fruits = new Array(3); 4. fruits[0] 5. fruits[1] = "apple"; = "orange";

6. fruits[2]

= "banana"; // 3

7. document.write(fruits.length); 8.

9. // (2) Create an Array object and initialize the array 10. var days = new Array("sun", "mon", "tue", "wed", "thu", "fri", "sat"); 11. document.write(days[0]); document.write(days.length); // "sun" // 7

12. Assign directly to an array literal, in the form of [value1, value2, ...]
13. var anotherDays = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]; document.write(anotherDays.length); // 7

You can access individual element of an array via an index number, in the form of anArrayName[index]. The index of the array begins at 0. You can use the built-in property length to retrieve the length of the array. Array is usually processed collectively using a loop, e.g.,
var days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; document.write("<p>" + days[0]); for (var i = 1; i < days.length; i++) { document.write(" | " + days[i]); } document.write("</p>"); // <p>sun | mon | tue | wed | thu | fri | sat</p>

Array's Length
The JavaScript array's size is dynamically allocated. You can add more elements to an array. You can also remove the content of an element using keyword delete. The element becomes undefined. For example,
var days = ["sun", "mon", "tue"]; document.writeln(days.length); document.writeln(days); days[5] = "fri"; // 3 // sun,mon,tue // Dynamically add an element

document.writeln(days.length); document.writeln(days); undefined) delete days[2]; document.writeln(days.length); document.writeln(days); days[days.length] = "sat"; document.writeln(days); for..in loop

// 6 // sun,mon,tue,,,fri (elements in between are

// Remove the content of an element // 6 // sun,mon,,,,fri // Append at the end // sun,mon,,,,fri,sat

JavaScript provides a special for..in loop to process all the elements in an array. The syntax is as follows, where index takes on the each of the index number of element which are not undefined.
for (var index in arrayName) { ... }

For example,
var months = ["jan", "feb"]; months[11] = "dec"; for (var i in months) { document.writeln(index + ":" + months[i] + ", "); } // 0:jan, 1:feb, 11:dec,

Array's Properties and methods

The Array object has these commonly-used properties:
length: number of items.

It has these commonly-used methods:

join(separator): join the elements of an array together into a single string, separated by the separator (defaulted to ","). For example, var fruits = ["apple", "orange", "banana"]; fruits.join(); fruits.join("|"); // Create an array object

// gives "apple,orange,banana" // gives "apple|orange|banana"

concat(value1, value2, ..., valueN): returns a new array composing of this array and

the given arrays or values.

reverse(): reverses the order of elements in the array, the first becomes last. sort(): sorts the elements in the array. push(): adds one or more elements to the end of an array and returns the last element


pop(): removes and return the last element from an array. shift(): removes and returns the first element from an array. unshift(): adds one or more elements to the front of an array and returns the resultant

length of the array.

splice(): adds and/or removes elements from an array. slice(): extracts and returns a section of an array (sub-array).

Important: For detailed specification and examples about a built-in object, check "Core JavaScript References". Example: [TODO]




A string can be created in two ways: 1. directly assigned a string literal in the form of "..." or '...'. 2. invoke the String object constructor via the operator new, i.e., new String(content). For example,
var str1 = 'Hello'; document.writeln(typeof str1); var str2 = new String('Hello'); document.writeln(typeof str2); // Assign a string literal // Type is string (primitive) // String object constructor // Type is object

The former is called a string literal, while the later constructs a String object. String object is a wrapper for primitive string, which provides many useful methods for manipulating strings. Commonly-used properties:
length: the number of characters in the string.

Commonly-used methods:
indexOf(aChar, fromIndex): returns the index of the character aChar, starting from index fromIndex. The first character has index of 0. charAt(index): returns the character at the index position. substring(beginIndex, endIndex): returns the substring from beginIndex to endIndex


lastIndexOf(aChar, fromIndex): scans backward.

split(delimiter): returns an array by splitting the string using delimiter. toUpperCae(), toLowerCase(): returns the uppercase/lowercase string.

These methods correspond to an HTML tag:

anchor(aName), link(url): turns the string into HTML anchor tag <a name="aName"> or <a href="url">. big(), small(), strike(), blink(), bold(), italics(), fixed(), sub(), sup(): same as the

corresponding HTML tag.




Number object is a wrapper object for primitive number, which provides many properties and





Boolean object is a Wrapper object for primitive boolean, which provides many properties and





Commonly-used constructors:
new Date(): constructs a Date object with the current date and time. new Date("Month, day, year hours:minutes:seconds") : constructs a Date object with

the the given time string.

new Date(year, Month, day): where month is 0-11 for Jan to Dec. new Date(year, Month, day, hours, minutes, seconds)

Commonly-used methods:
getDate(), setDate(), getMonth(), setMonth(), getFullYear(), setFullYear(): get/set

the date (1-31), month (0-11 for Jan to Dec), year (4-digit year).

getDay(): get the day of the week (0-6 for Sunday to Saturday). getHours(), setHours(), getMinutes(), setMinutes(), getSeconds(), setSeconds():

get/set the hours/minutes/seconds.

getTime(), setTime(): get/set the number of milliseconds since January 1, 1970, 00:00:00.




Commonly-used properties:
E, PI: Eulers constant and PI. LN2, LN10, LOG2E, LOG10E: ln(2), ln(10), log2(e), log10(e). SQRT2, SORT1_2: square root of 2 and half.

Commonly-used methods:

sin(a), cos(a), tan(a), asin(x), acos(x), atan(x), atan2(x,y) cell(x), floor(x), round(x) exp(x), log(x), pow(base,exp), sqrt(x) max(x,y), min(x,y) random(): returns a pseudo-random number between 0 and 1.




Every function in JavaScript is actually a Function object. A variable can be assigned a Function object, which will take the type function. For example,
function sayHello() { return "Hello"; } document.writeln(sayHello()); document.writeln(typeof sayHello); // Define a 'named' function // Invoke function with function name // Type is function

var magic = sayHello;

// Assign to a function object (without parentheses)

document.writeln(typeof magic); // Type is function document.writeln(magic()); // Invoke function

You can define a inline (anonymous) function and assign it to a variable as follows:
var magic = function() { return "Hello" };

Besides using function keyword, you can also use the Function constructor (with new operator) to define a Function object (which is not easily understood and not recommended).
magic = new Function("arg1", "arg2", "return arg1 + arg2"); document.writeln(magic(55, 66)); document.writeln(typeof magic); // Type function

// same as function magic(arg1, arg2) { return arg1 + arg2; } document.writeln(magic(55, 66));

The syntax for Function constructor is:

functionName = new Function("argument1", "argument2", ..., "functionBody");

9. Defining Your Own Objects

There are two ways to define and create your own objects: 1. define a constructor (called procedural approach) 2. via an object initializer (i.e., assigned a object literal).

9.1 Creating new objects via Constructor and " new " operator
You can create your own objects by defining a constructor, and invoke the constructor with the new operator to create a new object.

Keyword " this "

"this" refers to the current object. this.propertyName and this.methodName() refer the property and method of this object.

Let us define a constructor for a Circle object, with two properties radius and dateCreated, and two methods getArea() and toString() in "Circle.js". We shall then use the "CircleTest.js" and "CircleTest.html" to test the Circle object defined.

" Circle.js "

1// Define a constructor for the Circle object, 2// 3// 5 6 7 8 9 10 11} 12 13// Define the method getArea(). 14function getArea() { 15 16} 17 18// Define the method circleDescription(). 19function circleDescription() { 20 21 return "Circle with radius=" + this.radius + " created on " + this.dateCreated; return this.radius * this.radius * Math.PI; with properties radius and dateCreated, and methods getArea() and toString(). // Properties this.radius = radius || 1; this.dateCreated = new Date(); // Methods this.getArea = getArea; // Assigned a function object this.toString = circleDescription; // Assigned a function object // Default is 1 // Assigned an object

4function Circle(radius) {


" CircleTest.js "

1// Create two Circle objects 2var circle1 = new Circle(1.5); 3var circle2 = new Circle(2.6); 4 5// Invoke methods using dot operator. 6document.writeln("<p>" + circle1 + ", Area=" + circle1.getArea() + "</p>"); 7document.writeln("<p>" + circle2 + ", Area=" + circle2.getArea() + "</p>");

" CircleTest.html "

1<html> 2<head> 3 4 5 <title>Creating our own objects</title> <script type="text/javascript" src="Circle.js"></script> <script type="text/javascript" src="CircleTest.js"></script>

6</head> 7<body></body> 8</html>

Dissenting the Program

1. Properties are declared inside the constructor via this.propertyName, which can then be initialized. 2. Methods can be declared inside the constructor via this.methodName. There are a few ways to provide the method's definition: a. Define an ordinary function, and assign the functionName (without parentheses, which is a function type) to this.methodName, as in the above example. b. Assign this.methodName to an inline function, e.g.

this.getArea = function() { return this.radius * this.radius * Math.PI; };


Invoke the Function constructor with new operator:

= new Function("return this.radius * this.radius *

this.getArea Math.PI");

3. To invoke a method, use anObjectName.aMethodName(arguments). The parentheses is necessary even there is no augment.

4. The toString() is a special method, which returns a string description of this object. toString() will be implicitly invoked if an object is passed into the write(), writeln(), or '+' operator. In other words, document.write(circle1) is the same as document.write(circle1.toString()). All the JavaScript built-in objects has a toString() method.

9.2 Creating objects via Object Initializer

You can create a new object by directly assign an object literal (called Object Initializer) to a variable. The syntax is as follows:
objectName = {propertyOrMethod1:value1, propertyOrMethod2:value2, ... }

The name and value are separated by ':'. The name-value pairs are separated by commas. There is no comma after the last name-value pair. JavaScript's object is simply a collection of name-value pair (of properties or methods), similar to a hash or an associative array, as reflected in the above syntax. For example:
// Create an object via object literal var circle = { radius: 5.5, dateCreated: new Date(), getArea: function toString: circleDescription } function() { return this.radius*this.radius*Math.PI; }, // inline

// Define method function circleDescription() { return "Circle with radius=" + this.radius + " created on " + this.dateCreated; }

// Invoke method using the dot operator document.writeln("<p>" + circle + ", Area=" + circle.getArea() + "</p>");

Object literal has gained popularity over the past few years (over the procedural approach). A subset of the object literal called JSON (JavaScript Object Notation) has become one of the most common data formats for Ajax.

Operator " delete "

You can remove a property or a method from an object via operator delete.

Operator " instanceOf "

You can use the instanceOf operator to check if a particular instance belongs to a particular class of objects, e.g.,
var now = Date(); now instanceOf Date; // gives true;

Operator " in "

You can use the in operator to check if a particular property belongs to an object, for example,
"PI" in Math; // gives true

Loop for...in
Iterate a specified variable over all the properties of an object. Example [TODO]

Loop with
Establishes the default object for a set of statements. Example [TODO]

9.3 Property


All the JavaScript objects have a special property called prototype, that can be used to add property or method dynamically after the object is defined (via a constructor or an initializer). The added property/method will be available to all the new objects. For example,
// Circle constructor function Circle(radius) { this.radius = radius || 1.0; this.getArea = function() { return this.radius * this.radius * Math.PI; }; }

// Define more property and method Circle.prototype.getCircumference = function() { return 2 * this.radius * Math.PI; };

Circle.prototype.color = "green";

// Create a Circle and invoke property/methods var circle1 = new Circle(1.5); document.writeln(circle1.getArea()); document.writeln(circle1.getCircumference()); document.writeln(circle1.color);

"prototype" is a powerful tool. It lets you modify existing object in your program. You can add extra properties or methods to existing objects at runtime. Any time you attempt to access a property of that isn't defined in the constructor, JavaScript will check the prototype to see if it exists there instead, e.g., circle1.getCircumference() and circle1.color in the above example. You can implement inheritance via prototype, by setting aChildObject.prototype = new parentObject().

9.4 Property


All JavaScript objects has a special property called constructor, which contains a reference to the function that created the object. For example,
// Construct an Array object var months = new Array('jan', 'feb', 'mar'); document.writeln(months.constructor); document.writeln(months); // Array() // jan,feb,mar

// Create another Array object by invoking the constructor of the first object. var days = months.constructor('mon', 'tue', 'wed') document.writeln(days); // mon,tue,wed

10. Document Object Model (DOM) API for JavaScript

Document Object Model (DOM), is a standard API that allows programmers to access and manipulate the contents of an HTML/XHTML/XML document dynamically inside their program. It models an HTML/XHTML/XML document as an object-oriented, tree-like structure, known as a DOM-tree, consisting of nodes resembling the tags (elements) and contents. DOM also provides an interface for event handling, allowing you to respond to user's or browser's action.

DOM API is implemented in many languages such as Java, JavaScript, Perl, and ActiveX. DOM API specification is maintained by W3C. DOM has various levels: DOM Level 0 (DOM0) (Pre-W3C): obsolete DOM Level 1 (DOM1) (W3C Oct 1998): obsolete DOM Level 2 (DOM2) (W3C Nov 2000) and DOM Level 2 HTML (HTML DOM2) (W3C Jan 2003) DOM Level 3 (DOM3) (W3C Apr 2004): yet to be fully supported by browsers.

10.1 Finding and Selecting Elements

In JavaScript, we often use DOM API to select elements within the current document, so as to access or manipulate their contents. The most commonly-used functions are:


Descriptio n
Returns the element with the given unique id. Returns an array of elements with the given

<input type="text" id="foo" /> var elm = document.getElementById("foo"); var input = elm.value; <input type="checkbox" name="foo" value="hello" /> var elms = document.getElementsByName("foo"); var input = elms[0].value;


attribute. Several elements may share the same name attribute.

document.getElementsByTagName(aTagN ame)

Returns an array of elements with the given tag name.

<input type="text" /> var elms = document.getElementByTagName("inpu t"); var input = elms[0].value;

You can use wildcard * in document.getElementsByTagName("*") to select all the elements, e.g.,
var elms = document.getElementsByTagName("*"); for (var i = 0; i < elms.length; i++) { document.writeln("<p>" + elms[i].value + "</p>"); .......

The above functions select element(s) based on the unique id, name attribue and tag-name. HTML 5 further defines two function that can select elements based on class attribute (which is used extensively by CSS in the class-selector):

document.querySelector(aClassName) document.querySelectorAll(aClassName)

Returns the first element with the given class attribute. Returns an array of elements with the given class attribute.


Beside the above selection functions, there are many other selection functions available. However, I strongly recommend that you stick to the above functions. I listed below the other function below for completeness. 1. document.images returns an array of all
document.getElementsByTagName("img"). <img>




2. document.forms: return an array of all <form> elements. 3. document.links and document.anchors: return all the hyperlinks <a href=...> and anchors <a name=...> elements. [To confirm!]

10.2 Manipulating Element's Content thru the " innerHTML " Property
You can access and modify the content of an element via the "innerHTML" property, which contains all the texts (includes nested tags) within this element. For example,
<p id="magic">Hello, <em>Paul</em></p> <script type="text/javascript"> var elm = document.getElementById("magic"); // Read content alert(elm.innerHTML); // Change content elm.innerHTML = "Goodday, <strong>Peter</strong>"; alert(elm.innerHTML); </script> // Goodday, <strong>Peter</strong> // Hello, <em>Paul</em>

"innerHTML" is the most convenient way to access and manipulate an element's content. However, it is not a W3C standard, but it is supported by most of the browsers.

10.3 DOM Tree & Nodes

W3C recommends that you access and manipulate HTML elements via the DOM tree and nodes. However, it is really an overkill for writing simple JavaScripts. I present them here again for completeness. When a browser loads an HTML page, it builds DOM models a web page in a hierarchical tree-like structure composing of nodes, resembling its HTML structure. An example of an HTML document with the corresponding DOM-tree is given follow. Take note that the text content of an element is stored in a separate Text node.
<html> <head> <title>DOM Tree</title> </head> <body> <h2 onmouseover="this.style.color='red'" onmouseout="this.style.color=''">Testing</h2> <p>welcome to <i>JavaScript</i>...</p> </body> </html>

Load the web page onto Firefox, and use the firebug to inspect the DOM tree. A DOM-tree comprises the following types of nodes: 1. Document Node: the root node representing the entire HMTL document. 2. Element node: represents an HTML element (or tag). An element node may have child nodes, which can be either element or text node. Element node may also have attributes. 3. Text Node: contains the text content of an element. 4. Others: such as comment, attribute. A DOM node has these properties:
nodeName: contain the name of the node, which is read-only. The nodeName for an Element node is the tag-name; nodeName for the Document node is #document; nodeName for Text nodes is #text. nodeValue: contain the value of the node. nodeValue for Text node is the text contained; nodeValue for Element node is undefined. nodeType: an integer indicating the type of the node, e.g., Element (1), Attribute (2), Text (3),

Comment (8), Document (9).

parentNode: reference to parent node. There is only one parent node in a tree structure. childNodes: array (or node-list) of child nodes.

firstChild, lastChild: reference to the first and last child node. prevSibling, nextSibling: reference to the previous and next sibling in the same level.

Take note of the difference between singular and plural terms. For example, parentNode refer to the parent node (each node except root has one and only one parent node), childNodes holds an array of all the children nodes. The root node of the DOM tree is called document. The root node document has only one child, called document.documentElement , representing the <html> tag, and it acts as the parent for two child nodes representing <head> and <body> tags, which in turn will have other child nodes. You can also use a special property called document.body to access the <body> tag directly. For example, you can use the following node property to access the Text node "Welcome to " in the above example:
document.documentElement.lastChild.childNodes[1].firstChild.nodeValue; // "Welcome to " document.body.lastChild.firstChild.nodeValue; above // same as

The following JavaScript lists all the nodes in the <body> section, in a depth-first search manner, via a recursive function.
<html> <head> <title>DOM Tree</title> <script language="JavaScript"> function printNode(node) { document.writeln("Node name=" + node.nodeName + ", value=" + node.nodeValue + ", type=" + node.nodeType + "<br />"); if (node.hasChildNodes()) { var childs = node.childNodes; for (var i = 0; i < childs.length; i++) { printNode(childs[i]); } } } </script>

</head> <body onload="printNode(document.body)" ><h2 onmouseover="this.style.color='red'" onmouseout="this.style.color=''">Testing</h2><p>welcome <i>JavaScript</i>...</p></body> </html> Node name=BODY, value=null, type=1 Node name=H2, value=null, type=1 Node name=#text, value=Testing, type=3 Node name=P, value=null, type=1 Node name=#text, value=welcome to , type=3 Node name=I, value=null, type=1 Node name=#text, value=JavaScript, type=3 Node name=#text, value=..., type=3 to

Accessing the HTML element via Node interface may not be too useful nor practical for JavaScript applications, as you need to know the actual topological structure of the DOM-tree. Furthermore, some browsers (e.g., firefox) may create extra Text nodes to contain the white spaces between tags.

10.4 Text Node

DOM models the texts enclosed by HTML tags as a separate text node. It cannot have child node. To retrieve the text content, you could the property nodeValue. For example,
<p id="magic">Hello</p> ...... alert(document.getElementById("magic").firstChild.nodeValue ); document.getElementById("magic").firstChild.nodeValue = "Hi"; // text change to "Hi"


Attribute Properties
property elementName.attributeName, where attributeName is the name of the attribute, or methods value).

To access an attribute of an Element node called elementName, you could either use:



For example,

<html> <head><title>Test Attributes</title></head> <body> <p id="magic1" align="left">Hello</p> <p id="magic2" align="center">Hello, again.</p>

<script type=text/javascript> var node = document.getElementById("magic1") ; document.writeln(node.align); node.align = "center"; // Get attribute "align" // Set attribute "align" to a new value

node = document.getElementById("magic2") ; document.writeln(node.getAttribute("align") ); node.setAttribute("align", "right") ; </script> </body> </html> // Read attribute "align" // Write attribute "align"

10.6 Attribute


(for CSS)

Element has a property called style, which models CSS style with CSS properties such as color and textAlign. For example,
<p id="magic">Hello</p> ...... document.getElementById("magic1").style.color="green"; document.getElementById("magic1").style.textAlign="right";

10.7 Manipulating Nodes

A Node object has these functions:
aNode.hasChildNodes(): returns true if this node has at least one child node.

Manipulating child node:

o o o o


before an existing child node. child node.


insert a


aParentNode.replaceChild(newChildNode, existingChildNode): replace an existing aParentNode.removeChild(childNodeToRemove): remove the specified child node. aParentNode.appendChild(nodeToAppend): append the given node as the last child.


Creating a New Element ( createElement() ) and Text Node ( createTextNode() ), Appending a Node ( appendChild() )
To create new text node, you can use document.createTextNode(text) to create a standalone textnode, followed by an anElementNode.appendChid(aTextNode) to append the text node to an element. Similarly, you can use document.createElement(tagName) to create a stand-alone element, followed by an anElementNode.appendChild(elementToAppend) to append the created element into an existing element. For example, we shall create a new text node, as a child of a new <p> element. We shall then append the new <p> element as the last child of <body>.
<body> <p id="magic">Hello</p> <script type="text/javascript"> alert(document.getElementById("magic").innerHTML); var newElm = document.createElement("p"); newElm.appendChild(document.createTextNode("Hello, again")); document.body.appendChild(newElm); </script> </body>

Inserting a new Node ( insertBefore() )

<body> <p id="magic">Hello</p> <script type="text/javascript"> var magicElm = document.getElementById("magic"); alert(magicElm.innerHTML); var newElm = document.createElement("p");

newElm.appendChild(document.createTextNode("Hello, again")); document.body.insertBefore(newElm, magicElm); </script> </body>

Replacing a Node ( replaceChild() )

Change the last line to document.body.replaceChild(newElm, magicElm) .

Deleting a Node ( removeChild() )

You can remove a child node from a parent node via aParentNode.removeChild(aChildNode). For example, let remove the last <p> from <body>.
<body> <p>Hello 1</p> <p>Hello 2</p> <p id="magic">Hello 3</p> <script type="text/javascript"> var elm = document.getElementById("magic"); alert(elm.innerHTML); document.body.removeChild(elm); </script> </body>

10.8 The



The document object is the root node of the DOM-tree. It can be used to access all the elements in an HTML page. It contains these properties:
documentElement, body, title: references the <html>, <body> and <title> tags respectively. lastModified, referrer, cookie, domain: information retrieved from the HTTP response


form[], applets[], images[], embeds[], links[], anchors[]: Arrays containing the

respective HTML elements (backward compatible with DOM0). The document object has the following methods:
write(string), writeln(string): Write the specified string to the current document. writeln() (write-line) writes a newline after the string, while write() does not. Take note

that browser ignores newlines in an HTML document, you need to write a <br /> or <p>...</p> tag for the browser to display a line break.
clear(): Clear the document. open(), close(): Open/close the document stream. getElementById(), getElementsByName(), getElementsByTagName(): element(s) by id, name, or tag-name, respectively.



11. Event Handling in HTML DOM

JavaScripts are often event-driven. That is, a piece of codes (called event handler) fire in response to a certain user's or browser's action, such as clicking a button, enter some texts, or loaded a page. DOM API provides methods for capturing events so you can perform your own actions in response to them. It also provides an Event object which contains information specific to a given event that can be used by your event handler.

11.1 Attach Event Handler to an HTML tag

You can attach event handler (e.g., onclick, onmouseover) to a specific HTML tag as the tag's attribute, as follows:
<tagName eventHandler="JavaScript statement(s)" otherAttributes >contents</tagName>

The event handler can be a single JavaScript statement, a series of JavaScript statements (separated by semi-colon), or most often, a function call. For example,
<!-- Event handler calls built-in functions --> <body onload="alert('welcome')" onunload="alert('bye')" >

<!-- Event handler calls a user-defined function --> <script language="javaScript"> function myHandler(event) { alert(event); } </script> <input type="button" value="click me" onclick="myHandler()" />

<!-- Event handler composes of JavaScript statement(s) --> <h1 onmouseover="this.style.color='red'; this.style.backgroundColor='black'"

onmouseout="this.style.color=''; this.style.backgroundColor=''" >Hello</h1>

You can also define an event handler in script by assigning a Function object (without parentheses) to an event handler. For example,
<!-- Event handler assigned via DOM object instead of inside HTML tag --> <p id="magic">Welcome</p> <script language="javaScript"> document.getElementById("magic").onclick = myHandler; parentheses </script> // function name without the

11.2 Built-in Events and Event Handlers

JavaScript supports many types of events, as tabulated below. Certain events such as click are applicable to all the HTML elements; certain event such as load and unload are applicable to a selected group of tags.

Event Name
click submit reset select keypress keydown keyup mousedown mouseup mouseover moueout mousemove load unload

Event Handler
onclick onsubmit onreset onselect onkeypress onkeydown onkeyup onmousedown onmouseup onmouseover onmouseout onmousemove onload onunload

User clicks on the component. User clicks the "submit" button. User clicks the "reset" button. User selects text in a text box or text area. User holds down a key. User presses/releases a key. User presses/releases a mouse button. User moves the mouse pointer at/away from a link or hot spot. User moves the mouse pointer When the page is loaded into the window. When another page is about to be

HTML Element

<form>, <input type="submit"> <form>, <input type="reset"> <textarea>, <input type="text"> document, image, link, textarea

button, document, link

<body>, <frameset>, <img> <body>, <frameset>

loaded. blur onblur When a particular form element losses focus. E.g., after the element is selected, and the user clicks somewhere or hit the tag key. Same as onblur, but the elements must be changed. Same as onblur, but the element gains focus. User draps and drops something (e.g., a file) onto the navigator window. User moves/resizes the window Users stops or aborts an image from loading. When a JavaScript or image error occurs while loading a document or an image. window window, frame <img> <img>

change focus drapdrop move resize abort error [To Check]

onchange onfocus ondrapdrop onmove onresize onabort onerror

11.3 The



The event handlers are passed one argument, an Event object, which described the event and its current states. You can use it to determine where an event originated from and where it currently is in the event flow. The following properties are available to all the Event object:
type: A string indicating the type of event, e.g., "click", "mouseover". eventPhase: integer 1 for captured, 2 for at the target, and 3 for bubbling phase.

Mouse-Related Events
Including click, mouseup, mousedown, mouseover, mouseout, mousemove. For mouse-related events, the Event object provides these additional properties:
button: integer 1 for left button, 2 for middle, and 3 for right clientX, clientY: mouse location relative to the client area. screenX, screenY: mouse location relative to the screen. altKey, ctrlKey, metaKey, shiftKey: boolean value indicating where these key was pressed

when the mouse event is fired.

Key-Related Events
Including keyup, keydown and keypress. For key-related events, the Event object provides these additional properties:

keyCode: ASCII code of the key pressed. altKey, ctrlKey, metaKey, shiftKey: boolean flag indicating whether these key was also

clientX, clientY: mouse location relative to the client area. screenX, screenY: mouse location relative to the screen.

11.4 Adding Event Listener

You can also add/remove event listener to tags, using the following methods:
element.addEventListener(eventType, functionName, useCapture); element.removeEventListener(eventType, functionName, useCapture);

where eventType is pre-defined event name such as mouseover, mouseout, click, etc; functionName is the event handler; useCapture is a boolean flag which specifies at which phase of the event flow (capture or bubble) the event handler will be called. For example,
<p id="magic">Hello</p> ...... <script type="text/javascript"> var element = document.getElementById("magic"); element.addEventListener('mouseover', false); element.addEventListener('mouseout', function() { this.style.color=''; }, false); </script> function() { this.style.color='green'; },

Event listeners can be added to any node, even text nodes (which you could not assign event handlers to as they have no attributes). There are two phases of event flow: a capture phase followed by a bubbling phase. 1. Event Capture phase: The event first flows down from the document root to the target element that trigger the event. 2. Event Bubbling phase: the event then bubbles up from the target element to its parent node, all the way back to the document root. For each event type, you could define a event handler for the capture phase (triggered as event flows down from the root to the target element), and another event handler for the bubbling phase (triggered when the event bubble up from the target element to the root). Example: [TODO]

12. JavaScript Built-in Browser Objects: screen , history , location

12.1 The




The built-in navigator object represents the browser. It contains the following properties related to the browser:
platform: Operating system. appName, appCodeName, appVersion, appUserAgent: Identified the browser. language, plugin, mimeTypes: options or features supported by the browser.

others. [TO CHCEK]

12.2 The



The window object represents an open window in a browser. It is the top-level object in the JavaScript hierarchy. All top-level properties and methods such as alert(), prompt(), parseInt() belongs to the window object. The window object is also the default object. That is, alert() is the same as window.alert(). A window object is created automatically with every <body> or <frameset> tag. [TODO]

13. Regular Expression

A Regular Expression (or Regexe in short) is a pattern that accepts a set of strings that matches the pattern, and rejects the rests. Regexe is extremely and amazingly powerful in searching and manipulating text strings and text documents. Read "Regular Expression" for syntax on regexe.

13.1 Examples
/^[0-9]+$/ matches strings with 1 or more digits. /^[0-9]{5,8}$/ matches string with 5 to 8 digits. /^[a-zA-Z]+$/ matches strings with 1 or more letters. /^[0-9a-zA-Z]+$/ matches strings with 1 or more digits or letters.

13.2 Creating a Regexe in JavaScript

There are two ways to create a regexe in JavaScript: 1. Use a regexe literal enclosed by two forward slashes /.../, for example,
2. var identifier = /[a-zA-Z_][a-zA-Z_]*/; 3. var integer = /[1-9][0-9]*|0/;

var imageFile = /\w+\.(jpg|gif|png)/i;

4. Call the constructor of the built-in RegExe object, for example,

5. var pattern = new RegExe("[1-9][0-9]*|0"); var anotherPattern = new RegExe("\w+\.(jpg|gif|png)", "i"); modifier // pattern,

Modifier: You can use modifier "g" to perform a global search (return all matches instead of the
first match), and "i" for case-insensitive matching, as shown in the above example.

Back References: You can use $1 to $99 to refer to the back references (within a string), or
Regexe.$1 to Regexe.$99 object properties. Example 1: Swap first and second words
var pattern = /(\S+)\s+(\S+)/; var input = "Hello world";

input = input.replace(pattern, "$2 $1"); // result is "world Hello"

Example 2: Remove HTML markup tags in non-greedy manner

var pattern = /<code>(.*?)<\/code>/g; // ? (after *) curb greediness; g modifier for global match var input = "<code>first</code> and <code>second</code>"; input = input.replace(pattern, "$1"); // result is "first and second" // If greedy is used (remove the ?), // result is "first</code> and <code>second"

13.3 JavaScript's Methods that use Regular Expression

Regexe are meant for searching and manipulating text string. Hence, the String and RegExe objects have many methods to operate on regexe and string.

String Object
aStr.match(regexe): Match this string with the given regexe. Returns the matched substring or null if there is no match.

aStr.search(regexe): Search this string for the given regexe pattern. Returns the beginning

position of the matched substring or -1 if there is no match.

aStr.replace(regexe, replacement): Search the string for the given regexe pattern. If found, replaces the matched substring it with the replacement string. aStr.split(regexe): Split this string using the delimiter pattern defined in regexe. Returns

an array of strings containing the splitting parts.

RegExe Object
aRegexe.test(aStr): Tests this regexe against the given string. Returns boolean true or false. aRegexe.exec(aStr): Executes a search for a match in a string and returns the first match (or an array of matched substring with "g" modifier). aRegexe.compile(): Compile this regexe to improve the running efficiency.

Example: aStr .match( aRegexe ) and aRegexe .test( aStr )

var msg = "Hello world"; var pattern = /hell/; // case sensitive matching

document.write(msg.match(pattern) + "<br />"); // null (no match) document.write(pattern.test(msg) + "<br />"); // false

pattern = /hell/i;

// case insensitive matching

document.write(msg.match(pattern) + "<br />"); // "Hell" document.write(pattern.test(msg) + "<br />"); // true

Example: aStr .replace( aRegexe , replacementStr )

var msg1 = "This is a string"; var pattern = /is/; // First match only

document.write(msg1.replace(pattern, "was") + "<br />"); // Thwas is a string var pattern = /is/g; // All matches (global)

document.write(msg1.replace(pattern, "was") + "<br />"); // Thwas was a string

Example: aStr .search( aRegexe )


Example: aStr .split( aRegexe )


14. Miscellaneous
14.1 Task Scheduling via Timeout
Two methods, setTimeout(codes, milliseconds) and clearTimeout(timeoutName) are provided to schedule a piece of codes to be executed after a specified milliseconds.
var task = setTimeout("alert('Hello')", 10000);

The variable task permits you to cancel the scheduled time event before timeout if desires:

14.2 Bitwise Operators

JavaScript provides the following bitwise operators are provided for integers (same syntax as Java):

<< >> >>> & | ~ ^

Left bit-shift (padded with 0s) Signed right bit-shift (padded sign-bit) Unsigned right bit-shift (padded with 0s) Bitwise AND Bitwise OR Bitwise NOT (1's compliment) Bitwise XOR

bitPattern << number bitPattern >> number bitPattern >>> number bitPattern1 & bitPattern2 bitPattern1 | bitPattern2 ~bitPattern bitPattern1 ^ bitPattern2


Similarly, the following bitwise operation cum assignment operators are provided: <<=, >>=, >>>=, &=, |=, ^=.

14.3 Operator Precedence

Operator Name
Parentheses, Array index, Dot Negation, Increment/Decrement Multiply, Divide, Modulus Addition, Subtraction Bitwise Shift

() [] . ! ~ - ++ -* / % + << >> >>>

Relational Equality Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Ternary (Shorthand if-else) Assignment Comma (separate parameters)

< <= > >= == != & ^ | && || ? : = += -= *= /= %= ,

14.4 Try-catch and Exception Handling


14.5 Execute JavaScript Statement from Browser's Address Bar

You can issue You can execute JavaScript from Firefox's navigator toolbar or Internet Explorer's address bar, via pseudo-protocol javascript:statement. For example,
javascript:alert('Hello'); javascript:alert(document.title);alert('Hello, again') javascript:document.title

The statement can access variables and objects on the current document. The JavaScript statement used in a javascript: URL should not return any value. For example, alert() does not return a value (or returns undefined). If it returns an explicit value, the browser loads a new page and places the returned value in the body of the page. You can use the void operator to stay in the same page. void evaluates its expression, and returns undefined. For example,

You can bookmark the javascript statement (someone called them bookmarklets). For example, you can write a bookmarklet to change the background color of a web page, so that the web page is easier to read.


1. ECMAScript Specification: "Standard ECMA-262 ECMAScript Language Specification 5.1", (same as "ISO/IEC 16262" 3rd eds). 2. Mozilla's (MDN) JavaScript Project @ https://developer.mozilla.org/en/JavaScript. "Core JavaScript Guide" @ https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide, and "Core JavaScript Reference" @ https://developer.mozilla.org/en/JavaScript/Reference. 3. "Document Object Model (DOM)" Level 1, 2, 3 @ http://www.w3.org/standards/techs/dom. 4. "JavaScript" and "HTML DOM" Tutorials @ http://www.w3schools.com.
Last modified: October 14, 2009 Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan (ehchua@ntu.edu.sg) | HOME