Java Script Reference
What is Java Script ?
Important uses
What can JS do?
Limitations
How to trigger action
Events list
Document Object Model
Reuseable structures
Syntax reference
Standard JS Objects
Window & Document Objects
Other Html tags and properties
Reuseable code structures
function functionName()
{
;
return;
}
if ()
{
;
}
if ()
{
;
}
else
{
;
}
switch ()
{ case :
;
break;
case :
;
break;
default:
;
} // end switch
while ()
{
;
} // break , continue (next)
do {
;
}
while (); // break , continue (next)
for (init; test; update)
{
;
} // break , continue (next)
for (variable in object)
{
;
} // break , continue (next)
with(objectName)
{
;
}
// saves repeating object name
Usage guide, tips, and reference
What is Java Script?
JavaScript is a programming language that can be embedded in an Html document, and then executed by a client's browser, to provide dynamic action on a Web page. (Without calls to the server.)
Other languages (such as VBscript) can be used within Html, but they rarely are. JavaScript has many capabilities found in other object-oriented languages. But JS is more forgiving - for example you do not have to (and in fact can't..) specify data types, and conversion between types is automatic.
JS can be inserted into Html as small, disconnected pieces or as large, self contained blocks of code.
Important uses
JavaScript ( embedded in an Html file that is running on a browser) empowers Html pages to DO much more than just sit there on the user's PC screen. JS lets you - the Web programmer - respond to the user and to the operating environment. JS can be used to ......
Validate form fields before passing them to the server.
Communicate with the user when needed.
Control the browser or access its information.
Direct or prevent certain user actions.
Handle error conditions as they occur.
Run animation (or control any programmable function) using a "timer" to start, run, and stop.
What else can JS do?
Communicating with the user includes:
Sending messages or data to the user via the standard "print()" function, or in the browser's status bar, or in an "alert box" - which waits for the user to click "ok".
Giving the user some control via the "confirm box" - which lets the user "ok" or "cancel" an action before you do it.
Getting input data from the user via the "prompt box".
Helping the user make good decisions by providing additional information as it is needed. For example, telling them where a link is going to go before they click it, or warning them of the size of images they are about to load.
Directing user actions includes:
Drawing their attention to a specific area of a Web page by highlighting it. ( Changing its color, size, or background. Or by placing the cursor on the item - which is called "focusing".)
Delaying or denying a user's request to link out of the page until they complete certain tasks that you consider important - like completing a form.
Controlling the browser includes:
Forcing it to open a new window, and then filling it with whatever you wish.
Asking the browser (which is running your JS code) for information such as what version number it is, what kind of computer operating system you're loaded in, and much more.
Generating additional Html tags or text content (that was not in the original code), and having it display before, during, or after the normal page loads. It's even possible to use Java Script to generate ALL the Html right there in the client's browser. So you could only generate code that you know will work on the current OP system and browser!
With JavaScript, you can .....
Examine any Html tag or attribute on the page and get its value or content. You can also find out where the mouse is located, if it has been clicked or not, and whether or not the user has typed something on the keyboard. (These user actions are called events or event triggers.)
Change any Html tag contents or attribute value. (Text color, size, which "img src" to load, and much more.)
Limitations
Most browsers will run basic JavaScript. But a modern browser (Netscape 6.0 or Explorer 5.5) is required to use certain features, such as dynamic positioning of Html elements via JS and CSS (cascading style sheets). Note - this powerful combination of Html, Css, and JS is called Dhtml (dynamic Html).
How to trigger action
Java Script that is coded "in line" - within the Html head or body but NOT within a JS function definition - is immediately executed as the Html file is loaded.
JS that is coded inside a function definition is executed later if and when called.
Function calls, and other JS actions, are initiated by "onEvent" triggers which are embedded inside Html tags like this.....
(tagName onEvent = " functionName (parameters) ; " ) ... calls a JS function
(tagName onEvent = " attribute = ' newValue ' ; " ) .... changes the current tag attribute
(tagName onEvent = " tag.attribute = ' newValue ' ; " ) .... changes another tag's attribute
In all 3 examples above, the double quotes enclose a valid JS statement, which is always ended with a semicolon. The quotes could in fact contain several JS statements.
Events list
Any event can be used to trigger any JS action,
although some combinations are more useful.
I tried to test all these in Netscape 4.7 and Explorer 5.0.
Those marked with * worked in both.
Event Valid in tag... Means (Possible usage?)....
onAbort (img) Loading interrupted
onBlur * (body = document) Window has been de-selected
* (form) + (Text, ) Element de-selected
(TextArea, Select)
onFocus * (body= document) Window is now selected
* (form) + (T,TA,Sel ) Element selected
onChange (form) + (T,TA,Sel ) Value of element changed
(select) + (option ) Menu changed
onClick * (a href = link) Down and up
(button) ""
onDblClick (button) ""
(body? = document) ""
(img) ""
onError (img) Can't load
(body=document)
onKeyDown (form) + (input) ?
(.... following 2 events detectable in Explorer ...)
(.... only if form field is selected first ...)
onKeyPress * (form) + (input) ?
onKeyUp * (form) + (input) ?
onLoad * (body) Window content is loaded
(img) Image is loaded
onUnLoad * (body)
(img) How?
onMouseDown * (a href = link) Mouse pressed down
* (img) ""
(? document) ""
(button) ""
onMouseUp * (a href = link) Mouse released
* (img) ""
(? document) ""
(button) ""
onMouseOver * (a href = link) Mouse placed over
(img) ""
(area) ""
onMouseOut * (a href = link) Mouse moved off
(img) ""
(area) ""
onReset (form) User clicked reset button
..( confirm this !! )
onSelect (form) + (T,TA,Sel)
onSubmit (form) User clicked submit button
Document Object Model
JS can be used to examine or change any Html tag attribute. There are 2 basic ways to specify which attribute to access....
By assigning your own unique name to each tag you wish to reference with JS later, EG...
( tagName name=" uniqueName " )
Or you can use the generic name that is automatically predefined for every tag as the Html file loads. These predefined names make each tag programatically accessible as an "object" - some with predefined "methods" that you can call and use. These objects "model" the document as follows.......
<<..... Window ....>>
(assumed)
V V V V V
V V V V V
Document Frame[] Location History Navigator
(HTML body) (doc URL) (back, fwd) (browser name...)
V V V
V Plugin Mime-type
V
Anchor[] (a href links)
Applet[]
Area[]
Image[]
Layer[] (old way to position page elements)
Link[] (to external CSS files)
Plugin[]
Form[] -------->Button
Checkbox
File (upload)
Hidden
Password
Radio
Reset
Select ---------> Option
Submit
Text
TextArea
Think of this as a system for addressing mail, with "Document" = the country, "Anchor, Applet..." =the state, and "button, Checkbox.." = individial cities. To send mail, you have to specify all 3 pieces of information, with the country first, then state, then city - separated by a decimal point.
Let's assume you have the following Html form ...
(form name="myForm")
(input type="text" name="textField1" )
You can extract the field's content (or "value" ) with any of these JS statements....
X = document . myForm . textField1 . value ;
X = this . myForm . textField1 . value ;
X = document . form . textField1 . value ;
X = document . form[0] . textField1 . value ;
X = document . myForm . elements[0] . value ;
To change the value, simply turn the statement around .....
document . myForm . textField1 . value = X ;
After executing this statement, the browser automatically refreshes the screen.
Syntax reference
This reference list only the most commonly used syntax.
---------- Std JS functions --------------
isNaN(string) Not a number (0-9?)
encodeURI(string) Replaces space with %20, etc.
parseFloat(string)
parseInt(string)
variable . toString()
object . valueOf()
(others...)
---------- Operator precedence --------------
() []
! -var ++ -- (logical not, negate, increment)
* / % (% = modulus = divide and return remainder)
+ -
< > <= >= (compare)
== !=
&& || (logical and, or )
= (assign)
+= -+ *= /* %= (shortcuts)
---------- Special chars ( escape sequences)--------------
\n new line - CR + LF
\t tab
\' single quote
\" double quote
(others...)
--------------------------------------------------------------------------------
Objects, properties, and methods
Objects provide much of the power of JS.
Any property (variable) listed below can be accessed or changed.
Methods provide "ready to call " functions .
----- Std JS Objects List-----
Array create
Boolean create
Date manipulation
Error returns info
Function creates as object
Global JS built in methods
Math calculations
Number manipulating
Object common functions for std JS objects
RegExp find & replace text in strings
String manipulating
------------------- Std JS Objects Details -----------------------
Array
Array methods .............
concat() combine 2 arrays to 1
join() combine all elem into string
pop() remove & return last elem
push() add (at end) & return
reverse() elem seq
shift() remove & return 1st elem
slice() create new array from a section
splice() add or remove elem
sort()
unshift() add new elems to start, and
return new length
Array properties..........
array . length number of elements
Boolean create
methods .............
?() ?
properties..........
? . ? ?
Date manipulation
methods .............
getDate() from a date object
setDate() into a date object
toString() converts to a string
.... Many others exist ....
properties..........
? . ? ?
Error returns info
methods .............
?() ?
properties..........
? . ? ?
Function creates as object
methods .............
?() ?
properties..........
? . ? ?
Global JS built in methods
methods .............
?() ?
properties..........
? . ? ?
Math calculations
methods .............
math . abs(x)
math . ceil(x) round up to next int
math . floor(x) round down to next int
math . max(x,y)
math . min(x,y)
math . pow(x.y) x to y power
math . random() returns random number
math . round(x) to nearest int (up or down)
math . sqrt(x)
math . ?() ?
properties..........
math . PI constant
Number manipulating
methods .............
number . toString()
properties..........
number . NaN not a number
Object common functions for std JS objects
methods .............
?() ?
properties..........
? . ? ?
RegExp find & replace text in strings
methods .............
?() ?
properties..........
? . ? ?
String manipulating
methods .............
string . big() adds (big) (/big) to a string
string . bold() adds ()(/)
string . charAt(index) returns char at that position
string . fontcolor(color) adds ()(/)
string . fontsize(size) adds ()(/)
string . indexOf(text, index) returns position of 1st char in text arg
or -1 if not found, starting search at index
string . lastIndexOf(text, index) same, exc returns last posn
string . link(href) adds ()(/)
string . small() adds ()(/)
string . split(separator) breaks text into an array
string . substring(start, end+1) extract part of string
string . toLowerCase()
string . toUpperCase()
properties..........
string . length # of chars
Window & Document Objects
These have a heirarchical structure, listed here ALPHABETICALLY.
See structural chart elsewhere in this doc.
Note that in some cases (anchor[], applet[], ...) the object name is singular,
but the property name (document.anchors[], etc.) the name is plural.
document . ANCHOR[] array lists your (a href) links
document . APPLET[]
document . AREA[]
document . form[] . BUTTON
document . form[] . CHECKBOX
DOCUMENT your Html file
document . form[] . FILE to upload to server
document . FORM[]
FRAME []
document . form[] . HIDDEN
HISTORY back, forward
document . IMAGE[] lists your images
document . LAYER[] old way to position page elements
document . LINK[] to external Css files
LOCATION where your Html came from
navigator . MIMETYPE
NAVIGATOR browser name, version
document . form[] . select . OPTION
document . form[] . PASSWORD
document . PLUGIN
navigator . PLUGIN
document . form[] . RADIO
document . form[] . RESET
document . form[] . SELECT
document . form[] . SUBMIT
document . form[] . TEXT
document . form[] . TEXTAREA
WINDOW the top object, name assumed
----- Window & Document Objects Details -----
These have a heirarchical structure, listed here ALPHABETICALLY.
See structural chart elsewhere in this doc.
document . ANCHOR[] array lists your (a href) links
methods .............
?() ?
properties..........
? . ? ?
document . APPLET[]
methods .............
?() ?
properties..........
? . ? ?
document . AREA[]
methods .............
?() ?
properties..........
? . ? ?
document . form[] . BUTTON
methods .............
?() ?
properties..........
? . ? ?
document . form[] . CHECKBOX
methods .............
?() ?
properties..........
? . ? ?
DOCUMENT your Html file
methods .............
document . close() tell browser I'm finished writing to doc, now display it
document . getElementById() returns the Html element
document . getElementsByName() returns array
document . open() new window (now use write, writeln)
document . write()
document . writeln() with CR, LF
properties..........
document . anchors[]
document . applets[]
document . body contains ALL the content
document . cookie current cookie string
document . domain server my doc came from
document . forms[]
document . images[]
document . lastModified of current document
document . links[]
document . referrer use to go Back
document . title of curr doc
document . URL where curr doc came from
document . form[] . FILE to upload to server
methods .............
?() ?
properties..........
? . ? ?
document . FORM[]
methods .............
form . reset() done from JS
form . submit() done from JS
properties..........
form . action URL to submit to
form . method get or post
form . encoding MIME specified by endtype attribute
form . enctype the data format to submit
form . target window to receive results from server
form . name identifies the form
form . elements[]
form . length number of elements
FRAME []
methods .............
?() ?
properties..........
? . ? ?
document . form[] . HIDDEN
methods .............
?() ?
properties..........
? . ? ?
HISTORY back, forward
methods .............
history . back() Go back
history . forward() Go forward
history . go() to specified doc
properties..........
history . length # of docs opened during curr browser session.
document . IMAGE[] lists your images
methods .............
?() ?
properties..........
image . border Read only - width in Px
image . complete true when loaded
image . height read - only
image . hspace read - only Px to L and R
image . lowsrc URL of lo res alternate image
image . name to access via JS
image . src Url
image . vspace read-only PX above and below
image . width read-only
document . LAYER[] old way to position page elements
methods .............
?() ?
properties..........
? . ? ?
document . LINK[] to external Css files
methods .............
?() ?
properties..........
? . ? ?
LOCATION where your Html came from
methods .............
location . reload() force reload of self
location . replace() replace self with new page
properties..........
location . hash a Url's anchor
location . host hostname & port
location . hostname
location . href full Url
location . pathname directory path
location . port
location . protocol Http, Smtp, Ftp
location . search query string
navigator . MIMETYPE
methods .............
?() ?
properties..........
? . ? ?
NAVIGATOR browser name, version
methods .............
navigator . javaEnabled()
properties..........
navigator . appCodeName
navigator . appName
navigator . appVersion
navigator . platform
navigator . userAgent
document . form[] . select . OPTION
methods .............
?() ?
properties..........
? . ? ?
document . form[] . PASSWORD
methods .............
?() ?
properties..........
? . ? ?
document . PLUGIN
methods .............
?() ?
properties..........
? . ? ?
navigator . PLUGIN
methods .............
?() ?
properties..........
? . ? ?
document . form[] . RADIO
methods .............
?() ?
properties..........
? . ? ?
document . form[] . RESET
methods .............
?() ?
properties..........
? . ? ?
document . form[] . SELECT
methods .............
?() ?
properties..........
? . ? ?
document . form[] . SUBMIT
methods .............
?() ?
properties..........
? . ? ?
document . form[] . TEXT
methods .............
?() ?
properties..........
? . ? ?
document . form[] . TEXTAREA
methods .............
?() ?
properties..........
? . ? ?
WINDOW the top object, name assumed
methods .............
alert(text) box with OK button. Click returns true
blur() removes focus from window
clearInterval() cancels a setInterval()
clearTimeout() calcels a setTimeout()
close() my window
confirm(text) Ok and cancel. Ok returns true, else false
focus() makes window active
open() new window
prompt() box to enter info. OK returns default,
Cancel returns null.
setInterval(MS) repeats a function every MS = milliseconds
setTimeout() executes function once after waiting MS
properties..........
window . defaultStatus default text written to status bar
window . document
window . frames[]
window . history
window . location
window . name to access via Js
window . opener object that opens windows
window . parent frame that contains mine
window . self self reference
window . status temp text to status bar
window . top topmost window that contains curr frame
window . window self reference
---------------- end Objects, properties, and methods ----------------
Other Html tags and properties
Only commonly used tags and attributes are listed.
Most attributes should be accessible by JavaScript.
Tag Attributes (ALL CAPS = REQUIRED)
-ALL- id class style
a href name target
applet height width
body background bgcolor text
button name type value
div align
font color face size
form ACTION method name target
h1-6 align
head
hr align size width
img align ALT border height SRC width
input (varies with type)
li value
meta CONTENT name
p align
script language src TYPE
select multiple name size
span
textarea COLS name ROWS
table align bgcolor border cellpadding cellspacing width
tr align bgcolor valign
td align bgcolor colspan height rowspan valign