LevSelector.com New York
home > Javascript

On this page:
* main_sites
* books
* examples & references
* debugging
* objects
* image rollovers
* misc.examples
break lines, alerts, form, clock,
hidden frame, select
no multithreading
regex, hash,
reverse, reference,
location, caching, colors,
java applet <=> script,
* add to favorites
* loan payments
* list2list
* win2win
* radio buttons
* formcopy
* cookies
* date_pickers
* String object
* Math*Number
* array
* misc_functions
* Object

See more on using Javascript in DHTML on my html/dhtml page

Note (2009):

This page was first created in 1999. Today (2009) it is definitely outdated, although still may be useful. Javascript made a lot of progress in the last 10 years. And there is much more information on the web. You can look on wikipedia, or you can search for javascript tutorials or javascript interview questions, or you can search for specific topic, for example: javascript closures, etc. Here are some good pages:

Note (2014):

Nowadays you can use javascript both on the server side and on front end, and you can write html5/javascript apps which work in browser and on mobile devices:

Here's your homework:

  • Get an account on heroku (https://www.heroku.com - cloud application platform).
  • Go through the node.js tutorial on heroku and install node, etc.
  • Install drywall
  • Look through the drywall code and see if you can understand how it works. It has pretty all of the trendiest tools like boostrap, backbone, express etc.


It would be nice to be able to make HTML page clever enough to do something meaningful or to interact with the user without running to the server every time. For example, if user has made a mistake filling out the form, the validation can be done using some programming embedded into HTML page.  This kind of programming is usually done using Javascript.

The idea of having a script embedded into a static HTML page to add functionality is very powerful. Many scripting languages were used for this purpose. The embedded scripts can be interpreted
 - either on the side of the web server (Server side Javascript, ASP, PHP, JSP, etc.),
 - or on the client browser (client-side Javascript, JScript, VBScript, Perlscript, etc.).

Below we will talk about client-side (browser) Javascript.

Javascript is a lightweight interpreted programming language.  It allows to:
 - Detect the browser type, access some properties of the browser, window, and HTML document
 - Control (to some extent) elements of the browser window and document (for example, images, layers, etc.).
 - Interact with the user, read and write cookies, interact with java applets
 - Do misc. math. calculations, processing with regular expressions, - and much more.

Javascript syntax is similar to C, C++ and java.  You see similar if/else statements, for/while loops, && operator, {  } blocks, /* ..*/  and // comments, etc. But there are also many differences:
 - JavaScript is an untyped language. Same variable can be a number or a multi-line text (similar to perl).
 - Objects in JavaScript are more like Perl's associative arrays.

Cross-browser pains:
Different versions of browsers on different platforms vary dramatically in how they support Javascript.  Everything is different: object models of the browsers and documents in them (DOM), and how to access document elements, event handling, etc. Designing a cross-browser Javascript is a painful process, because you have to detect the type and version of the browser and write 2 or more versions of the same code embedded in the same document. Plus after every change you have to test it on different browsers and platforms as well.

Main Sites home - top of the page -
Dan Steinman's tutorial and API (not updated after October 1999):
* www.dansteinman.com/dynduo/ - CrossBrowser DHTML Tutorial and API
* dansteinman.com
     */dynduo/en/links.html - Dan's DHTML links
     */dynapi/js/ - collection of javascripts, 
     *ddart.pe.kr/dhtml/dynduo/ - mirror site
      Download the tutorial and API:
     * /downloads/dynduo/dynduo-19991024.zip - tutorial in HTML
        (local basics and DynLayer API as txt to copy into editor for printing)
     * /downloads/dynapi/dynapi-19991024.zip - APIs
     * /downloads/dynduo/pdf/dynduo-19991024.pdf - 123 page printable tutorial

See (and download) next generation API here (frequently updated):
* dynapi.sourceforge.net/index.php - DynAPI - library and tutorials

* DynamicDrive - very good examples and convenient to use
* www.brainjar.com - Javascript

* developer.netscape.com/docs/manuals/communicator/jsguide4 - Netscape's JavaScript Guide
* home.netscape.com/eng/mozilla/3.0/handbook/javascript - Netscape's JavaScript Handbook
* Inside DHTML -
* www.ruleweb.com/dhtml/ - Jeff Rule's Dynamic HTML and SMIL Site
* HotScripts.com -
* Javascripts.com -
* JavaScript.com -

* www.scriptsearch.com -
* www.dhtmlzone.com -
* www.developer.com - eathweb
* www.builder.com - CNET
* www.stars.com - the Web Developer's Virtual Library -
* WebReference.com -
* www.WebCoder.com - JavaScript and Dynamic HTML
* javascript.internet.com/ - The Javascript Source, tons of "cut and paste"
* www.irt.org/articles/script.htm - Javascript articles
* JavaScript Standard -
* news://usenet/comp.lang.javascript - Usenet Javascript newsgroup
* home.earthlink.net/~oxherder/ - The Way of Javascript - A brief JavaScript tutorial inspired by the 12th century verse of the Zen Patriarch, Kakuan - commenting on this set of Taoist drawings.
* www.wilsonmar.com/1javascr.htm - sophisticated processing on the browser using Javascript (see also XML and DOM - Document Object Model)
* www.irt.org/articles/js211/index.htm - article on multi-dialogue forms

* developer.netscape.com   JavaScript (on Netscape site)
* rummelplatz.uni-mannheim.de/~skoch/js/script.htm - JavaScript tutorial
* www.hudziak.com/haznet/ - more JavaScripts
* www.zdnet.com/devhead/resources/scriptlibrary/index.html - more JavaScripts
* www.javagoodies.com - Javascript, etc.
* www.w3-tech.com/crash/CrashCourse.html - crash courses in HTML, Java, JavaScript

More javascript:
*www.thefreesite.com/Free_Java_JavaScript - free Javascript/ Java
* Javascript Links
* Javascript Source
* Earthweb Javascript
* PageResource Page
* ServerSide Javascript

Books home- top of the page -


* Javascript for the World Wide Web (Visual Quickstart Guide) by Tom Negrino, Dori Smith - simple intro.
* Javascript Bible by Danny Goodman, Brendan Eich - The absolute MUST HAVE book. Has a tutorial and a reference. ( also print out this 4 page diagram - http://devedge.netscape.com/viewsource/goodman_roadmap/jsbible3/NS4_Obj.pdf )
* Javascript : The Definitive Guide (Dave Flanagan) - One of the most popular books on Javascript. It's more of a reference than a tutorial, but Flanagan is an excellent technical writer.
     ( code examples from ftp://ftp.oreilly.com/pub/examples/nutshell/javascript/ )
* Dynamic Html : The Definitive Reference by Danny Goodman, 1998 
     ( code examples from ftp://ftp.oreilly.com/pub/examples/nutshell/dynamic_html/ )
* JavaScript Application Cookbook by Jerry Bradenbaugh, 1999 
     ( code examples from ftp://ftp.oreilly.com/examples/misc/jscook/ )
* Web Design in a Nutshell : A Desktop Quick Reference by Jennifer Niederst, Richard Koman, 1998 
* Webmaster in a Nutshell, 2nd Edition By Stephen Spainhour & Robert Eckstein, 1999
* Designing with JavaScript By Nick Heinle, 1997 
  (code examples - ftp://ftp.oreilly.com/examples/misc/designjs/ )
* Prototype and script.aculo.us - by Christophe Porteneuve (2007)

Examples & References home - top of the page -

* examples from Javascript : The Definitive Guide - Looking through these examples is the best way to learn Javascript
* reference_page from Web Master in a Nutshell - 200 KB of Javascript reference on 1 page!!  Excellent!!
* www.dansteinman.com/dynduo/ - read first part (Basics) - best intro into DHTML

Download more examples:
* ftp://ftp.oreilly.com/pub/examples/nutshell/javascript/
* ftp://ftp.oreilly.com/pub/examples/nutshell/dynamic_html/
* ftp://ftp.oreilly.com/examples/misc/jscook/
* ftp://ftp.oreilly.com/examples/misc/designjs/

Debugging home - top of the page -

Some debugging tools -added September 2008

Old notes (~2000):

Javascript is very sensitive and sometimes tricky to debug. For example, I found that it doesn't like underscores in the names - so don't use them. For example this:

     this.form.t_payee.value   // will not work

will not work, but this is OK:

     this.form.tpayee.value  // OK

A common way to debug javascript is to type "javascript:" in location field of Netscape Communicator to pop-up Netscape Communicator Console.

While debugging, it may be convenient to ouput some information.
You can do this using layers: mem/js_dhtml/show_debug_info.html
Or you can simply print to a small window as shown below:
Debug window:
  var dwin = null;

  function debug(msg) {
    if ((dwin == null) || (dwin.closed)) { 
      dwin = window.open("","debug_console","scrollbars=yes,resizable=yes,height=100,width=300");
    // dwin.document.close();  // uncomment this to see only last message

  <script>var n = 0;</script>
  <a href="javascript:debug('You have pushed me:\t' + ++n + ' times.');">press me</a>

Examples - objects home - top of the page -

Working with objects:
function MyClassName (paramA, paramB) {
  property1 = "prop1 is read only";
  propertyA = paramA;
  propertyB = paramB;

  // method pointers:
  this.getPropertyA = _getA;
  this.getPropertyB = _getB;

  // methods:
  function _getA() { return propertyA; }
  function _getB() { return propertyB; }

  // private methods:
  function aPrivateMethod() { return "I am a private method"; }

var objMyClass = null;
objMyClass = new MyClassName("A","B");
alert(objMyClass.getPropertyA());  // displays "A"

// accessing private method fails - Netscape quietly bombs:
alert(objMyClass.aPrivateMethod());  // fails

// Defining Method:
function PrintCard() { 
   document.write("Name: ", this.name, "\n"); 
   document.write("Address: ", this.address, "\n"); 

// Defining Object (constructor function):
function Card(name,address,work,home) { 
   this.name = name; 
   this.address = address; 
   this.PrintCard = PrintCard; 

// Creating Instances of Objects:
tom = new Card("Tom Jones", "123 Elm Street", "555-1234", "555-9876"); 

// Calling method on an object:

// Extending Objects Dynamically:

function my_update() { 
   this.name = prompt("Enter the correct name:", this.name); 
   this.address = prompt("Enter the address for " + this.name, this.address); 

// add "Class" variable:

Card.pi = 3.14159;

// extend instance without touching prototype:

tom.myupdate = my_update; 
tom.country = 'USA';

// or extend prototype:

Card.prototype.myupdate = my_update; 
Card.prototype.country = '___';

// Another way to add function to a prototype:

Card.prototype.myupdate = function() {
   this.name = prompt("Enter the correct name:", this.name); 
   this.address = prompt("Enter the address for " + this.name, this.address); 

//Now you can call:


Examples - image rollovers home - top of the page -

Image rollovers:
// Preload images can be done as a function called from body onload() event:

 imageA = new Image();
 imageA.src = "imageA.gif";

// If there are many images - you can preload them in a loop:

var images = new Array(10);
for(var i = 0; i < 10; i++) {
    images[i] = new Image();
    images[i].src = "images/" + i + ".gif";

// You can make your own preload function for convenience:

function preload(imgObj,imgSrc) {
 if (document.images) {
  eval(imgObj+' = new Image()')
  eval(imgObj+'.src = "'+imgSrc+'"')

// And call it like this:

// Once images are preloaded - all you have to do to change the image is this:

document.images["imageName"].src = imageObject.src

// You can wrap this into a function ( call it  changeImage()) 
// To do rollovers on mouse events make a link associated with this image:

<A HREF="javascript:void(null)"
  <IMG NAME="myImg" SRC="imageA.gif" WIDTH=75 HEIGHT=75 BORDER=0></A>

Misc. examples home - top of the page -

Breaking program lines into 2 to keep them short - tested on both IE and Netscape browsers:

// NOTE: be careful - it is not Perl.
// You can't start a string on one line - and finish on another:
//  s = " word1                 // ERROR - unterminated string literal
//              word2"; 

// Another example of the same:
// In plain html you can break a long list of parameters in a URL like this:
//  <a href="http://somedomain/test.cgi?
// par1=val1
// &
// par2=val2">test</a>
// As you see, this makes a long string where parenthesis start on one line - and finish on another.
// This will not work in JavaScript !

// You can split variable assignment near the "="

    'mama1 ';

// you can initialize several variables on one line
var i=2, j=3;

// you can split list of function parameters into several lines
var arr = new Array( "one",

// and split list in for loop
for (i=0;
           alert (arr[i]);

// you can split definition of a long string using '+'
mystr =  "word1.1 "
       + "word1.2\n"
       + "word2.1 "
       + "word2.2";

// you can split long logic in if into several lines in if() or while()
// note: you can also split concatenations of strings
//   into several strings even inside a function call
if (j==3
    i==2) {
  alert('OK '
        + 'OK')
} else {
  alert('Not '
        + 'OK')

// you can split new window definition into several lines.
// then if you splitting the long string with window parameters and concatenate with '+' sign
                      + "resizable=yes,height=400,width=400");


Alert , confirm & prompt:
function myalert() {
  ss = "First "
       + "line\n"
       + "Second "
       + "Line";

function myconfirm() {
  var msg = "some message";
  if (confirm(msg)) 

function myprompt() {
  var name = prompt("What is your name?", "");
  alert("Welcome to my home page, " + name);

<br><a href="javascript:myalert()">press to see alert</a>
<br><a href="javascript:myconfirm()">press to see alert</a>
<br><a href="javascript:myprompt()">press to see alert</a>

Form (with data validation):

function myvalidate() {
  var f1 = document.form1;
  var nn = f1.elements.length;
  for (var j=0; j<nn;j++){
    if (f1.elements[j].value.length==0) {
      alert("Please fill out ALL fields");
      return false;
  return true;

function mysubmit(){
  if (!myvalidate()) return;

<form name="form1" method="POST" action="some_action">
  <br>1: <input type="text" name="name1" value="">
  <br>2: <input type="text" name="name2" value="">
  <br><input type="button" value="click me" onClick="mysubmit()">
  <br><input type="reset" value="reset">

Other ways to submit a form:

use submit button:  <input type="submit" value"click me">
or image as a button:  <input type="image" src="mybutton.gif">

To do data validation in these cases, you will have to add onsubmit handler into the <form> tag.
<form name="form1" method="POST" action="some_action" onsubmit="mysubmit();return false;">
or like this:
<form name="form1" method="POST" action="some_action" onsubmit="mysubmit2();">
function mysubmit2(){
  // some data validation here
  if (everything_OK) return true else return false;

Digital clock in status line:

  var timeout_id = null; // This will be used to hide clock

  function show_clock() {
    var d = new Date();
    var h = d.getHours();
    var m = d.getMinutes();
    var ampm = (h >= 12)?"PM":"AM";
    if (h > 12) h -= 12;
    if (h == 0) h = 12;
    if (m < 10) m = "0" + m;
    var t = h + ':' + m + ' ' + ampm;
    defaultStatus = t;  // Display it in the status line.
    timeout_id = setTimeout("display_time_in_status_line()", 60000); // 60000 ms is 1 minute.

  function hide_clock() {
    timeout_id = null;
    defaultStatus = '';

To test click on the "show" link and remove mouse from it.
<br><a href="javascript:show_clock()";>show clock</a>
<br><a href="javascript:hide_clock()";>hide clock</a>

Hidden frameset (to store some javascript functions and objects):
<html><head><title>some title</title></head> 
<frameset name="my_top" rows="0,160,*"  frameborder="1" border="1">
 <frameset name="my_hidden_frameset" COLS="0,0" frameborder="0" border="0" noresize scrolling="NO">
  <frame name="my_hidden_frame1" src="my_hidden_frame1.pl" frameborder="0" border="0" scrolling="NO" noresize>
  <frame name="my_hidden_frame2" src="my_hidden_frame2.pl" frameborder="0" border="0" scrolling="NO" noresize>
 <frame name="my_head" src="my_head.pl" frameborder="0" border="0" scrolling="NO">
 <frame name="my_main" src="my_main.pl" frameborder="1" border="1" scrolling="YES">
Your browser cannot display frames.

frame addressing using frame name:
If all frameset definitions are made in one file - then all frames are accessible via one frames array  (even in nested framesets) may be accessed by their name from top:

But if internal frameset (f2) is loaded into a frame of an external frameset (f1), then there are 2 separate frame arrays, and addressing should go like this:

If your frameset may be called from another frameset, then "top" will not be your "top" - but the one of the caller frameset.  Then you can use "parent" instead of "top".  For example, to address hidden frame from "my_main" frame you would do something like this:
    parent.frames["my_hidden_frame1"].document.bgColor = "#CCCCCC"; // make frame size  >0 to see that it works

Select onChange handling:
<select name="subject" 
  onChange="javascript:top.window.frames['my_main_frame'].location = this.options[this.selectedIndex].value">
<option value="main_summary.html" SELECTED>Summary</option>
<option value="main_positions.html">Positions</option>

What if you press a button which started a javascript function (via onClick event processing) - and while this function is working - you press another button (or the same button) which similarly should call a function. Will this function run simultaneously with the first one? Or it will wait until the first one finishes?

The answer: the 2nd function will wait. here is a test page that demonstrates this.

If you want to emulate parallel execution - your function can use setTimeout() to call itself after a delay, during which delay another function (or same function) have a chance to execute.

Regular Expressions:
function check(num){     // checks if all are digits
   var str=num.value
   var re=/\D+/g
   if (re.test(str)|| (str=='')){
       // do something

function commafy(num){    // adds "," in front of each 3 digits
   num=num+'';      // convert number to string
   var re = /(\d+)(\d{3})/      // define regex
   while (re.test(num)) {       // apply regex, memorize into $1, $2
      num=num.replace(re, "$1,$2")  // add ","
   return num

function dosave () {
   var result;
   var t;      // text
   var m = "Duplicate nicknames are not permitted.\\n Please edit your nickname entries and resubmit this form. ";
   for (i = 2; i < document.forms.mainForm.elements.length; i++) {
     t = document.forms.mainForm.elements[i].value;
     t = t.replace(/\s/g, '_');
     eval("if (hash." + t + "== 1) {alert('" + m + "'); result = false} else {hash." + t + " = '1'}");
   if (result != false) {

Reverse the string:
var mystring = 'word1 word2';
var myregexp = /\s/ ; 
  // or you can make myregexp=''  to split after every char
var newArray = mystring.split(myregexp);
var my_out_string = unescape(newArray.join(''));

Value and reference:
var xmas1 = new Date(96, 11, 25); 
var xmas2 = xmas;     // Both variables now refer to the same object value.
xmas2.setDate(21);   // we change this object using 2nd ref.
xmas1.getDate();      // Returns 21, not the original value of 25.
var xmas3 = new Date(96, 11, 25); 
(xmas1 == xmas2)     // Evaluates to true
(xmas1 != xmas3)      // Evaluates to true. 2 DIFFERENT objects contain the same date.

// passing arrays to functions: they passed by copy of a reference as objects
// everything passed as copy of value (value of references for objects and arrays)
function add_base(arr, base) {
    for (i=0;i<arr.length;i++) arr[i] += base;

// Strings compared by value:
var s1 = "hello";
var s2 = "hell" + "o";
if (s1 == s2) alert("Strings compared by value");

Location, Links & Anchors:
parent.frames[0].location = "http://www.yahoo.com";
var ss = parent.frames[0].location.href;

d= window.document;

var text;
var a = d.anchors[i];
ns4 = (document.layers)? true:false; 

if (ns4) text = a.text;
else text = a.innerText;
if ((text == null) || (text == '')) text = a.name;

When using "location", how you can make sure that the browser will not use the cached version?
The solution which I use is to tag the url with a dummy parameter with the date in it - thus tricking the brower into thinking that you are requesting a different page.
  // -------------------------------
  var pageLink ='some_domain/cgi-bin/some_script.cgi?key1=value1&key2=value2';
   // here it goes
   var today = new Date();
   var ms = today.getTime();  // time in ms
   var cc = '&';    // use '?' if this will be the first parameter 
      pageLink += cc + 'ms=' + ms;   // I add this parameter to force reload of the page
   some_window.location.href = pageLink ;
   // some_window.location.href  = pageLink + '&ms=' + (new Date()).getTime();
   some_window.focus() ;
   // -------------------------------

You may tag this way any kind of a URL (even static html pages).

Other methods, which not always work or desirable:
  - use meta-tags in the headers of HTML pages. 
You can read more here: http://support.microsoft.com/support/kb/articles/Q234/0/67.ASP
There are 2 metatags: 
   <meta http-equiv="Pragma" content="no-cache"> 
   <meta http-equiv="expires" content="0"> 

  - Use javascript location.reload(true) command - doesn't necessarily work

function setcolor(w) {
    var r = (Math.random() * 256).toString(16);
    var g = (Math.random() * 256).toString(16);
    var b = (Math.random() * 256).toString(16);
    var colorString = "#" + r + g + b;
    w.document.bgColor = colorString;
    setTimeout('setcolor(' + w.name + ')', 1000);

Java Applets:
// In both browsers (IE & NS) javascript can call public methods in java applet.
// The method can accept and return numbers, strings and boolean values 
// (as parameters and return values).

var s1 = document.applets["myapplet"].public_java_method(p1,p2,...);
var s1 = document.myapplet.public_java_method(p1,p2,...);

// where

<applet code="Applet1.class" width=300 height=300 name="myapplet">...</applet>

In Netscape browser you can also pass back and forth objects 
(both Java and Javascript objects) using LiveConnect.

Add to favorites home - top of the page -

Instruction to add the page to favorites
var msg = '';
if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
  var url="http://www.yourdomain.com";
  var title="Your Label";
   var msg =  '<A HREF="javascript:window.external.AddFavorite(url,title);" '
    + 'onMouseOver=" window.status=' 
    + "'Add this site to your favorites!'; return true "
    + '"onMouseOut=" window.status='
    + "' '; return true "
    + '">Click on this <font color="#993399">link</font> '
    + 'to add this web page to your favourites - it means you can come here more easily in future.</a>';
} else {
var msg = "Press CTRL and D at the same time now. "
   +"That will add this web page to your bookmarks - it means you can come here more easily in future";

Here it is actually working: (text below should be different in IE and Netscape)

Loan Payments example home - top of the page -

Loan Payments Calculator: running example
<form name="loandata">
    <tr><td colspan=3><big><b>Enter Loan Information:</b></big></td></tr>
    <tr><td>1)</td><td>Amount of the loan (any currency):</td>
        <td><input type=text NAME=principal SIZE=12 onChange="calculate()"></td>
    <tr><td>2)</td><td>Annual percentage rate of interest:</td>
        <td><input type=text NAME=interest SIZE=12 onChange="calculate()"></td>
    <tr><td>3)</td><td>Repayment period in years:</td>
       <td><input type=text NAME=years SIZE=12 onChange="calculate()"></td>

    <tr><TD COLSPAN=3>
      <BIG><B><INPUT TYPE=button VALUE="Compute" onClick="calculate()">
        Payment Information:</B></BIG>
    <tr><td>4)</td><td>Your monthly payment will be:</td>
        <td><input type=text NAME=payment SIZE=12></td>
    <tr><td>5)</td><td>Your total payment will be:</td>
        <td><input type=text NAME=total SIZE=12></td>
    <tr><td>6)</td><td>Your total interest payments will be:</td>
        <td><input type=text NAME=totalinterest SIZE=12></td>


function round(x) { return Math.round(x*100)/100; }

function calculate() {
    var principal = document.loandata.principal.value;
    var interest = document.loandata.interest.value / 100 / 12;
    var payments = document.loandata.years.value * 12;

    var x = Math.pow(1 + interest, payments);
    var monthly = (principal*x*interest)/(x-1);

    if (!isNaN(monthly) &&
        (monthly != Number.POSITIVE_INFINITY) &&
        (monthly != Number.NEGATIVE_INFINITY)) {

        document.loandata.payment.value = round(monthly);
        document.loandata.total.value = round(monthly * payments)
        document.loandata.totalinterest.value = 
            round((monthly * payments) - principal);
    else {
        document.loandata.payment.value = "";
        document.loandata.total.value = "";
        document.loandata.totalinterest.value = "";


List to List  home - top of the page -

Copy selected items between 2 lists:

// ------------------------------------
function selectAll(aList, state) {
  for (var i=0; i<aList.options.length; i++) {
    aList.options[i].selected = state;

// ------------------------------------
function compare(aText, bText) {
  var  i = 0;
  aString = aText.toString(); aString.toLowerCase();
  bString = bText.toString(); bString.toLowerCase();
  if (aString < bString) return -1;
  else if (aString > bString) return 1;
  return 0;

// ------------------------------------
// removeItems() - remove selected options from a <SELECT> list
// ------------------------------------
function removeItems( sel ) {
  if( sel.selectedIndex < 0 ) return 0;
  var len = sel.options.length;
  var oo=0;  // oo - old indexes
  var nn=0;  // nn - new indexes
  while (oo < len) {
    // go through the list skipping selected options
    if( ! sel.options[oo].selected ) {
      sel.options[nn].text = sel.options[oo].text;
      sel.options[nn].value = sel.options[oo].value;
      sel.options[nn].selected = false;
  sel.options.length = nn; // cut the length to new smaller value
  return 1; // returns 1 on success, 0 on failure

// --------------------------------------
// moveItems(fromList, toList, toSort, toSelect)
//   - moves selected items from from List to toList
//   toSort (boolean) - sort the toList if true
//   toSelect (boolean) - select moved items in toList if true
//   needs these functions:
//        selectAll(), compare(),  removeItems()
// --------------------------------------
function moveItems(fromList, toList, toSort, toSelect) {
  if (fromList.selectedIndex < 0) return;
  selectAll(toList, false);
  for(var i=0; i < fromList.options.length; i++) {
    if (! fromList.options[i].selected) continue;
    addOption = fromList.options[i];
    var exist = false;
    for( var l = 0; l < toList.options.length; l++ ) {
      if( (addOption.text == toList.options[l].text)
         && (addOption.value == toList.options[l].value) ) {
                 exist = true;

    if( exist ) continue;

    var newOption =
      new Option(addOption.text, addOption.value, false, toSelect);
                 // text,       value,   defaultSelected, selected

    if (toSort) {
      var j;
      var to_length = toList.length;
      toList.options[to_length] = new Option('tt','vv');
      for (j=0; j<to_length; j++) {
        if (compare(newOption.text, toList[j].text) < 0) {
          for (k=to_length; k>j; k--) {
            toList.options[k].value = toList.options[k-1].value;
            toList.options[k].text = toList.options[k-1].text;
      toList.options[j] = newOption;
    } else { // no sorting
      toList.options[toList.options.length] = newOption; // add to the end

  } // for cycle

  removeItems(fromList); // remove selected items from the fromList
  return 1; // success


// note about creating new options and assigning them values/text in Internet Explorer:
//   1. you have to create a new object for each new option (you can't use the same object for more than one option)
//   2. you can't write option[i]=option[j];  you have to explicitely assign each property:
//        option[i].text=option[j].text;
//        option[i].value=option[j].value;

// Note about removing options from select lists:
// The standard documented way to remove list items from a select-list is to set them to null:
//   some_select.options[i] = null 
//  This works fine in IE and in most cases in Netscape.
// But sometimes (not always) Netscape crashes when:
//  - multiple items (as little as 2) were selected for removal
//   AND
//  - they were selected in the middle of the list


<table cellpadding=10><tr> <td>
   <select name=s1 multiple size=8>
    <option value=1>item1</option> 
    <option value=2>item2</option>
    <option value=3>item3</option>
    <option value=4>item4</option>
   <input type=button name=b1 value=">>" onClick="moveItems(this.form.s1, this.form.s2, false, false )"> <br>
   <input type=button name=b2 value="<<" onClick="moveItems(this.form.s2, this.form.s1, false, false )"> <br>
   <input type=button name=b3 value="del in list 2" onClick="removeItems(this.form.s2)">
    <select name=s2 multiple size=8>
    <option value=5>item5</option>
    <option value=6>item6</option>
    <option value=7>item7</option>
    <option value=8>item8</option>

Sorting a list of options in a select box:
// ------------------------------------
// ------------------------------------
function compare(aText, bText) {
    i = 0;
    aString = aText.toString(); aString.toLowerCase();
    bString = bText.toString(); bString.toLowerCase();
    if (aString < bString) { return -1; }
    else if (aString > bString) { return 1; }
    return 0;

// ------------------------------------
// this actually takes forever on long lists
// ------------------------------------
function sortOptions(mylist) {
  var copyOption = new Array();

  for (var i=0;i<mylist.options.length;i++)
        copyOption[i] = new Array(mylist[i].value, mylist[i].text);

  copyOption.sort(function(a,b) { return compare(a[0],b[0]); });

  for (var i=mylist.options.length-1; i>-1; i--)
        mylist.options[i] = null; // this may bomb in Netscape

  for (var i=0; i<copyOption.length; i++) {
    mylist.options[mylist.length] = new Option( copyOption[i][1],
      copyOption[i][0], false, false );
    mylist.options[mylist.length-1].selected = false;

Win2win example home - top of the page -

Win 2 Win Examples:

Open Window:
NS4 = (document.layers) ? 1 : 0;
IE4 = (document.all) ? 1 : 0;

var menuWindow
function view_menu(){
  if (! menuWindow || menuWindow.closed) { 
    menuWindow = window.open("popup_menu.html","menuWindow","scrollbars=yes,resizable=yes,height=300,width=500")
    // menuWindow.moveTo(200,200);
  else { 

TD {FONT-FAMILY: arial, geneva, helvetica; FONT-SIZE: 9pt;}

Update Opener from popup menu:
<html><head><title>some info</title>
<script language="JavaScript">
  function updateParent(newURL) {
    opener.document.location=newURL; self.close() 
<a href="javascript:updateParent('http://www.google.com')">here</a>
to change main window to Google<br>

<title> some </title>
<script language="JavaScript">
var newWindow
function makeWindow(){
 var str="<html><head><title>small window</title>"
 str+="<script language='JavaScript'>"
 str+="function updateParent(newURL) { opener.document.location=newURL; self.close() }"
 str+="<body>Type text and press the button to send text back to opener<p>"
 str+="<form onsubmit = 'return false'>"
 str+="<input type='text' name='info' value=''><br>"
 str+="<input type='button' value='send info' onClick="
 str+="<input type='button' value='close window' onClick="
 str+="<A HREF = \"javascript:updateParent('http://www.yahoo.com')\">goto yahoo and close menu</A><br>"
Sample application showing how to exchange data between 2 windows<p>
<form onsubmit = 'return false'>
<input type="button" value="Make new window" onClick="makeWindow()"><p>
<input type="text" name="result" value=""><br>
<input type='button' value='send info' 

Radio Buttons Example home - top of the page -

Radio Buttons Example:
  // ------------------------------------
  function myshow(ff) {
    var ss = "";

    for (var ii=0 ; ii< ff.group1.length ; ii++) {
      ss += ff.group1[ii].value
      ss += " " + ff.group1[ii].checked +"\n";
    ss += "\n";
    for (var ii=0 ; ii< ff.group2.length ; ii++) {
      ss += ff.group2[ii].value
      ss += " " + ff.group2[ii].checked +"\n";

  </script></head><body bgColor=#FFFFFF>
  <form name='form1'>
  <TEXTAREA NAME="mytext" ROWS="6" COLS="55" onclick='myshow()'></TEXTAREA>

  <input type='radio' name = 'group1' value='one' onclick='myshow(this.form)' CHECKED >rb11
  <input type='radio' name = 'group1' value='two' onclick='myshow(this.form)'>rb12
  <input type='radio' name = 'group2' value='one' onclick='myshow(this.form)' CHECKED >rb21
  <input type='radio' name = 'group2' value='two' onclick='myshow(this.form)'>rb22

  <br><a href='javascript:myshow(this.form)'>show</a>

Formcopy function example home - top of the page -

Form Copy function example:

function formcopy(f1,f2) {
        var ii=0;
        var ll = f1.elements.length;
        var myvalue='';
        for (ii=0;ii<ll;ii++) {
                var myname=f1.elements[ii].name;
                var mytype=f1.elements[ii].type;
                switch (mytype) {
                        case "hidden":
                        case "text":
                        case "textarea":
                        case "radio":
                                if (f1.elements[ii].checked == true) {
                        case "checkbox":
                                if (f1.elements[ii].checked == true) {
                       case "select-multiple":
                                var jj;
                                var v = '';
                                var mysep = '::::';
                          for (jj=0;jj<f1.elements[ii].options.length; jj++) {
                                if (f1.elements[ii].options[jj].selected == true) {
                                                if (myvalue.length > 0) myvalue += mysep;
                                                myvalue += v;
                        case "select-one":
                                var jj;
                                var v = '';
                          for (jj=0;jj<f1.elements[ii].options.length; jj++) {
                                if (f1.elements[ii].options[jj].selected == true) {
  return true;

Cookies home - top of the page -

A cookie is information that a Web site puts on your hard disk so that it can remember something about you at a later time.
* www.LevSelector.com/mem/perl_cgi/cookie.html - short Perl/Javascript/Java examples
* do search for cookielib on search engines ( www.google.com/search?q=cookielib ) - Matt's Script Archive: HTTP Cookie Library.
* www.zdnet.com/devhead/resources/scriptlibrary/javascript/cookies.html -
* www.hidaho.com/cookies/cookie.txt -
* www.cookiecentral.com/ -
* www.worldwidemart.com/scripts/cookielib.shtml -
* home.netscape.com/newsref/std/cookie_spec.html -
* www.netscapeworld.com/netscapeworld/nw-07-1996/nw-07-cookies.html -

Date pickers home - top of the page -

There are many examples of javascript date pickers:
* http://www.google.com/search?q=javascript+date+picker -
* http://javascript.internet.com/calendars/popup-date-picker.html-
* http://www.softricks.com/js/Calendar/Calendar.html -
   * http://www.softricks.com/js/Calendar/tutorial.html -
   * http://www.softricks.com/js/Calendar/faqs.html -
* http://html_help4u.tripod.com/datepick.html -
* http://uts.cc.utexas.edu/~esuez/cal5.html -
* http://www.siteexperts.com/tips/elements/ts29/page1.asp -

String home - top of the page -

String Object and string datatype are not the same - but in most cases JavaScript converts between them automatically. For example, when you invoke a String object method on a string value, JavaScript converts that value to a temporary String object, allowing the method to be invoked.

Properties - only one - length:
length The number of characters in the string. 
For any string s, the index of the last character is s.length-1.

anchor() Returns a copy of the string, enclosed within <a name="name"> and </a> HTML tags.
big()  Returns a copy of the string, enclosed between <big> and </big> HTML tags.
blink()  Returns a copy of the string, enclosed between <blink> and </blink> HTML tags.
bold() Returns a copy of the string, enclosed between <b> and </b> HTML tags.
charAt()  string.charAt(n)     //n is the index of the character to be returned

Extracts the n-th character from a string. The first character of the string is numbered 0. If n is not between 0 and string.length-1, then this method returns an empty string. Note that JavaScript does not have a character datatype that is distinct from the string type, so the returned character is a string of length 1.

fixed()  Returns a copy of the string, enclosed between <tt> and </tt> HTML tags.
fontcolor()  string.fontcolor(color)

Returns a copy of the string, enclosed between <font color="color"> and </font> HTML tags. The color argument is a string specifying the color name or value to be used as the value of the color attribute in the <font> HTML tag. Colors are specified either as one of the standard color names recognized by JavaScript, or as red, green, and blue color values, expressed as six hexadecimal digits (RRGGBB).

fontsize()  string.fontsize(size)

Returns a copy of the string, enclosed between <font size="size"> and </font> HTML tags. The size argument is an integer between 1 and 7 or a string that begins with a + or - sign followed by a digit between 1 and 7. If an integer is specified, it is an absolute font size specification. If a string is specified, the font specification is relative to the <basefont> size.

indexOf()  string.indexOf(substring) 
string.indexOf(substring, start)

Searches the string for an occurrence of substring. The search begins at position start within string, or at the beginning if no start is specified. start is an integer between 0 and string.length-1. Returns the position of the first occurrence of substring after the start position, or -1 if no occurrence is found.

italics()  Returns a copy of the string, enclosed between <i> and </i> HTML tags.
lastIndexOf()  string.lastIndex(substring) 
string.lastIndex(substring, start)

Searches the string backwards for an occurrence of substring. The search begins at position start within string, or at the end, if no start is specified. start is an integer between 0 and string.length-1. Returns the position of the first occurrence of substring before the start position, or -1 if no occurrence is found.

link()  string.link(href)

Returns a copy of the string, enclosed between <a href="size"> and </a> HTML tags. href specifies the URL target of the hypertext link that is to be added to the string. This string argument specifies the value of the HREF attribute of the <a> HTML tag.

small()  Returns a copy of the string, enclosed between <small> and </small> HTML tags.
split()  string.split() 

Converts a string to an array of strings, using a specified delimiter character/string at which the string will be split. If no delimiter is specified, then the returned array has only one element, the string itself. Note that the String.split() method is the inverse of the Array.join() method.

strike()  Returns a copy of the string, enclosed within <strike> and </strike> HTML tags.
sub() Returns a copy of the string, enclosed within <sub> and </sub> HTML tags.
substring()  string.substring(from, to)

Extracts a substring of a string. from is a value between 0 and string.length-1. to is an optional integer that is one greater than the position within string of the last character of the desired substring. to must be between 1 and string.length. The character at position from is included in the substring, while the character at position to is not. The returned string contains characters copied from positions from to to-1 of string.

sup()  Returns a copy of the string, enclosed within <sup> and </sup> HTML tags.
toLowerCase()  Returns a copy of the string, with all characters converted to lowercase.
toUpperCase()  Returns a copy of the string, with all characters converted to uppercase.
valueOf()  Returns the string value contained in the String object; Netscape 3.0 and later. See Object.valueOf().

Examples of usage:

A number of the String methods are used for creating HTML:

    link_text = "My Home Page".bold();

The code above code embeds the following string into the HTML document that is currently being parsed:

   <A HREF="http://www.djf.com/~david"><B>My Home Page</B></A>

The following code extracts the 3rd through 5th characters of a string and converts them to upper-case letters:


Math object home - top of the page -

Math Object is a read-only reference to a placeholder object that contains mathematical functions and constants. Math is itself an object, not a class of objects, so its constants and methods are invoked directly through it. Math is actually a global property of the Window object, and as such, is usually referred to as Math, rather than as window.Math. See also Number

There are functions and constants:


area = radius * radius * Math.PI;
y = Math.sin(x);

Math.E e = the base of natural logarithms
Math.LN2 The natural logarithm of 2
Math.LN10 The natural logarithm of 10
Math.LOG10E The base-10 logarithm of e
Math.LOG2E The base-2 logarithm of $e$
Math.PI The constant pi
Math.SQRT2 The square-root of 2
Math.SQRT1_2 The reciprocal of the square-root of 2

Methods (Functions):
abs Math.abs(x)   // x is any numeric value or expression Computes an absolute value.
acos Math.acos(x)  // x is a numeric value or expression between -1.0 and 1.0 radians Computes an arc cosine (inverse cosine). Return value is between 0 and pi radians.
asin Math.asin(x)  // x is a numeric value or expression between -1.0 and 1.0 radians Computes an arc sine (inverse sine). The return value is between -pi/2 and pi/2 radians.
atan Math.atan(x)  //x is any numeric value or expression Computes an arc tangent (inverse tangent) in radians. The return value is between -pi/2 and pi/2 radians.
atan2 Math.atan2(x, y)    // x, y are the coordinates of the point Computes the counter-clockwise angle from the positive X axis to a point (x, y). Performs half of the conversion between Cartesian coordinates and polar coordinates; computes and returns the angle theta of an (x, y) point.
ceil Math.ceil(x)  // x is any number or numeric expression Rounds a number up to the closest integer (i.e., computes the ceiling function); negative numbers are rounded up to 0.
cos Math.cos(x)   // x is any number or numeric expression, in radians Computes a cosine; the return value will be between -1.0 and 1.0 radians.
exp Math.exp(x)   // x is a number or numeric expression to be used as exponent Computes an exponent of $e$.
floor Math.floor(x) // x is any numeric value or expression Rounds a number down to the closest integer (i.e., computes the floor function); negative numbers are rounded to be more negative.
log Math.log(x)   // x is any numeric value or expression greater than 0 Computes a natural logarithm.
max Math.max(a, b)  // a, b are any two numeric values or expressions Returns the larger of two values.
min Math.min(a, b)  // a, b are any two numeric values or expressions Returns the smaller of two values.
pow Math.pow(x, y) Computes $x sup y$. (Raises its first argument to the power of its second argument and returns the result.)
random var r = (Math.random() * 256).toString(16); Computes a random number; 
round Math.round(x) // x is any numeric value or expression Rounds to the closest integer
sin Math.sin(x)   // x is an angle, in radians Computes a sine.
sqrt Math.sqrt(x)  // x is any numeric value or expression greater than or equal to 0 Computes a squareroot.
tan Math.tan(x) Computes a tangent.
atan Math.atan(x)  // x is an angle, in radians Opposite to tan

Number object home - top of the page -

Number Object

Numbers are a basic, primitive data type in JavaScript.

The Number() constructor:
  new Number(value)
is actually more commonly used as a placeholder for five useful numeric constants. Note that these values are properties of the Number() constructor function itself, not of individual number objects. For example, you use the MAX_value property as follows:

biggest = Number.MAX_value

not like this:
n = new Number(2);
biggest = n.MAX_value  // wrong

MAX_value The largest representable number.
MIN_value  The smallest (i.e., closest to zero, not most negative) number representable in JavaScript.
NaN Special Not-a-Number value. JavaScript prints the Number.NaN value as NaN. Note that the NaN value always compares unequal to any other number, including itself. Thus, you cannot check for the not-a-number value by comparing to Number.NaN. Use the isNaN() function instead.
NEGATIVE_INFINITY Special negative infinite value; returned on overflow. JavaScript displays the NEGATIVE_INFINITY value as -Inf. This value behaves mathematically like an infinity.
POSITIVE_INFINITY  Special infinite value; returned on overflow. JavaScript displays the POSITIVE_INFINITY value as Inf. This value behaves mathematically like an infinity.

toString() number.toString(radix)  // radix is an integer between 2 and 16 Converts a number to a string, using a specified radix (base).

By contrast, the toString() method of the Number object is a method of each Number object, not of the Number() constructor function. JavaScript implicitly invokes the Number() constructor to convert the number to a temporary Number object for which the toString() method can be invoked. Thus you can use the toString method with a variable that holds a number, even though that value is not actually an object:

var n = 1234;
var binary_string = n.toString(2);
var hex_string =  n.toString(16);

Array object home - top of the page -

Array Object

new Array()     // with no arguments, length field is set to 0
new Array(size)   //    size = number of elements; sets length
new Array(element0, element1, ..., elementn) // length set to number of elements

length a = new Array();     //  a.length initialized to 0
b = new Array(10);  // b.length initialized to 10
c = new Array("one", "two", "three");   // c.length initialized to 3
c[3] = "four";    // c.length updated to 4
c[10] = "blastoff";    // c.length becomes 11
You can also set the value
of the length property to change
the size of an array 
(i.e., truncate elements or add "undefined" ones).

Example: make multidimensional array as an array of arrays:

arr = new Array([1,2,3], [4,5,6,61,62], [7,8,9]);
ss = '';

ss+="total length: " + arr.length + " elements<br>\n";

for (i=0;i<3;i++) {
  var len = (arr[i]).length;
  ss += i + " => " + len + " elements: ";
  for (j=0;j<len;j++) 
    ss+=arr[i][j]+', ';


This script will produce the following output:

total length: 3 elements
0 => 3 elements: 1, 2, 3, 
1 => 5 elements: 4, 5, 6, 61, 62, 
2 => 3 elements: 7, 8, 9, 



join array.join()
If no separator, the empty string is used.  Converts each of the elements of an array to a string, and then concatenates those strings, inserting the specified separator string between the elements. Returns the resulting string. You can split a string up into array elements--with the split() method of the String object.
reverse Reverse, in place (i.e., without creating a new array), the order of the elements of an array.
sort array.sort()
array.sort(orderfunc)   // orderfunc - optional comparison function
With no arguments, sorts by asc; You may supply a function that compares two values (a & b) and returns a number  (-1, 0 or 1) indicating if a is less, eq. or greater than b.

Some functions home - top of the page -

Some Functions
escape( ) escape("Hello World!");  // returns Hello%20World% returns a new string that contains an encoded version of s to allow transmission of data. Commonly used to encode cookie values. See also String, unescape().
eval() eval(code) Executes Javascript code in its string argument. Returns the value
of the last expression in code that it evaluates.
isNaN( ) isNaN(x) Tests whether an argument (x) is "not a number". Commonly
used to test the results of parseFloat() and parseInt() to see if they represent legal numbers, or to check for arithmetic errors, such as division by zero.
parseFloat( ) parseFloat(s) // s is the string to be parsed and coverted to a number Parses and returns the first number that occurs in s (i.e., converts a string to a number). Parsing stops, and the value is returned, when parseFloat() encounters a character in s that is not a valid part of the number (i.e., a sign, a digit, decimal point, exponent, etc.). If s does not begin with a number that parseInt() can parse, then the function returns NaN.
parseInt( ) parseInt(s)
parseInt(s, radix) 
  //s is the string to be parsed
  //radix is the integer base of the number to be parsed
  // radix can be any value between 2 and 36.
Parses and returns the first number that occurs in the string s (i.e., it converts a string to an integer). Parsing stops, and the value is returned, when parseInt() encounters a character in s that is not a valid numeral for the specified radix. If s does not begin with a number that parseInt() can parse, then the function returns NaN.

If radix is 0, or if it is not specified, parseInt() tries to determine the radix of the number from s. If s begins with 0x, then parseInt() parses the remainder of s as a hexadecimal number. If s begins with a 0, then parseInt() parses the number in octal. Otherwise, if s begins with a digit 1 through 9, then parseInt() parses it as a decimal number.

unescape( ) unescape ('Hello%20World%21') 
  // returns  Hello World!
decodes a string encoded with escape() and returns the decoded copy. 
unescape() decodes s by finding and replacing character sequences of the form %xx, where xx is two hexadecimal digits.

Object Object home - top of the page -

Object Object - serves as the "superclass" for all other JavaScript objects, and therefore methods of the Object object are also methods of all other object types. The behavior of the Object object is also shared by all other object types. When an Object object is newly created, it has no properties defined; you can add a property definition to an object simply by assigning a value to the property. Objects can also be used
as associative arrays.

new Object();
new Object(value);

assign()  object.assign(value)    // value is the value to be assigned If defined, used to implement the JavaScript assignment operator (=).
eval()  eval(code) 
Evaluates a string of JavaScript code in the context of the given object.
toString()    . If defined, used to convert an object to a string.
valueOf()     . Returns the primitive value of the object, if any. For objects of type Object, this method simply returns the object itself. For other object types, such as Number and Boolean, this method returns the primitive value associated with the object.

Defining the toString(), method, and also the less frequently used assign() and valueOf() methods of an object, is most efficiently done in a
constructor method for your object type, or with the prototype object of your object.

// define a constructor for the Complex object type
   function Complex(x,y) { this.x = x; this.y = y; }

// give it a toString() method
   Complex.prototype.toString = new Function("return '{' + this.x + ',' + this.y + '}';");

// Create an object of this new Complex type
   c = new Complex(2, 2);

// Convert the object to a string, implicitly invoking the toString() method, and display the string.
   alert("c = " + c);