Index

Web Logo

JavaScript Quick Reference


Index    Top of Page

Introduction

This is an aide mémoire for the JavaScript language.   Brief code examples are given (in no particular order) which may be cut and pasted into other scripts as required.

Note that JavaScript is case-sensitive, e.g. LastModified is not the same as lastModified.



Index    Top of Page

JavaScript and JScript

Microsoft Internet Explorer 2 does not adhere to the JavaScript standard, implementing Microsoft's proprietary language JScript. This was partly a political decision, but also a logistical one because Netscape were late in releasing the definite "Version 1.0" implementation of JavaScript. The problem for JavaScript developers is finding workarounds for the incompatibilities that do crop up.

Fortunately, Internet Explorer 4 complies with JavaScript 1.2. In fact, both Netscape and Microsoft have committed themselves to supporting JavaScript, which is now an official standard, called ECMA-262. ECMA-262, also known as ECMA Script, has been ratified by the IETF and the W3C. An interface to ECMA-262 is part of the HTML4 standard.



Index    Top of Page

JavaScript URL/Interpreter Window

Netscape Navigator 3, Opera 3 and Microsoft Internet Explorer 4 allow single lines of JavaScript to be tested via the JavaScript URL, e.g. by entering javascript:alert('Hello World'); in the Location field. The main browser window will display the result of the actual code instruction, or it will confirm whether the code is valid (true) or not (false).

Furthermore, Navigator versions 3 and later have an interpreter window which allows sequential lines of code to be tested. This is activated by typing javascript: on its own in the Location field. Beware that objects such as document and window are seen as URLs outside the interpreter window and will cause Netscape to return an error message. It is best to test statements without those objects, e.g. 'Hello World' instead of document.write('Hello World').



Index    Top of Page

Comments in JavaScript

Reading through lines and lines of code is difficult at the best of times. Therefore, it is necessary at times to add comments to explain the purpose of specific lines for future reference. Comments can also be used as a marker, signifying the start of a new process.

To prevent comments being read as code by the JavaScript interpreter, prefix them with two forward slashes. This should be done for every line containing a comment, e.g.:

//  This is the first line of my comment.
//  This is the second line of my comment.
Comments can also be inserted after a line of code:
a=prompt('Please enter your name','');  // Displays the prompt box.


Index    Top of Page

{ }  (curly braces)

Curly braces are used to combine a set of primitive statements into a block or compound statement, such as those found in if, for and while control statements. Braces are also used to mark the start and finish of a function block. Braces must always be used in functions, even when the function contains only one statement:
  function doSomething()
  {
    x = 0;
  }



Index    Top of Page

;  (semicolon)

The semicolon is used to mark the end of simple statements. Unlike C, C++ and Java, JavaScript does not require a semicolon if the next statement starts on a new line. The examples below are both valid ways of presenting statements:

a = 5;
b = 4;

a = 5; b = 4;

It is considered good programming practice to always include semicolons at the end of JavaScript statements, whether they are needed or not.



Index    Top of Page

Alert (Message) Box

See also: Confirm and Prompt Boxes.  

Alert() is a Method belonging to the Window Object.

    alert('\n\nDocument Properties:\n'
    + '_________________________________   \n\n'
    + document.title                       + '\n\n'
    + 'Modified: ' + document.lastModified + '\n'
    + '_________________________________   \n')

Note that \n generates a line feed character in Alert boxes (see 'Escape Sequences').

Alert box messages in Netscape Navigator are prefaced with "JavaScript Alert:".  Internet Explorer does not display any such identification. This has been raised as a possible security problem.




Index    Top of Page

Arrays, Creating

In JavaScript, Arrays and Objects are identical in nature. Arrays can have Object properties and Objects can have array elements.

In Navigator 3 and Internet Explorer 3, arrays can be created with the following constructor:

    myarray = new Array();
        myarray[0] = "first element";
        myarray[1] = "second";
        myarray[2] = "third";
        myarray[3] = "fourth";


    d = new Array(16);
        d[0] = "dansak";
        d[1] = "korma";
        d[2] = "madras";

        d[14] = "jalfrezi"
        d[15] = "vindaloo"
Note that the first element of an array is numbered '0' (zero). Therefore, the last element of array d will be 15 (16 - 1).

Use the length property to determine the number of elements in the array.

    arraysize = myarray.length

Although array.length always returns the correct number of elements in an array, the number of the last element will always be one less.

Navigator 3 and Internet Explorer 4 introduced three new methods for manipulating arrays, array.join, array.sort, and array.reverse.

The Array() constructor is not available in Navigator 2. It uses the Object() constructor which can be assigned elements or properties. When a Navigator 2 array is assigned a property, it is assigned the next available array element. Therefore, in the following example address.town could also be called up as address[1] and address.county as address[2].

    address = new Object();
      address[0] = "64 High Street";
      address.town = "Basingstoke";
      address.county = "Hampshire";

Care must be taken that to ensure that array properties are not overwritten by new array elements. It is best to choose one method of building arrays and sticking to it, rather than mixing them in the same program.

Also, Navigator 2 does not understand array.length. This restriction applies only to user-defined arrays, - built-in arrays such as document.links do have a length property. It is common for user-defined arrays to store the array length in the first element of the array (array[0]):

    function MakeArray(length);
    {
        this.size = length;
        for(var i =1; i <= length; i++)
             this[i] = 0;
    }
Alternatively, the array length can be stored in an external variable.

If the array will be updated frequently (as 'real' data often becomes out of date), re-numbering the element arrays will become tedious (all array elements must be numbered sequentially). Instead, use the ++ operator to increment the array element number:

    nu = 0;
    data = new Array();

    data[nu++] = "apples";
    data[nu++] = "pears";
    data[nu++] = "bananas";
    data[nu++] = "grapefruit";
Alternatively, put the data into a string, with each record separated by a character which can be used to create the array when required:
    dt = "Date|Event|Circuit|Country";
    dt += "~16 May|Monaco Grand Prix|Monte Carlo|MC";
    dt += "~30 May|Spanish Grand Prix|Barcelona|E";
    dt += "~13 June|Canadian Grand Prix|Montreal|CAN";
(Note that the last example is in fact an array of arrays, where the '|' character can be used as the separator for the sub-elements).

The next line uses the split property to convert the data string into an array called 'data':

    data = dt.split('~');
There is no apparent limit on the length of character strings, apart from available memory and resources on server and client machines.




Index    Top of Page

Arrays, Sorting Elements of

To sort the elements of an array, use the sort property:
    myarray.sort();
Note that sort re-orders the elements of myarray directly, no new arrays have to be created. To reverse the order of an array's elements, use the following:
    myarray.reverse();



Index    Top of Page

Calling External JavaScript Files

This feature is available in JavaScript 1.1 onwards (i.e. Netscape Navigator V3.0 onwards and Microsoft Internet Explorer V4.0 onwards).

    <SCRIPT LANGUAGE="JavaScript 1.1" SRC="sub_doc.js">
    </SCRIPT>
Example contents for sub_doc.js:
    document.write('This is text from another file.')

For external JavaScript files to be included, they must have a .js extension, and must be exported by the web server with MIME-type "application/x-javascript".


Index    Top of Page

Confirm and Prompt Boxes

See also: Alert (Message) Boxes.  

Prompt Box

confirm() and prompt() are properties belonging to the Window Object.

Confirm: confirm('Do you want to press the OK Button?');

Prompt: a=prompt('Please enter your name','');

              if (a==null) {
                   document.write('You did not enter your name')
              }
               else {
                   document.write('Your name is ' + a)
              }
The second argument in prompt() is the default message in the text input box (which can be overwritten by user input). If this argument is omitted, the message undefined is displayed. If the argument is set to a null string, the text input box will be blank.

Prompt boxes in Netscape Navigator do not allow multiple lines (i.e. using the \n newline character) although Internet Explorer's Prompt boxes do.



Index    Top of Page

Date Object

To create a Date Object, use the following constructor:
    tm = new Date(arglist);
If arglist is omitted, the current date and time is stored. Optional arguments are:

integer Milliseconds after UTC, e.g 5000 = 5 seconds past midnight, 1st January 1970.
month, day, year e.g. 12, 31, 1999
datestring e.g. Sat 21 August 1999

Once the Date Object has been constructed, it can be manipulated as follows:

Date.getYear()Retrieve the year (two or four digit number.
Date.setYear()Set the year in Date, e.g. Date.setYear(1998). Note that two digit numbers can be used for the 20th century.
Date.toGMTStringReturns a string expression in the format Mon, 20 Aug 2001 22:55:34 GMT (format may vary from OS to OS).
Date.toLocaleStringReturns a string expression in the format 08/20/01 23:55:34. This is not generally as useful as .toGMTString.
To get the current year:

    now = new Date();

    y = Date.getYear(now);
    document.write('The year is ' + y);
         // returns two or four digit integer (see below)
    x = Date.getMonth(now);
    document.write('The month is ' + x);
         // returns month as integer between 0 and 11
Navigator returns two digit integer for years between 1900 and 1999, and four digit integer for all other years. Internet Explorer always returns the year minus 1900 (i.e. 1985 is returned as 85, 2010 is returned as 110). Internet Explorer cannot return years prior to 1970.

To display a "time of day" greeting:

    today = new Date()
    if (today.getHours() > 16)  {
        document.writeln('Good Evening!')
    }
    else if (today.getHours() > 11)  {
        document.writeln('Good Afternoon!')
    }
    else if (today.getHours() < 12)  {
        document.writeln('Good Morning!')
    }

To display a 'Page last updated' message at the foot of each document, use the following code:

    //  Check datestamp is present in HTTP header (server not obliged to send it):
    if (Date.parse(document.lastModified) != 0) {
       a = new Date(document.lastModified);

       // Set a pivot year of 1950 for Millennium non-compliant browsers:
       if (a.getYear() < 50) {
          a.setYear(a.getYear() + 2000);
          }

       document.write('Last Modified: ' + a.toGMTString() + '<BR>');
       }



Index    Top of Page

Displaying Text in Non-JavaScript Browsers
(but hiding it from JavaScript-enabled Browsers)

    <SCRIPT LANGUAGE="JavaScript">
        <!-- -->  If JavaScript is enabled, this text will not 
        <!-- -->  be displayed, but it will be visible on non-
        <!-- -->  JavaScript Browsers.<P>
    </SCRIPT>

The <NOSCRIPT></NOSCRIPT> tags may also be used, because non-JavaScript Browsers ignore the tags and display any text inside them. Unfortunately, Navigator 2 does not play ball because it too does not recognise the <NOSCRIPT></NOSCRIPT> tags!

Alternatively, divert JavaScript-enabled Browsers to another page, so that messages for non-JavaScript Browsers are not seen.

<HTML><HEAD><TITLE>Document Title</TITLE>

    <SCRIPT LANGUAGE="JavaScript 1.1"><!-- Hide code
        window.location.href="newpage.htm";
    //--></SCRIPT>

    </HEAD>
<BODY>Sorry, you need JavaScript enabled to read this page.<P>
</BODY></HTML>


Index    Top of Page

Document Object

The Document Object is a field of the Window Object. The window reference may be omitted.

window.document
document
Properties:
lastModified - date and time the document was last uploaded or saved[R] *
location     - a synonym of the URL property
referrer     - URL of the document from where the current document was opened
title        - Title of the document [R]
URL          - URL of the document [R]
vlinkColor   - colour of visited links.
[R]  Read-Only

 *    Some web servers do not return this information, in which case
     midnight 1st January 1970 UTC is displayed.

Methods:

clear()      - Erases the document's contents
close()      - Closes a document opened with the open() stream
open()       - Opens a stream to which document contents may be written
write()      - Inserts a string or strings into the document
writeln()    - Same as write() but appends a line feed character
window.document.writeln('hello world')



Index    Top of Page

Escape Sequences

Use Escape sequences to insert characters which would otherwise not display in Alert boxes or corrupt JavaScript code (e.g quotation marks).

    \'    Single quote  '
    \b    Backspace
    \f    Form Feed
    \n    Newline (Line Feed)
    \r    Carriage Return
    \t    Tab

    \xxx  Latin (ISO8859-1) character xxx
    \251  Copyright Symbol ©


Index    Top of Page

escape() and unescape()

The escape() function converts all spaces, punctuation marks, accented characters, and any other characters which are not standard ASCII letters or numbers into the form %nn , where nn represents the hexadecimal value of the encoded charcater in the Latin-1 (ISO-8859-1) character set.

As an example, the expression escape("Hello World!") will encode the string to Hello%20World%21.

Use the unescape() function to decode strings encoded by the escape() function.

The use of encode() and unescape() ensures that the string is portable to all computers, networks and transmission paths, regardless of character encodings, providing of course, that they all support standard ASCII. The function is also used to overcome the restriction on the use of punctuation marks when setting cookie values.

escape() performs encoding not dissimilar to that of URL-encoding. The main difference is that URL encoding replaces spaces with the + character.



Index    Top of Page

Forms

If a form has a single text input field, pressing [CR] or [Enter] may allow the form to be sent to the server without clicking on the Submit button. This is certainly a feature of Navigator and Internet Explorer browsers. It may also be an undesirable feature, e.g. the user may have hit [Enter] unintentionally before entering data, or you may want JavaScript to validate form data before it is posted.

The problem does not arise with other form elements used on their own, or if there are two or more text input fields on the form.

The onSubmit argument does not always prevent a form with invalid data from being submitted.



Index    Top of Page

Functions

Ideally, Javascript should be inserted between the document header, i.e. between the <HEAD> and </HEAD> tags, so that all code is loaded into memory before the HTML content is parsed.

For tidiness, code can be wrapped inside Functions:

    <SCRIPT LANGUAGE="JavaScript"><!--Hide etc.
        function dothis()
        {
           code goes here...
        }
    //--></SCRIPT>
The relevant function can then be called up from the required position in the document:
    <A HREF="link.htm" onmouseOver=dothis()>A Link</A><P>
It is generally safe to deploy the document.write statement where it is needed in the document, rather than from within the document header.


Index    Top of Page

Hiding Code from older Browsers:

<HTML><HEAD><TITLE>Document Title</TITLE>

    <SCRIPT LANGUAGE="JavaScript 1.1">
    <!-- Start of Tag which hides code from old Browsers

        JavaScript code goes here...
            "            "  
            "            "  

    // End of Tag which hides code from old Browsers --> 
    </SCRIPT>

</HEAD>

This is often abbreviated to something like this:

    <SCRIPT LANGUAGE="JavaScript 1.1"><!-- 
        JavaScript code goes here...
            "            "  
            "            "  
    // --></SCRIPT>


Index    Top of Page

Image Replacement

Navigator 3 introduced the Image() Object, which allowed images in a document to be referenced by an array.

The following script produces a "Windows-style" menu, where dragging the mouse over the menu option causes a new image to be loaded:

    <HEAD><SCRIPT LANGUAGE="JavaScript 1.1">
    d = new Array(16);         // Create Array for Image Objects

    for(var i = 0; i < 16; i++) {
        d[i] = new Image();          // Create Image Object
        d[i].src = "img" + i + ".gif";  // Load the URL
    }


    function paint(x,y) {
        document.images[x].src=y;
    }

    function unpaint(x,y) {
        document.images[x].src=y;
    }
    </SCRIPT></HEAD>

    <BODY>
    <A HREF="homepage.htm" onmouseOver=paint(0,d[0].src) 
onmouseOut=unpaint(0,d[1].src)>
<IMG SRC="img1.gif" ALT="Home Page" 
WIDTH=95 HEIGHT=20 BORDER=0></A>
etc...

Specifying the .src property of the Image Object forces the image file to be loaded into the Browser's cache, even if it is not required immediately for display. This eliminates any delay between the mouse moving over the Object and the new image being displayed.



Index    Top of Page

Navigator Object

Properties:

Property Netscape Navigator Internet Explorer
appCodeName MozillaMozilla
appName NetscapeMicrosoft Internet Explorer
appVersion 3.03 (Win95; I)2.0 (compatible; MSIE 3.0A;Windows 95)
mimeTypes[]
mimeTypes.length
text/html, images/gif etc. Not supported
userAgent Mozilla/2.01 (Win16; I)Mozilla/2.0 (compatible; MSIE 3.0A;Windows 95)



Index    Top of Page

Operators, Arithmetic

+Adds both operandstotal=sum1+sum2;
-Subtracts the second operand from the firsttotal=sum1-sum2;
*Multiplies the two operandstotal=sum1*sum2;
/Divides the first operand by the secondtotal=sum1/sum2
%Divides the first operand by the second and returns the remainderresult=sum1%sum2
++Increments the operand by 1sum1++
--Decrements the operand by 1sum1--
-When used with a single operand, converts a positive value to a negative value



Index    Top of Page

Operators, Comparative

==Returns true if the operands are equal, otherwise returns false
!=Returns true if the operands are not equal
>Returns true if the first operand is greater than the first
<Returns true if the first operand is less than the second
>=Returns true if the first operand is greater than or equal to the first
<=Returns true if the first operand is less than or equal to the second



Index    Top of Page

Query Strings

Query strings are the portion of a URL that follow a question mark '?', also known as 'searches' and 'command tails'. These are normally seen on web form requests (note that the query string is only visible on GET methods). HTML Forms do not have to be acted upon by server-side CGI scripts, the form's 'Action' argument' can be directed to another HTML document containing Javascript. Thus web forms can be processed client-side.

Use location.search to read a query string, for example:

    if (location.search == '?reverse') {
       myarray.reverse();
       }
Note that location.search returns everything following, and including, the question mark, e.g., on:
http://www.anydomain.com/doc.htm?myquery_string
?myquery_string is returned.   



Index    Top of Page

Recursion

    for(var i = 0; i < 16; i++) {
        d[i] = new Image();          // Create Image Object
        d[i].src = "img" + i + ".gif";  // Load the URL
    }


    count = 0;
    while (count < 10) {
         document.write(myarray[count]);
         count++;
         }



Index    Top of Page

Search a String (indexOf)

    string.indexOf(substring);

Finds the starting location of a substring in string. The first characater of string is at position 0. If the substring is not found, the value -1 is returned.

   if (haystack.indexOf(needle) > -1) {
       document.write('Needle found in haystack.');
   }


Index    Top of Page

Strings, Passing to other Pages (URLs)

Strings can be passed to another URL in the form of "command tails". This is often seen in queries to CGI scripts but can also be used in JavaScript routines. The key here is the location.search property placed in the target URL/Page.

The example below sends text to the URL second_page.htm.  Note the use of the question mark ? to separate the query string from the URL:

    function sendto(a)
    {
       window.location.href='second_page.htm?' + escape(a);
    }

    document.write('<FORM NAME="form">');
    document.write('<INPUT TYPE="text" NAME="txt1" SIZE="40"><P>');
    document.write('<INPUT TYPE="Button" VALUE=" Send Now " ');
    document.write('onclick=sendto(form.txt1.value)></FORM>');
The file second_page.htm would retrieve the string as follows:

    a = unescape(location.search);
    document.write(a.split('?')[1]);

Do not forget to convert the command tail or query to an escape sequence before transmission (using the escape() command), and to unescape() the query at the destination. This is to ensure that all network and transmission paths understand non-ASCII characters such as spaces and punctuation marks.



Index    Top of Page

Strings, Returning Substrings

To return a part of a string, type:

    stringname.substring(x, y);
Where x is the start position (note 1st character is at position '0') and y is the number of characters to return.

For example:

    outp = 'Fred Bloggs";
    document.write(outp.substring(5, 6);
Returns Bloggs.

If you want to return the remainder of the string from your starting point, but do not know the length of the string, you can set y to a number much gretaer than the string could ever be, e.g:

    document.write(outp.substring(5, 3000);


Index    Top of Page

VBScript

Microsoft's proprietary scripting/programming language based on Visual Basic Applications (VBA). VBScript routines are called up using <SCRIPT></SCRIPT> tags with the LANGUAGE attribute set to VBScript.

    <SCRIPT LANGUAGE="VBScript">
    <!-- Start of Tag which hides code from non-VBScript Browsers

        // VBScript code goes here...

        Document.Write "You have VBScript enabled."

    // End of Tag which hides code from non-VBScript Browsers --> 
    </SCRIPT>

Netscape Navigator has never supported VBScript, which means that such scripts will be unreadable on about 50% of web browsers. No VBScript plug-in for Netscape (if one exists) has gained prominence, indicating the level of support this language has achieved on the World Wide Web.

VBScript will be more effective on those intranets which run MS Internet Explorer as the default client browser.



Index    Top of Page

Windows, Opening

The syntax for opening a new window is as follows:

constant = window.open("URL", "Window_Name", "Features")

When using JavaScript to print to a new window, leave URL as a null string. Window_Name can contain alphanumeric characters and the underscore character.

Features specify browser options as follows:
toolbar Displays the Browser toolbar with Back and Forward buttons.
location Displays the text box used to enter URLs from the keyboard.
directories Displays directory buttons, such as What's New and What's Cool in Netscape.
status Displays the Status window at the bottom of the Browser.
menubar Displays the menu bar with File, Edit, etc.
scrollbars Displays horizontal and vertical scrollbars when required.
resizable Allows the Browser window to be resized. Depending on the Browser and operating system in use, if resizable is ommitted, the user may still have control over the window's size.

Note that the spelling resizeable will not work.

width When followed by an integer, specifies the window's width in pixels, eg: width="600".
height When followed by an integer, specifies the window's height in pixels, eg: height="300".

A script to open a new browser window and add text to it would look something like this:

  n = window.open("","NEW","WIDTH=400,HEIGHT=250,menubar,scrollbars");

  n.document.open("text/html");
  n.document.write('<HTML><HEAD></HEAD><BODY>');
  n.document.writeln('Text in a new Window.<P></BODY></HTML>');

  n.document.close();
Specify the MIME type with the document.open() statement. If no MIME type is specified, text/html is assumed. Options are text/html and text/plain.


Index    Top of Page

Windows, Microsoft, Print Dialogue Box

Netscape Communicator 4 introduced a Javascript method for calling up the Windows Print Dialogue box. This method was later adopted by Microsoft Internet Explorer 5. The author cannot verify whether this method is replicated on other platforms, and thererfore could be of limited use on the World Wide Web.

However, it may be better suited to intranets where Microsoft Windows is the default client installation. The code for this method is as follows:

  <INPUT TYPE="button" VALUE=" Printer Setup " onClick="window.print()">
This code will create error messages on earlier browsers when users click the button, as the browser will be expecting a function called window.print within your script.

 

Therefore, it would be wise to put this code inside a conditional statement which tests for the presence of Communicator 4 or MSIE5.


Created:    11th April 1998
Updated:   Friday 16 November 2001 20:32:01
Philip Jefferson

   Go to top of Page

Index