- Introduction
- JavaScript and JScript
- JavaScript URL/Interpreter Window
- Comments in JavaScript
- { } (curly braces)
- ; (semicolon)
- Alert (Message) Box
- Arrays, Creating
- Arrays, Sorting Elements of
- Calling External JavaScript Files
- Confirm and Prompt Boxes
- Date Object
- Displaying Text in Non-JavaScript Browsers
- Document Object
- Escape Sequences
- escape() and unescape()
- Forms
- Functions
- Hiding Code from older Browsers
- Image Replacement
- Navigator Object
- Objects (see Arrays)
- Operators, Arithmetic
- Operators, Comparative
- Query Strings
- Recursion
- Search a String (indexOf)
- Sorting Data (see Arrays, Sorting Elements of)
- Strings, Passing to other Pages (URLs)
- Strings, Returning Substrings
- Time ( see Date Object )
- VBScript
- Windows, Opening
- Windows, Microsoft, Print Dialogue Box
Note that JavaScript is case-sensitive, e.g.
LastModified is not the same as
lastModified.
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.
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').
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.
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;
}
It is considered good programming practice to always include semicolons at the end of JavaScript statements, whether they are needed or not.a = 5; b = 4;a = 5; b = 4;
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.
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";
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.
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();
<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".

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.
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 |
| 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.toGMTString | Returns a string expression in the format Mon,
20 Aug 2001 22:55:34 GMT (format may vary from OS to OS). |
| Date.toLocaleString | Returns a string expression in the format 08/20/01
23:55:34. This is not generally as useful as .toGMTString. |
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>');
}
<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>
window.document documentProperties:
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')
\' 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 ©
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.
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.
<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.
<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>
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...
.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.
Property Netscape Navigator Internet Explorer appCodeName Mozilla Mozilla appName Netscape Microsoft 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)
| + | Adds both operands | total=sum1+sum2; |
| - | Subtracts the second operand from the first | total=sum1-sum2; |
| * | Multiplies the two operands | total=sum1*sum2; |
| / | Divides the first operand by the second | total=sum1/sum2 |
| % | Divides the first operand by the second and returns the remainder | result=sum1%sum2 |
| ++ | Increments the operand by 1 | sum1++ |
| -- | Decrements the operand by 1 | sum1-- |
| - | When used with a single operand, converts a positive value to a negative value |
| == | 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 |
?', 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.
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++;
}
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.');
}
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.
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);
<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.
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.
|
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.
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.