By David Flanagan
Book Price: $9.95 USD
£6.95 GBP
PDF Price: $7.99
Cover | Table of Contents
/* and
*/ is a comment, and is ignored by JavaScript.
Also, any text between // and the end of the
current line is a comment, and is ignored. Examples:
// This is a single-line, C++-style comment. /* * This is a multi-line, C-style comment. * Here is the second line. */ /* Another comment. */ // This too.
_ and
$ characters. The first character of an identifier
must not be a digit, however. The following are legal identifiers:
i my_variable_name v13 $str
/* and
*/ is a comment, and is ignored by JavaScript.
Also, any text between // and the end of the
current line is a comment, and is ignored. Examples:
// This is a single-line, C++-style comment. /* * This is a multi-line, C-style comment. * Here is the second line. */ /* Another comment. */ // This too.
_ and
$ characters. The first character of an identifier
must not be a digit, however. The following are legal identifiers:
i my_variable_name v13 $str
break do if switch typeof case else in this var catch false instanceof throw void continue finally new true while default for null try with delete function return
var statement:
var i = 1+2+3; var x = 3, message = 'hello world';
1 3.14 0001 6.02e23
0x:
0xFF // The number 255 in hexadecimal
NaN, which
represents a value that is not-a-number. Use the global function
isNaN( ) to test for this value.
Math.sin(
), Math.pow( ), and
Math.random( ).
true and
false. These values represent truth or falsehood,
on or off, yes or no, or anything else that can be represented with
one bit of information.
'testing' "3.14" 'name="myform"' "Wouldn't you prefer O'Reilly's book?"
\) appears within a
string literal, it changes, or escapes, the meaning of the character
that follows it. The following table lists these special escape
sequences:
|
Escape
|
Represents
|
|---|---|
\b |
Backspace |
1+2 total/n sum(o.x, a[3])++
|
P
|
A
|
Operator
|
Operation performed
|
|---|---|---|---|
|
15
|
L
|
.
|
Access an object property
|
|
L
|
[ ] |
Access an array element
| |
|
L
|
( ) |
Invoke a function
| |
|
R
|
new |
Create new object
| |
|
14
|
R
|
++ |
Pre-or-post increment (unary)
|
|
R
|
-- |
Pre-or-post decrement (unary)
| |
|
R
|
- |
Unary minus (negation)
| |
|
R
|
+ |
Unary plus (no-op)
| |
|
R
|
~ |
Bitwise complement (unary)
| |
|
R
|
! |
Logical complement (unary)
| |
|
R
|
delete |
Undefine a property (unary) (JS 1.2)
| |
|
R
|
typeof |
Return data type (unary) (JS 1.1)
| |
|
R
|
void |
Return undefined value (unary) (JS 1.1)
| |
|
13
|
L
|
*, /, % |
Multiplication, division, remainder
|
|
12
|
L
|
+, - |
Add, subtract
|
|
L
|
+ |
Concatenate strings
| |
|
11
|
L
|
<< |
Integer shift left
|
|
L
|
>> |
Shift right, sign-extension
| |
|
L
|
>>> |
Shift right, zero extension
| |
|
10
|
L
|
<, <= |
Less than, less than or equal
|
|
L
|
>, >= |
Greater than, greater than or equal
| |
|
L
|
instanceof |
Check object type (JS 1.5)
| |
|
L
|
in |
Check whether property exists (JS 1.5)
| |
|
9
|
L
|
== |
Test for equality
|
|
L
|
!= |
Test for inequality
| |
|
L
|
=== |
Test for identity (JS 1.3)
| |
|
L
|
!== |
Test for non-identity (JS 1.3)
| |
|
8
|
L
|
& |
Integer bitwise AND
|
|
7
|
L
|
^ |
Integer bitwise XOR
|
|
6
|
L
|
| |
Integer bitwise OR
|
|
5
|
L
|
&& |
Logical AND
|
|
4
|
L
|
|| |
Logical OR
|
|
3
|
R
|
?: |
Conditional operator (3 operands)
|
|
2
|
R
|
= |
Assignment
|
|
R
|
*=, +=, -=,
etc.
|
Assignment with operation
| |
|
1
|
L
|
,
|
Multiple evaluation |
s = "hello world"; x = Math.sqrt(4); x++;
while loop consists of a single
statement. If you want the loop to execute more than one statement,
use a compound statement. This is a common technique with
if, for, and other statements
described later.
break and continue statements:
label : statement
breakbreak statement terminates execution of the
innermost enclosing loop, or, in JavaScript 1.2 and later, the named
loop:
break ;
break label ;
casecase is not a true statement. Instead it is a
keyword used to label statements within a JavaScript 1.2 or later
switch statement:
case constant-expression : statements [ break ; ]
switch statement, a
group of statements labeled by case should usually
end with a break statement.
continuecontinue statement restarts the innermost
enclosing loop, or, in JavaScript 1.2 and later, restarts the named
loop:
continue ;
continue label ;
defaultcase, default is not a
true statement, but instead a label that may appear within a
JavaScript 1.2 or later switch statement:
default:
statements
[ break ; ]
do/whiledo/while loop repeatedly executes a statement
while an expression is true. It is like the
while loop, except that the loop condition appears
(and is tested) at the bottom of the loop. This means that the body
of the loop is executed at least once:
new operator and it uses the
this keyword to refer to and initialize the newly
created object. For example, here is a constructor to create objects
of a new class named Point.
function Point(x,y) { // Constructor for Point
this.x = x; // Initialize X coordinate
this.y = y; // Initialize Y coordinate
}
prototype. This property refers to a special
prototype object for the class of objects created by the constructor.
Any properties you define on this prototype object are inherited by
all objects created with the constructor function. The prototype
object is commonly used to make methods available to all instances of
a class. Defining a method named toString allows
instances of your class to be converted to strings. For example:
// Define function literals and assign them
// to properties of the prototype object.
Point.prototype.distanceTo = function(that) {
var dx = this.x - that.x;
var dy = this.y - that.y;
return Math.sqrt(dx*dx + dy*dy);
}
Point.prototype.toString = function () {
return '(' + this.x + ',' + this.y + ')';
}
// Define a commonly used Point constant Point.ORIGIN = new Point(0,0);
// Call constructor to create a new Point object var p = new Point(3,4); // Invoke a method of the object, using a static // property as the argument. var d = p.distanceTo(Point.ORIGIN); // Adding the object to a string implicitly // invokes toString(). var msg = "Distance to " + p + " is " + d;
/)
characters, optionally followed by one or more of the modifier
characters g (global search), i
(case-insensitive search), and m (multi-line mode;
a JavaScript 1.5 feature). In addition to this literal syntax,
RegExp objects can be created with the
RegExp( ) constructor, which accepts the pattern
and modifier characters as string arguments, without the slash
characters.
\) that have special meanings. The simplest of
these escape sequences provide alternative ways of representing
literal characters:
|
Character
|
Meaning
|
|---|---|
\n, \r, \t |
Match literal newline, carriage return, tab
|
\\, \/,
\*,\+, \?,
etc.
|
Match a punctuation character literally, ignoring or escaping its
special meaning
|
\xnn |
The character with hexadecimal encoding nn.
|
\uxxxx |
The Unicode character with hexadecimal encoding
xxxx.
|
|
Character
|
Meaning
|
|---|---|
[...] |
Match any one character between brackets
|
[^...] |
Match any one character not between brackets
|
|
.
|
Match any character other than newline
|
\w, \W |
Match any word/non-word character
|
\s, \S |
Match any whitespace/non-whitespace |
switch statement, regular
expressions, and a number of other features. Almost compliant with
ECMA v1, but has some incompatibilities. Implemented by Netscape 4.
switch statement or regular
expression support. Conformant implementations are JavaScript 1.3 and
JScript 3.0.
<script> tag and a
</script> tag. For example:
<script>
document.write("The time is: " + new Date());
</script>
src
attribute of the <script> tag to specify the
URL of an external script to be loaded and executed. Files of
JavaScript code typically have a .js extension.
Note that the </script> tag is still
required when this attribute is used:
<script src="library.js"></script>
language attribute to
specify what language a script is written in. This attribute defaults
to "JavaScript"
in all browsers, so you do not usually have to set it. You can also
use attribute values such as
"JavaScript1.3" and
"JavaScript1.5" to specify the
version of JavaScript your code uses. Browsers that do not support
the specified version of the language simply ignore the script.
<script> tag and a
</script> tag. For example:
<script>
document.write("The time is: " + new Date());
</script>
src
attribute of the <script> tag to specify the
URL of an external script to be loaded and executed. Files of
JavaScript code typically have a .js extension.
Note that the </script> tag is still
required when this attribute is used:
<script src="library.js"></script>
language attribute to
specify what language a script is written in. This attribute defaults
to "JavaScript"
in all browsers, so you do not usually have to set it. You can also
use attribute values such as
"JavaScript1.3" and
"JavaScript1.5" to specify the
version of JavaScript your code uses. Browsers that do not support
the specified version of the language simply ignore the script.
language
attribute of the <script> tag. Instead, the
official way to specify the language a script is written in is with
the type attribute. For JavaScript, set this
attribute to the MIME type
"text/javascript":
<script src="functions.js"
language="JavaScript1.5"
type="text/javascript"></script>
onclick attribute specifies an event handler that
displays an alert (a dialog box) when the user clicks the button:
<input type="button" value="Press Me"
onclick="alert('Hello World!');">
window and refers back to the Window object
itself:
window // The global Window object window.document // The document property of the window document // Or omit the object prefix
document, which refers to the Document object that
describes the document displayed by the browser window. The Document
object is described in a section of its own following these
window-related subsections.
alert( ) lets you display a message to the user,
confirm( ) lets you ask the user a yes-or-no
question, and prompt( ) lets you ask the user to
enter a single line of text. For example:
alert("Welcome to my home page!");
if (confirm("Do you want to play?")) {
var n = prompt("Enter your name");
}
status property. The text you set on this
property appears in the status area until you or the browser
overwrites it with some new value. You can also set
defaultStatus to specify text to appear by default
when the browser is not displaying any other information in the
status line. Here is an HTML hyperlink that uses JavaScript in an
event handler to set the status text to something other than the URL
of the link:
document property that
refers to a Document object. The Document object is arguably more
important than the Window object itself: while the Window represents
the browser window, the Document object represents the HTML document
that is displayed in that window. The Document object has various
properties that refer to other objects which allow access to and
modification of document content. The way that document content is
accessed and modified is called the document object model, or DOM,
and there are several DOMs in existence:
title,
URL, and lastModified provide
information about the document as a whole. See the reference section
for further details on these and all Document properties and methods.
Other properties are arrays that refer to specific types of document
content:
forms[ ]images[ ]applets[ ]links[ ]anchors[ ]name attribute of the HTML
<a> tag) in the document.
document.forms[0], and the third image is
document.images[2]. Another way to refer to
document forms, images, and applets is to give them names with the
HTML name attribute:
<form name="address">...</form>
document.forms["address"] // A named form document.address // The same thing
elements[ ] array that contains objects
representing the elements of the form, in the order they appear in
the form. See Input, Select, and Textarea in the reference section
for details on these form elements.
elements[ ] array of a Form works much like
the forms[ ] array of a Document: it holds form
elements in the order they appear in the form, but it also allows
them to be referred to by name. Consider this HTML excerpt:
forms[ ], images[ ], and other
array properties of the Document object, it defines methods that
allow scripts to access and manipulate any document element, not just
special-purpose elements like forms and images.
id attribute with a unique value.
Then, you can use the getElementById( ) method of
the Document object to look up those elements by their ID:
<h1 id="title">Title</h1>
<script>
var t = document.getElementById("title");
</script>
getElementsByTagName( ) method of the
Document object returns an array of all elements of that type. Each
document element also supports the same method, so you can also
obtain an array of specific types of tags that are all descendents of
an element:
// Get an array of all <ul> tags
var lists = document.getElementsByTagName("ul");
// Find the 3rd <li> tag in the second <ul>
var item = lists[1].getElementsByTagName("li")[2];
// Look up a node in the document
var n = document.getElementById("mynode");
var p = n.parentNode; // The containing tag
var c0 = n.firstChild; // First child of n
var c1 = c0.nextSibling; // 2nd child of n
var c2 = n.childNodes[2]; // 3rd child of n
var last = n.lastChild; // last child of n
documentElement property of the
Document object refers to the single getElementById(
) method. Instead, it allows you to look up arbitrary
document elements by id attribute within the
all[ ] array of the document object:
var list = document.all["mylist"]; list = document.all.mylist; // this also works
getElementsByTagName( )
method, the IE 4 DOM takes the unusual step of defining a
tags( ) method on the all[ ]
array, which exists on document elements as well as the Document
object itself. Here's how to find all
<li> tags within the first
<ul> tag:
var lists = document.all.tags("UL");
var items = lists[0].all.tags("LI");
all.tags( ) method.
childNodes[ ],
IE 4 uses children[ ], and instead of
parentNode, IE 4 uses
parentElement. IE 4 does not have any analogs to
firstChild, nextSibling, and
related W3C properties. One important difference between the IE 4 and
W3C DOMs is that the IE 4 document tree only includes HTML tags:
comments are ignored and document text is not part of the tree
itself. Instead, the text contained by any element is available
through the innerHTML and
innerText properties of the element object.
(We'll see more about innerHTML
in the next section.)
style property that corresponds to
the HTML style attribute that specifies inline
styles. Instead of referring to a simple string, however, the
style property refers to a Style object that has
properties corresponding to each of the CSS attributes of the style.
e has a
style attribute that specifies the CSS
color attribute, you can query the value of that
attribute as e.style.color. When a CSS attribute
name contains hyphens, the corresponding JavaScript property name
removes the hyphens and uses mixed-case capitalization. Thus, to set
the background-color CSS attribute of an element
e, you set e.style.backgroundColor. There is one
special case: the CSS float attribute is a
reserved word in JavaScript, so the corresponding JavaScript property
is cssFloat.
position property is set
to absolute, you can use the
top and left properties to
specify the absolute position (in pixels, percentages, or other
units) of the document element. Similarly, the
width and height properties
specify the size of the element. The visibility
property can initially be set to hidden to make a
document element invisible, and then dynamically set to
visible to make the element appear when
appropriate.
left and
width which represent numbers. When setting these
length and dimension properties, be sure to convert your numbers to
strings and to add the appropriate units specification (usually the
string px for pixels.) The following table
summarizes these positioning and visibility properties:
|
Handler
|
Supported by/Triggered when
|
|---|---|
onabort |
<img>; image load aborted |
onblur |
<body> and form elements; window or element
loses keyboard focus
|
onchange |
Form elements; displayed value changes
|
onclick |
All elements; mouse press and release; return
false to cancel
|
ondblclick |
All elements; mouse double-click
|
onerror |
<img>; image loading fails |
onfocus |
<body> and form elements; window or element
gets keyboard focus
|
onkeydown |
<body> and form elements; key pressed;
return false to cancel
|
onkeypress |
<body> and form elements; key pressed and
released; return false to cancel
|
onkeyup |
<body> and form elements; key released |
onload |
<body>, <frameset>,
<img>, <iframe>,
<object>; document, image, or object
completely loaded
|
onmousedown |
All elements; mouse button pressed
|
onmousemove |
All elements; mouse pointer moved
|
onmouseout |
All elements; mouse moves off element
|
onmouseover |
All elements; mouse moves over element; return
true to prevent link URL display in status bar
|
onmouseup |
All elements; mouse button released
|
onreset |
<form>; form reset requested; return
false to prevent reset
|
onresize |
<body>, <frameset>;
window size changes
|
onsubmit |
<form>; form submission requested; return
false to prevent submission
|
onunload |
<body>, <frameset>;
document unloaded
|
onclick, onmouseover and
onsubmit, it examines the return value of the
handler (if there is one) to determine whether it should perform the
default action associated with the event or not. Typically, if an
event handler returns value property of the
FileUpload form element.
mailto: or
news: URLs without user confirmation.
about: URLs, such as
about:cache.
|
Anchor
|
A named position in a document
|
|
Applet
|
A Java applet
|
|
Arguments
|
The arguments of a function
|
|
Array
|
Array creation and manipulation
|
|
Attr
|
An attribute of a document element
|
|
Boolean
|
A wrapper object for boolean values
|
|
Comment
|
An HTML comment
|
|
DOMException
|
Signals DOM errors
|
|
DOMImplementation
|
Creates documents, checks DOM features
|
|
Date
|
Manipulates dates and times
|
|
Document
|
An HTML document
|
|
DocumentFragment
|
Nodes to be manipulated together
|
|
Element
|
An HTML tag in a document
|
|
Error
|
Predefined exception types
|
|
Event
|
Event details
|
|
Form
|
An HTML input form
|
|
Function
|
A JavaScript function
|
|
Global
|
Global properties and functions
|
|
History
|
Browsing history
|
|
Image
|
An HTML image
|
|
Input
|
A form input element
|
|
Layer
|
An independent document layer
|
|
Link
|
An
<a> or <area>
link
|
|
Location
|
Current browser location
|
|
Math
|
Mathematical functions and constants
|
|
Navigator
|
Information about the browser
|
|
Node
|
A node in a document tree
|
|
Number |
Return to JavaScript Pocket Reference