Basic Javascript Intro
Basic Javascript Intro
| HOME
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
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
12. JavaScript Built-in Browser Objects: navigator, window, screen, history, location
12.1 The navigator object 12.2 The window object
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
JavaScript
Basics
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)
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.
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.
alert()
and
document.write()
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.
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>
(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.
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.
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>");
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
Date
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>
TRY:
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 ;
13</body> 14</html>
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).
TRY:
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.)
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() ">
onmouseover and onmouseout: fires when the user points the mouse pointer at/away from
6 7
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
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>
10
<p>Try closing the window or refreshing the page to activate the "Bye" alert
c.
<p
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
CSS
file
{
contains
only
one
style
definition:
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>
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?!)
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>
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!";
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.
TRY: [TODO]
TRY: [TODO]
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.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
[TODO]
5.1 The
<script>...</script>
Tags
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>
5.2
<head>
or
<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.
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
<noscript>...</noscript>
Tags
The <noscript>...</noscript> tags provide an alternate message if scripting is disabled or not supported.
6.2 Expression
An expression is a combination of variables, literals, operators, and sub-expressions that can be evaluated to produce a single value.
You can assign (and re-assign) a value to a variable using the assignment '=' operator.
Literals
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.
Types
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).
Example
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
Constants
You can create a read-only, named constant with the keyword const (in place of var). For example,
const SIZE = 9;
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.
Operator
+ * / % ++
Description
Addition Subtraction (or Unary Negation) Multiplication Division Modulus (Division Remainder) Unary Pre- or PostIncrement Unary Pre- or PostDecrement
Result
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.
Operator
+= -= *= /= %=
Description
Addition cum Assignment Subtraction cum Assignment Multiplication cum Assignment Division cum Assignment Modulus cum Assignment
Example
x += y; x -= y; x *= y; x /= y; x %= y;
Result
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;
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)
alert(parseInt(magic) + 22);
alert(parseInt(magic) + "22"); // String "1122" alert(parseInt(magic) + parseFloat("22.33")); alert(parseInt("abc")); // NaN // Number 33.33
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'.
Operator
==
Description
Equal To
Example
num == 8 str == '8' num == str 8 == '8' num == 8 str == '8' num == str 8 == '8'
Result
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.
Example,
<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)
// Comparing two strings document.writeln("8" < "10"); document.writeln("8" < "9"); // false (comparing two strings alphabetically) // true (comparing two strings, not numbers)
Logical Operators
The following boolean (or logical) operators are provided in JavaScript:
Operator
&& || !
Description
Logical AND Logical OR Logical NOT
Example
Result
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.
Convert a Number to a String : Simply concatenate the number with an empty-string, e.g., "" +
5 gives "5".
Convert
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.
gives
55,
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().
Syntax
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; }
Example
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++.
Syntax
while (test) { trueBlock; } do { trueBlock; } while (test); for (initialization; test; post-processing) { trueBlock; }
Example
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; }
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 \>");
Primitive arguments are passed by value. That is, a copy of the variable is made and passed into the function.
example,
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.
For example,
parseInt("88"); parseInt("88.99"); parseInt("Hello"); // gives number 88 // gives number 88 // gives NaN (Not-A-Number)
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.
load, unload: generated after the browser loaded a document, and before the next
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>
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.
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).
8.2
Array
Object
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
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,
concat(value1, value2, ..., valueN): returns a new array composing of this array and
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
added.
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
Important: For detailed specification and examples about a built-in object, check "Core JavaScript References". Example: [TODO]
8.3
String
Object
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
(exclusive).
split(delimiter): returns an array by splitting the string using delimiter. toUpperCae(), toLowerCase(): returns the uppercase/lowercase string.
8.4
Number
Object
Number object is a wrapper object for primitive number, which provides many properties and
methods.
8.5
Boolean
Object
Boolean object is a Wrapper object for primitive boolean, which provides many properties and
methods.
8.6
Date
Object
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
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():
getTime(), setTime(): get/set the number of milliseconds since January 1, 1970, 00:00:00.
8.7
Math
Object
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:
abs(x)
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.
8.8
Function
Object
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
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
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.
Example
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.
4function Circle(radius) {
22}
c.
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.
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.
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
prototype
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
constructor
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
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.
Function
document.getElementById(anId)
Descriptio n
Returns the element with the given unique id. Returns an array of elements with the given
name
Example
<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;
document.getElementsByName(aName)
<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):
Function
document.querySelector(aClassName) document.querySelectorAll(aClassName)
Description
Returns the first element with the given class attribute. Returns an array of elements with the given class attribute.
Example
[TODO] [TODO]
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>
elements,
same
as
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.
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),
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
Example
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.5
Attribute Properties
property elementName.attributeName, where attributeName is the name of the attribute, or methods value).
elementName.getAttribute(name)
To access an attribute of an Element node called elementName, you could either use:
and
elementName.setAttribute(name,
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
style
(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";
o o o o
aParentNode.insertBefore(newChildNode,
existingChildNode):
insert a
node
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.
aNode.cloneNode():
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>
10.8 The
document
object
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
header.
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.
Select
HTML
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'"
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
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
Description
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
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>
11.3 The
Event
object
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
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
pressed.
clientX, clientY: mouse location relative to the client area. screenX, screenY: mouse location relative to the screen.
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]
navigator
window
object
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.
12.2 The
window
object
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.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.
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";
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
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
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.
document.write(msg.match(pattern) + "<br />"); // null (no match) document.write(pattern.test(msg) + "<br />"); // false
pattern = /hell/i;
document.write(msg1.replace(pattern, "was") + "<br />"); // Thwas is a string var pattern = /is/g; // All matches (global)
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:
cancelTimeout(task);
Operator
<< >> >>> & | ~ ^
Description
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
Example
bitPattern << number bitPattern >> number bitPattern >>> number bitPattern1 & bitPattern2 bitPattern1 | bitPattern2 ~bitPattern bitPattern1 ^ bitPattern2
Result
Similarly, the following bitwise operation cum assignment operators are provided: <<=, >>=, >>>=, &=, |=, ^=.
Operator
() [] . ! ~ - ++ -* / % + << >> >>>
Relational Equality Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Ternary (Shorthand if-else) Assignment Comma (separate parameters)
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,
javascript:void(x=5)
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.
javascript:void(document.body.style.background='#FFF');
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 ([email protected]) | HOME