JavaScript Reference

Data Types

Numeric
     integer
     floating-point
String
Boolean(true|false)

Variables

var variableName

Operators

Arithmetic Operators

Operator

Action

+

Adds two values together

-

Subtracts one value from another or changes a value to its negative

*

Multiplies two values together

/

Divides one value by another

%

Produces the remainder after dividing one value by another

++

Increments a numeric value by 1 (adds 1 to it)

--

Decrements a numeric value by 1 (subtracts 1 from it)

+=

X += Y
The equivalent of
X = X + Y: add Y to X, replacing the value of X

-=

X -= Y
The equivalent of
X = X - Y: subtract Y from X, replacing the value of X

*=

X *= Y
The equivalent of
X = X * Y: multiply Y by X, replacing the value of X

/=

X /= Y
The equivalent of
X = X / Y: divide X by Y, replacing the value of X

Conditional Operators

Conditional
Operator

Comparison

==

Equal operator.
value1 == value2
Tests whether
value1 is the same as value2.

!=

Not Equal operator.
value1 != value2
Tests whether
value1 is different from value2.

<

Less Than operator.
value1 < value2
Tests whether
value1 is less than value2.

>

Greater Than operator.
value1 > value2
Tests whether
value1 is greater than value2.

<=

Less Than or Equal To operator.
value1 <= value2
Tests whether
value1 is less than or equal to value2.

>=

Greater Than or Equal To operator.
value1 >= value2
Tests whether
value1 is greater than or equal to value2.

Logical Operators

Logical
Operator

Comparison

&&

And operator.
condition1 && condition2
The
condition1 and condition2 tests both must be true for the expression to be evaluated as true.

||

Or operator.
condition1 || condition2
Either the
condition1 or condition2 test must be true for the expression to be evaluated as true.

!

Not operator.
! condition
The expression result is set to its opposite; a true condition is set to false and a false condition is set to true.

String Operators

Operator

Action

+

Concatenates two string variables or literals


Objects

Array Object

var array_name = new Array()

Array Methods

Method

Description

sort()

Sort an array in ascending or descending sequence:

array.sort(function(a,b){return a-b}) - descending
array.sort(function(a,b){return b-a}) - ascending


join(["separator"])

Join elements of array into string separated by separator.

 

slice(start,end)

Return a subset of elements of an array beginning with element start and ending at (but not including) element end.

 

splice(start,n)

Remove elements from array beginning at element start and including n elements.

 

toString()

Convert array to comma-separated string of element values.

 

split(["separator"])

Split a string into separate array elements at the separator character.

  NumberString = "10,13,23,25,36,47,54,75,80,85"
  MyArray = NumberString.split(",")


Image Arrays

var array = new Array()

array[n] = new Image()
array[n].src = "picture.gif"

Date Object

var date_variable = new Date()

Date Methods

Method

Description

getDate()

Returns the day of the month.
   TheDate.getDate()

getDay()

Returns the numeric day of the week (Sunday = 0).
   TheDate.getDay()

getMonth()

Returns the numeric month of the year (0 = January).
   TheDate.getMonth()

getYear()
getFullYear()

Returns the current year.
   TheDate.getYear()
   TheDate.getFullYear()

getTime()

Returns the number of milliseconds since January 1, 1970.
   TheDate.getTime()

getHours()

Returns the military hour of the day.
   TheDate.getHours()

getMinutes()

Returns the minute of the hour.
   TheDate.getMinutes()

getSeconds()

Returns the seconds of the minute.
   TheDate.getSeconds()

getMilliseconds()

Returns the milliseconds of the second.
   TheDate.getMilliseconds()

toTimeString()

Converts the military time to a string.
   TheDate.toTimeString()

toLocaleTimeString()

Converts the time to a string.
   TheDate.toLocaleTimeString()

toDateString()

Converts the date to an abbreviated string.
   TheDate.toDateString()

document Object

document Properties

Property

Description and Setting

bgColor

The color of the document background (read/write).
  document.bgColor = "Red"

fgColor

The color of the document text -- foreground color (read/write).
  document.fgColor = "#000000"

title

The title appearing in the <title> tag of the current document (read-only).

referrer

The URL of the document from which the user linked to the current document by clicking an <a href> link (read-only).

lastModified

The date on which the current document was last changed (read-only).

linkColor

The color of text for a link that the user has not yet visited (read/write).
  document.linkColor="Blue"

vlinkColor

The color of text for a link that the user has already visited (read/write).
  document.vlinkColor="#008000"

alinkColor

The color of text for a link that the user clicks (read/write).
  document.alinkColor="Orange"

document.body Properties

Property

Description and Setting

background

The URL of the background image for the document, if any (read/write).
  

bgProperties

Indicates whether the background image for the document is fixed or scrolls with the page content. A scrolling background image is the default and is set by an empty string (document.body.bgProperties="").
  

topMargin

The number of pixels of white space at the top of the document (read-only).

rightMargin

The number of pixels of white space on the right of the document (read-only).
 

bottomMargin

The number of pixels of white space at the bottom of the document (read-only).

leftMargin

The number of pixels of white space on the left of the document (read-only).

innerText

The text (but not the XHTML) on the page (read/write).

 

innerHTML

The text, including the XHTML, on the page (read/write).

 

clientWidth

The width in pixels of the viewable area of the document (read-only).
 

clientHeight

The height in pixels of the viewable area of the document (read-only).

scrollWidth

The width in pixels of the scrollable area of the document. Same as clientWidth if no horizontal scroll bar is present (read-only).

scrollHeight

The height in pixels of the scrollable area of the document. The full height of the document within the window (read-only).

scrollLeft

The number of pixels by which the document is scrolled horizontally to the left (read/write).

scrollTop

The number of pixels by which the document is scrolled vertically from the top of the document (read/write).

document Methods

Method Description
close()
Closes the specified document.

open() Opens the specified document.

write() Writes to the specified document.

document.getElementById("id") Creates an element reference through element id

Form Object

Checkbox Properties and Event Handlers

Property

Description

length

The number of checkboxes with the same name.


checked

A true or false value indicating whether a box is checked.


status

A true or false value indicating whether a box is checked.


value

The value attribute coded for a checkbox.


Event Handler

Description

onFocus

The control gains focus.


onBlur

The control loses focus.


onClick

The checkbox is clicked.


Drop-Down List Methods and Event Handlers

Property

Description

length

The number of options in the list.

 

selectedIndex

The index number, beginning with 0, of the selected option.

 

options[]

An array of the options in the list. Used to reference properties associated with the options; e.g., options[1].value or options[2].text.

 

selected

A true or false value indicating whether an option is chosen.

 

value

The value associated with an option. In the absence of a coded value attribute, the text label associated with the option.

 

text

The text label associated with an option.

 

Event Handler

Description

onFocus

The control gains focus.

 

onBlur

The control loses focus.

 

onChange

A different option from the one currently displayed is chosen.

 

Radio Button Properties and Event Handlers

Property

Description

length

The number of radio buttons with the same name.

 

checked

A true or false value indicating whether a button is checked.

 

status

A true or false value indicating whether a button is checked.

 

value

The value attribute coded for a button. A checked button with no assigned value is given a value of "on".

 

Event Handler

Description

onFocus

The control gains focus.

 

onBlur

The control loses focus.

 

onClick

The button is clicked.

 

Textbox and Textarea Methods and Event Handlers

Method

Description

blur()

Removes focus from the field; does not permit text entry in the control.

 

focus()

Assigns focus to the field; places the cursor in the control.

 

select()

Selects, or highlights, the contents of the control.

 

Event Handler

Description

onBlur

The field loses focus when the user tabs from or clicks outside the control.

 

onFocus

The field gains focus when the user tabs into or clicks inside the control.

 

onChange

The field loses focus after the contents of the control have changed.

 

Math Object

Math Methods

Method

Description

Math.abs(expression)

Returns the absolute (non-negative) value of a number:
   Math.abs(-100)

Math.max(expr1,expr2)

Returns the greater of two numbers:
   Math.max(10,20)

Math.min(expr1,expr2)

Returns the lesser of two numbers:
   Math.min(10,20)

Math.round(expression)

Returns a number rounded to nearest integer (.5 rounds up):
   Math.round(1.25)
   Math.round(1.50)
   Math.round(1.75)

Math.ceil(expression)

Returns the next highest integer value above a number:
   Math.ceil(3.25)
   Math.ceil(-3.25)

Math.floor(expression)

Returns the next lowest integer value below a number:
   Math.floor(3.25)
   Math.floor(-3.25)

Math.pow(x,y)

Returns the y power of x:
   Math.pow(2,3)

Math.sqrt(expression)

Returns the square root of a number:
   Math.sqrt(144)

Math.random(expression)

Returns a random number between zero and one:
   Math.random()

Navigator (Browser) Object

navigator Properties

Property

Description and Current Setting

appCodeName

The browser's code name.
 

appName

The browser's application name.
 

browserLanguage

The language used for display.
 

cookieEnabled

Whether the browser permits reading and writing of cookies.
 

cpuClass

The type of CPU of the computer running the browser.
 

platform

The operating system type running the browser.
 

userAgent

Information about the brower, version, and operating system platform.
 

String Object

String Properties

Property

Description

length

Returns the number of characters in a string:
   
TextString.length

 

String Formatting Methods

Method

Description

bold()

Changes the text in a string to bold.
   
TextString.bold()

 

italics()

Changes the text in a string to italic.
   
TextString.italics()

 

strike()

Changes the text in a string to strike-through characters.
   
TextString.strike()

 

sub()

Changes the text in a string to subscript.
   
"Subscript" + TextString.sub()

 

sup()

Changes the text in a string to superscript.
  
 "Superscript" + TextString.sup()

 

toLowerCase()

Changes the text in a string to lower-case.
   
TextString.toLowerCase()

 

toUpperCase()

Changes the text in a string to upper-case.
   
TextString.toUpperCase()

fixed()

Changes the text in a string to fixed (monospace) font.
   
TextString.fixed()

 

fontcolor("color")

Changes the color of a string using color names or hexadecimal values.
   
TextString.fontcolor("blue")
   
TextString.fontcolor("#0000FF")

 

fontsize("size")

Changes the size of a string using font sizes 1 (smallest) - 7 (largest).
  
 TextString.fontsize("4")

 

link("href")

Formats a string as a link.
   
TextString.link("page.htm")

 

StringProcessing Methods

Method

Description

charAt(index)

Returns the character at position index in the string.
   TextString.charAt(0)

charCodeAt(index)

Returns the Unicode or ASCII decimal value of the character at position index in the string.
   TextString.charCodeAt(0)

indexOf("chars")

Returns the starting position of substring "chars" in the string. If "chars" does not appear in the string then -1 is returned.
   TextString.indexOf("text")
   TextString.indexOf("taxt")

lastIndexOf("chars")

Returns the starting position of substring "char" in the string, counting from end of string. If "chars" does not appear in the string then -1 is returned.
   TextString.lastIndexOf("text")
   TextString.lastIndexOf("taxt")

slice(index1[,index2])

Returns a substring starting at position index1 and ending at (but not including) position index2. If index2 is not supplied, the remainder of the string is returned.
   TextString.substring(2,6)

split(delimiter)

Splits a string into separate substrings which are copied as individual elements into a new array object. The delimiter identifies the separator character for splitting the string but it is not included in the substrings. The array object does not need to be prior declared.
   MyArray = TextString.split(" ")

substr(index[,length])

Returns a substring starting at position index and including length characters. If no length is given, the remaining characters in the string are returned.
   TextString.substring(7,6)

substring(index1,index2)

Returns a substring starting at position index1 and ending at (but not including) position index2.
   TextString.substring(7,13)

toString()

Converts a value to a string.
   var NumberValue = 10
   var StringValue = NumberValue.toString()

toFixed(n)

Returns a string containing a number formatted to n decimal digits.
   var NumberValue = 10.12345
   var StringValue = NumberValue.toFixed(2)

toPrecision(n)

Returns a string containing a number formatted to n total digits.
   var NumberValue = 10.12345
   var StringValue = NumberValue.toPrecision(5)

window Object

References

property
window.property
self.property

top.property
parent.property
top.frame.property
parent.frame.property

window Properties

Property

Description and Setting

defaultStatus

The text to display in the status bar appearing at the bottom of the browser window.
 

length

The number of frames in the window
 

location

The URL of the document in the window.
  top.location =
 

screenLeft
screenTop

Returns pixel position of the [main] window relative to top-left corner of the screen.
 

screen Properties

Property

Description and Setting

availHeight

The height of the screen in pixels (not including the Task Bar).
 

availWidth

The width of the screen in pixels.
 

colorDepth

Number of bits per pixel used to display.
 

fontSmoothingEnabled

Whether Smooth Edges for fonts is chosen in the control panel.
 

height

The height of the screen in pixels (including the Task Bar).
 

width

The width of the screen in pixels.
 

window Methods

Method

Description

alert("string|variable")

Opens an alert message box and displays a text string.
alert("Hello there")

 

prompt("string","default text")

Opens a prompt message box and returns entered value.
Response=prompt("Enter something", "default text")

 

confirm("string")

Opens a confirm message box and returns true or false.
Response=confirm("Are you sure?")

 

eval("string expression")

Executes the string expression as a JavaScript statement.

 

focus()

Brings focus to a window. When working with secondary windows (see next page), brings the window to the foreground.

 

blur()

Removes focus from a window. When working with secondary windows (see next page), moves the window to the background.

 

open()

Opens a secondary window.

 

close()

Closes an open window.

 

createPopup()

Opens a popup window.

 

moveTo(h,v)

Moves the window to horizontal and vertical position relative top-left of screen:
   
moveTo(50,50)

 

moveBy(h,v)

Moves the window by + or - horizontal and vertical pixels:
   
moveBy(50,50)

 

parseFloat("string")

Converts string to floating-point value.

 

parseInt("string")

Converts string to integer value.

 

resizeTo(h,v)

Changes the size of the window to horizontal and vertical number of pixels:
   
resizeTo(800,600)
   
resizeTo(1024,768)

 

resizeBy(h,v)

Changes the size of the window by + or - horizontal and vertical pixels:
   
resizeBy(-50,-50)

 

print()

Prints the window or frame. Presents the print dialog box.

 

scrollTo(h,v)

Scrolls the document in the current window or frame to horizontal and vertical pixel postions from top of document:
   
scrollTo(0,50)

 

scrollBy(h,v)

Scrolls the document in the current window or frame by + or - horizontal and vertical pixel from current position:
   
scrollBy(0,-100)

 

setTimeout("statement", milliseconds)

Causes the script to pause for a specified number of milliseconds before executing the statement.

 

variable = setInterval ("statement", milliseconds)

Causes the script to execute the statement every milliseconds.

 

clearInterval(variable)

Clears the interval timer variable.

 

Secondary Windows

[variable = ] open("url","window_name","window_settings")

variable

a name assigned to the window for reference from a different window.

url

the location of the XHTML document to load into the secondary window.

window_name

a name you supply for the window. This name is used to reference the window within <frame> and <a> (anchor) tags. You can code a null value ("") if this reference is not needed.

window_settings

characteristics of the window. If you do not include these settings, a standard browser window is created. Otherwise, you can include any of the following parameters, separated by commas and including no blank spaces in the list:

toolbar=yes|no - display the browser's toolbar
location=yes|no - display the browser's location, or address bar
directories=yes|no - display the browser's directory buttons bar
status=yes|no - display the browser's status bar
menubar=yes|no - display the browser's menu bar
scrollbars=yes|no - display necessary window scroll bars
resizable=yes|no - permit user to resize the window
width=n - horizontal width of the window in pixels
height=n - vertical height of the window in pixels
fullscreen=yes|no - open the window full screen with no features

The set of parameters you choose to code must be enclosed in a single set of quotes and separated by commas:

"toolbar=yes,scrollbars=yes,height=400,width=300"

If you code any one of these settings, the remaining are considered to be voided and you need to specify any others you wish to use.

Modal/Modeless Dialog Windows

showModalDialog("url"[,arguments][,"window_settings]")
showModelessDialog("url"[,arguments][,"window_settings]")

url

location of the XHTML document to load into the modal dialog window.

arguments

a string, usually, of values passed to a script on the modal dialog page. The script receives the string as property window.dialogArguments.

window_settings

characteristics of the modal dialog window. Properties are set in CSS fashion, property:value, with settings separated by semicolons. The follow properties can be set:

dialogWidth:npx - horizontal width of the window in pixels
dialogHeight:npx - vertical height of the window in pixels
dialogLeft:npx distance of window in pixels from left edge of screen
dialogTop:npx - distance of window in pixels from top edge of screen
center:yes|no - display window in middle of screen
status:yes|no - display window's status bar
edge:raised|sunken - style of the window border
help:yes|no - display a help icon in titlebar

If no properties are provided a default window is displayed.

Statements

Assignment

var variable = integer|floating-point|"string"| variable|expression

Decision Making

if Statement

if (conditional expression)
  {
   ...
statements
  }


if...else Statement

if (conditional expression)
  {
   ...statements

  }
else
  {
   ...statements
  }


if...else if Statement

if (conditional expression1)
  {
   ...statements
  }
else if (conditional expression2)
  {
   ...statements
  }
else if (conditional expression3)
  {
   ...statements
  }
...
[ else {...statements} ]


switch Statement

switch (expression)
  {
  case "value1":
    ...statements
    break


  case "value2":
    ...statements
    break

  case "value3":
    ...statements
    break

  ...

    [
    default:
      ...statements
      break
    ]
  }

Iterations

for Statement

for (initial expression; conditional expression; incremental expression)
   {
   ...
statements
   }

while Statement

while (conditional expression)
   {
   ...statements

do while Statement

do
   {
   ...statements
   }
while (conditional expression)

break Statement

for() {
  
...

   if (true) {
      break
   }
}

continue Statement

for() {
  
...

   if (false) {
      continue
   }
}