*These notes are based on information taken from random sources on the Internet, and O'Reilly's excellent guide to Javascript (not really for absolute beginners). - 9/1/2024 |
Javascript is case-sensitive, HTML is not. Javascript event
handlers that have become part of HTML (like onclick
) are not case-sensitive
in the context of an HTML tag;
Javascript ignores spaces, tabs, and newlines appearing between tokens;
Simple statements in Javascript are terminated by the semicolon (;) ;
Javascript will occassionally insert a semicolon after a line break, if it thinks one should be there;
Comment with //
for a single line, and /*
... */
for several lines;
To hide Javascript from a browser that can't handle it,
start with <!--
and end with //-->
;
A literal is any data value appearing directly in a script;
An identifier is the title of a variable or function. The first character must be an underscore, dollar sign, or letter. Identifiers cannot match a reserved Javascript keyword (see pg. 32);
Chapter 3 - Data Types and Values
Primitive data type: number, string, boolean value. Composite data type: array, object;
In Javascript, all numbers are floating-point values;
The Math
object stores all complex math
functions [eg, Math.sin(x)
]. Otherwise, use +
, -
,
*
, and /
as usual;
toString(x)
converts a number to a string. x
is the radix; eg, hexadecimal = x = 16;
numbers larger or smaller than the max allowable = Infinity
or -Infinity
. Undefined results (eg, 0/0) result in NaN
.
Nothing equals NaN
, including itself [so you must detect it
with isNan()
];
The backslash, when placed before another character,
represents a character that is not otherwise representable within a string
(eg, '
can then be used as a literal apostrophe). Other special
chars include: \b
(backspace), \f
(form feed), \n
(newline), \r
(carriage return), \t
(tab), \"
(double quote), \\
(backslash);
Concatenate strings with the +
operator;
Access the length of a string with varname.length
;
Access a specific character in a string with varname.charAt(position)
;
Extract part of a string with varname.substring(position1,position2)
.
Note - strings are indexed starting with zero;
Find the position of a letter in a string with varname.indexOf(position)
;
The two legal boolean values are string literals true
and false
;
To define a function:
function varname(arg) {
return code_block;
}
Functions can be stored in variables, arrays, and objects, and can be passed as arguments to other functions;
A function literal looks exactly like a function, minus the
function name (eg, var varname = function(arg) { return code_block;
} . Functions defined this way are called "lambda" functions;
Create an object with: varname = new function()
;
Create an array with: varname = new Array()
;
followed by: varname[0] = value1
; varname[1]
= value2
; etc... or varname = new Array (value1,
value2,...)
;
The keyword null
indicates that a variable does
not contain a valid data type;
The keyword undefined
indicates that a variable
has no value or does not exist. This is different from null
,
but they are generally considered equal;
To use the Date object: varname = new Date(year,
month, day)
;
var varname = varvalue
.
Combine variable declaration by putting commas between varname
= varvalue
statements. If you drop the var
keyword, a variable is automatically declared as a global variable;x
, then put x
into y
, y
will keep that initial
value even if you later change x
. Composite data types
work through references, so it doesn't work that way for them; this
can be used to refer to the global object
(as well as window
);Chapter 5 - Expressions and Operators
An expression is a phrase of Javascript that can be evaluated to produce a value. The simplest expression is a literal. More complex expressions involve operators;
A unary operator converts one expression to another. A binary operator combines two expressions. A ternary (condition) operator brings three expressions together in an if/then sort of way;
Table of operators (* = Javascript 1.2 ** = only IE):
Operator | Operand Type | Operation Performed |
++ |
number | pre-or-post increment (unary) |
-- |
number | pre-or-post decrement (unary) |
- |
number | negation |
! |
boolean | invert value |
delete* |
variable | undefine a property (unary) |
new |
constructor call | create new object (unary) |
typeof |
any | return data type (as a string) |
void |
any | return value undefined
(unary) |
== |
any | test for equality |
!= |
any | test for inequality |
===** |
any | test for identity |
!==** |
any | test for non-identity |
& |
integers | AND |
^ |
integers | XOR |
| |
integers | OR |
&& |
booleans | logical AND |
|| |
booleans | logical OR |
?: |
boolean, any, any | conditional (ternary) operator |
% | numbers | modulo (returns remainder) |
, |
any | multiple evaluation |
"1" = true
would
result in true, even though 1 is in quotes;++
or --
are used as post-increment
operators, they increment the operand, but evaluate to the un-incremented
value (eg, if i = 1, j = i++
, then i = 2 and j = 1);==
, note that (in the case of arrays and objects)
two variables are equal only if they refer to the same object or array. In
other words, two different arrays containing the same elements would come up
unequal;==
resolves null
and undefined
as
equal;<
, <=
, >
, and >=
,
note that all capital letters come before lowercase letters, so that "Zoo"
< "ant"
evaluates to true
;&&
operates by checking if the
left-hand operand is false. If so, it returns the evaluation of the
left-hand operand. If not, it returns the evaluation of the
right-hand operand;||
operates by checking if the
left-hand operand is true. If so, it returns the evaluation of the left-hand
operand. If not, it returns the evaluation of the
right-hand operand;+=
adds the right-hand operand to the left-hand operand, then
assigns the new value to the left-hand operand (eg, total += sales_tax
is equivalent to: total = total + sales_tax
);?:
) as follows: expression1
? expression2 : expression3
(or, if exp1
then exp2 else exp3
);The delete
operator is used to destroy an object property or array element
(eg, delete my.birthday
);
void
operator is used to create an undefined value, since
there is no undefined keyword (eg, void 0
);if/then/else
works as follows: if (expression)
{code_block} else {code_block2}
. You can also use else
if
as many times as necessary;
the Javascript switch
statement works like the
ASP select
statement:
switch (expression) {
case (value):
code_block
break;
(note
- this is optional; it causes the switch loop to end if this value matches
the expression)
default:
(note -
this is optional; it is executed if no case value matches the expression)
code_block2
}
Note - Javascript does *not* allow user-defined variables to be used in case labels;
Loops work as follows: while (expression) {statement}
.
You can also use do/while
;
The for
statement works as follows: for(initialize
; test ; increment) {statement}
. Eg, for(count
= 0 ; count < 10 ; count++)
. You can also use: for (varname
in object) {statement}
;
Any statement may be labeled by preceding it with an
identifier name and a colon: labelname: statement
.
This label can then be used to access the statement from anywhere in a
script;
The break
statement ends a loop, while the continue
statementcauses a loop to restart in a new iteration;
The with statement makes it possible to add an object to the
top of the scope chain, thus saving type time: with(object)
{statements}
. Eg, with(frames[1].document.forms[0])
{name.value = ""; address.value = ""}
; etc}. You
can also save time by simply storing object
into a
variable;
The <layer> tag in HTML, when placed around a script, causes it to run in its own context with its own global object;
export varname
or export funcname
makes its target available in other execution contexts (eg, another
window). The import
statement copies the value of an export
target from its source into the new context;
Define a function with: function funcname(arg1,
arg2, ...) {statements}
, or with the new
operator as follows: varname = new function("arg1",
"arg2", "statements")
;
The return
statement ends execution of a function, and
returns a value;
If a function does not contain a return
statement,
it simply executes each statement in the function body and returns the
undefined value to the caller - it cannot meaninfully be used as part of a
larger expression;
Functions can be stored in a variable, then called with that variable (basically, you give the function a second name);
A Javascript function is defined with a fixed number of
arguments, but can be passed any number when invoked. These argument values
can be accessed/assessed through the arguments[]
array (for
example, you could count through all arguments and return the largest). The
arguments object also has a callee
property that refers to the
function being executed. You can use it to recursively invoke an unnamed
function;
The arity
property of a function returns the
number of arguments a function expects to receive. Use the length
property
with the arguments
array if you want the actual arguments
passed (note - arguments
is only available within the function
body). Arity
only functions correctly in Naviagor 4 if the
language attribute of the script is set to "JavaScript 1.2";
The apply
method of the function object allows
you to invoke a function as if it were a method of some other object. Its
first argument is the object on which the function should be invoked - that
object becomes the value of the this
keyword within the
function. Its second argument is an optional array of arguments to be passed
to the function (eg, f.apply(o, [1,2]
). In Navigator 5,
call
serves the same purpose (but the arguments aren't put in []
);
The delete
operator is used to entirely remove a
property from an object;
To create an object with changeable properties and methods:
1) create a constructor function
2) prefix all variables in the function with the this
keyword
3) instantiate the object with that function (eg, var obj_instance =
new func_name(args...)
). Note that func_name
is
effectively the object name;
Every object has a prototype, from which it inherits
properties. These properties can be inherited even if they are added to the
prototype after the object is created. Inheritance occurs only when reading
property values, not writing them. If you set property p
in
object o
as something, you create a new property directly in
o
;
Define the property of a prototype as follows: func_name.prototype.prop_name
= value
;
In Navigator 3, the prototype object is not created until
the constructor function is used for the first time, so instantiate a dummy
object before assigning values to the prototype (eg, new func_name();
);
A class defines the structure of an object. There may be multiple objects (ie instances) of the same class;
Built-in classes have prototypes (just as user-defined classes do), and you can assign values to them. This does not work in IE3;
The constructor
property of an object simply
refers to the function that was used to instantiate the object. For any
function f
, f.prototype.constructor
is always
equal to f
;
The toString
method returns a string that
somehow represents the type and/or value of the object it is invoked on. You
can define custom toString
methods for a prototype, if you
like;
The valueOf
method returns a number, boolean,
or function that somehow represents the value of the object referred to;
Chapter 12 - Javascript in Web Browsers
The Document object represents an HTML document, and the
Window object represents the window (or frame) that displays the document.
The Window object is the global object - you can refer to it with
window
or self
;
An example of the object chain in Javascript (see pg 210):
parent.frames[0].document.forms[0].elements[3].options[2].text
;
How Javascript can be embedded into HTML:
<script>
tags; SRC
or ARCHIVE
attributes
of a <script>
tag (the external file should be a .js
file, and should not contain <script>
tags or HTML in
general). .js files are cached by a browser, so if a script is used on
multiple pages, this technique is nice;onClick
); javascript:
protocol.
Use this where any HTML tag is expecting a URL (eg, a form tag, hyperlink, etc);<style type="text/javascript">
tags (not supported by IE);
&{statement};
This is effectively conditional HTML;<script>
tags may appear in the <body>
or <head>
of an HTML document, and all <script>
tags in a document are
part of the same Javascript program (meaning variables in one are accessible to
another);<script language="Javascript">
, even though
Javascript is usually the default script language of browsers; document.write
the closing tag as <\/script>
- otherwise, it won't work; onLoad
and onUnload
event handlers are defined in
the <body>
or <frameset>
tag of a
document. onLoad
is executed when a document fully loads,
onUnload
executes just before the page is unloaded (when the browser is
told to move on to a new page); onLoad
event handler (eg, window.loaded
= true;
), other event handlers can test this flag to see if they can
safely run;Chapter 13 - Windows and Frames
The alert()
method dispays a message to the
user;
The confirm()
method asks the user to click an
OK or Cancel button to confirm an operation. First, place a string in a
variable, then call that variable with confirm
(resulting in a
boolean value);
The prompt()
method asks a user to enter a
string. The first argument is a message to be displayed to the user, the
second argument will appear within the entry field (use ""
for
no default). Store the method in a variable, which you can then call later
in the script to retrieve the user's input;
The status line at the bottom of the browser can be
controlled with: event_handler="status='string';
return true;"
... the return
statement is used to
make the browser abandon its default action for the event;
defaultStatus
permanently sets the status line
to a certain string value;
The setTimeout()
method schedules a piece of
Javascript to be run at some time in the future. It has two arguments, a
function to be called (which is placed in quotes) and a time (in
milliseconds). clearTimeout()
can be used to cancel the
execution of that function;
setInterval()
and clearInterval()
are
like the timeout methods, except they automatically reschedule the code to
run repeatedly;
Window.navigator
refers to the Navigator
object, which has six properties that describe the user's browser/platform
(see pg 237). Its javaEnabled()
method returns true if the
browser supports Java. Its plugins[]
property is an array that
contains ever plugin the broswer has installed (test through strings?);
The screen
property/object provides information
about the size of the user's display and the number of colors available
(through its availWidth
, availHeight
, and
colorDepth
properties). 256 colors would return a value of 8 (8-bit);
The open()
method is used to open a new window.
Its first argument is the URL of the document to display in the new window
(use null
for empty). Its second argument is the name of the
window. Its third (optional) argument contains a comma-delimited list of
features, including: width,height,status,resizable
. The fourth
argument is a boolean value used if the second argument names an
already-existing window: true
tells the browser to replace the
current entry in the window's browsing history, false
(the
default) creates a new entry;
The close()
method closes a window. The
closed
property is true if the window in question has been closed;
In Javascript 1.2, the moveTo()
method moves
the upper-left corner of the window to the specified coordinates.
moveBy()
moves the window a specified number of pixels left or right
and up or down. resizeTo()
and resizeBy()
resize
the window by an absolute or relative amount;
The focus()
method brings keyboard focus to the
window, while blur()
relinquishes keyboard focus;
scrollBy()
scrolls the document by a specified
number of pixels horizontally and vertically. scrollTo()
specifies
an absolute position;
The location
property refers to the URL of the
document in the window; the href
property of location
contains
the complete text of the URL. Other properties of location include:
protocol
, host
, pathname
, and search
(which
contains any portion of a URL following [and including] a question mark).
Assigning a URL to the location object causes that URL to be loaded by the
browser. Methods of the location object include reload()
, which
reloads the page, and replace()
, which loads and displays a
different URL (also replacing the former URL's entry in the history list,
preventing a user from going back to the old page);
The History object is an array of URLs in the
browsing history of the window. Its back()
and forward()
methods
perform their namesake;
Note - functions are executed within the scope in which they were defined, *not* the scope in which they are invoked;
Chapter 14 - The Document Object Model
The DOM can be used to refer to HTML elements by name or
position. For example, a form named "f1
" can be accessed with:
document.forms[index#]
or document.f1
;
The properties of the Document object are:
Property |
Description |
alinkColor |
color of a link while it is
activated (ALINK attribute of the <body>
tag) |
anchors[] |
array of anchor objects that represent the anchors in the document |
applets[] |
array of applet objects |
bgColor |
background color of the document (BGCOLOR
attribute of the <body> tag) |
cookie |
enables JavaScript to read/write cookies |
domain |
allows mutually trusted web servers within the same internet domain to collaborate |
embeds[] |
array of embedded objects (eg, plugins or ActiveX controls) |
fgColor |
default text color of the document (TEXT
attribute of the <body> tag) |
images[] |
array of image objects |
lastModified |
string containing the modification date of the document |
linkColor |
color of unvisited links (LINK attribute of
the <body> tag) |
links[] |
array of link objects |
referrer |
URL of the document that referred user to the current document |
title |
text within the <title>
tag |
URL |
string specifying the URL from which the document was loaded |
vlinkColor |
color of visited links (VLINK
attribute of the <body> tag) |
<head>
of the
document; write()
method: open()
it, write()
any
number of times, then close()
the document;
open()
with a
single argument (the MIME type desired); elements[]
property of the Form object contains all the
input elements of a form. You can set those elements' default values and
read user input with this property;src
property - can be set to make the
browser load and display a new image in the same space. In such a case, you
will first want to cache the replacement image off-screen. You can do so by
instantiating an Image object and its corresponding image[].src
with
each loop. When it is time to perform the image replacement, simply set the
src
property of the desired on-screen image to the URL of the of the
desired image;onLoad
event handler - invoked when the image is fully
loaded; onError
event handler - invoked when an error occurs during
the image loading process; onAbort
event handler - invoked when the user cancels the
image load; complete
property - is false while the image is loading; Chapter 15 - Events and Event Handling
Event Handler | Trigger | Object(s) supported by |
onAbort |
loading interrupted | Image |
onBlur |
element loses input focus | all elements, Window |
onChange |
user selects or deselects an item, or enters text and moves input focus to another element | Select, text input elements |
onClick |
user clicks once. Return false
to cancel default action (eg, follow link, submit...) |
Link, button elements |
onError |
error occurs while loading image | Image |
onFocus |
element given input focus | all elements, Window |
onKeyDown* |
key pressed by user. Return false to cancel |
Document*, Image*, Link*, text elements |
onKeyUp* |
key released by user. Return false
to cancel |
Document*, Image*, Link*, text elements |
onLoad |
document or image finishes loading | Window, Image |
onMouseDown* |
user presses mouse button | Document, Image, Link, button elements* |
onMouseOut |
mouse moves off element | Link, Image*, Layer* |
onMouseOver |
mouse moves over element. For links,
return true to prevent URL from appearing in status bar |
Link, Image*, Layer* |
onMouseUp |
user releases mouse button. Return false to
cancel |
Document, Link, Image, button elements* |
onReset |
form reset requested. Return false
to prevent |
Form |
onResize |
window is resized | Window |
onSubmit |
Form submission requested. Return false
to prevent |
Form |
onUnload |
Document is unloaded | Window |
DHTML is a loosely defined term comprising several technologies: the Document Object Model (DOM), the extended event model, cascading style sheets (CSS), and absolute positioning of HTML elements;
CSS styles are specified as a semicolon-separated list of name/value
attribute pairs, with each name/value separated by colons. The list is
associated with an HTML attribute, or with a class or ID name. In the later
case, the style then applies to any HTML element with a CLASS
attribute set to that name, or to a unique HTML element with its ID
attribute set to that name. Style sheets are imported into an HTML document
with the <link> tag;
In Navigator, CSS can be referred to through Javascript with the tags
,
classes
, and ids
properties of the Document
object;
In IE, CSS can be referred to through the styleSheets[]
array of the Document object. Each element of this array is a StyleSheet
object, and contains a rules[]
array (which allows you to
access each rule) and an addRule()
method (which allows you to
create new rules). In IE (unlike Netscape) you can access inline styles by
setting the style
property of an HTML element within a
document;
CSS-P allows absolute positioning of HTML elements simply by defining a
few more CSS properties that can be set, including (most importantly) the position
property, which can be set to absolute (or relative). First, you set the position
property for an element. Next, you set the left
and top
properties (a number, followed by "px" or "in"), and
optionally, the visibility
and z-index
(zOrder
in IE) properties (the latter specifies the stacking order of elements). CSS-P
works best with inline styles, usually as an attribute to an HTML grouping
tag such as <span>
, <div>
, or any
other element that has an opening and closing tag (since Netscape 4 can't
apply it to tags that don't have a closer). Note - the span tag is much like
div, except that it doesn't force a line break;
To dynamically position elements in IE, simply change the value of a
position property (eg, left
, visibility
, etc)
through the style
object (eg, document.all.p23.style.left
= "2.24in";
);
To dynamically position elements in Netscape, place the elements in a <layer>
,
then position that layer with the position properties (after having first
set the elements' position
style set to absolute
).
The layer can be referred to through the layers[]
array, or
through the ID assigned to a layer (eg, document.L2
or
document.layers[1]
). The Layer object has a document
property of its own, through which its elements are accessed (eg, document.L2.document
...).
The moveBy() and moveTo() methods can be used to move a layer. The
visibility property is set to either "show" or "hide"
(unlike in IE)