Valid
	XHTML 1.1! Valid CSS!
Created 2005-06-20   Modified 2008-05-11
Chelton Evans

phpnotes Java Script Java Script home

AJAX tutorial
Developing JavaScript
Cookies
Accessing the Documents Elements
Strings
Check Box Example
eval
OO Java Script
    Approach 1
    Approach 2
    Passing by Reference
Navigating the DOM
Parse a XML string
Dynamic HTML
Misc
Cross Browser Issues

Examples

JavaScript Examples   clock   buttons and text output window   Dynamic Style   Form with function   Dark Services   Dark Services 2   tabs 1   tabs 2   tabs 3   Reference   Browse Images   Dynamic Tables   Sorting Tables   Drop Down Menu   Drop Down Menu 2   Show/Hide content box  

By file name

j001.html   j002.html   j003.html   j004.html   j005.html   j006.html   j007.html   j008.html   j009.html   j010.html   j011.html   j012.html   j013.html   j014.html   j015.html   j016.html   j017.html   j018.html   j019.html   j020.html   j021.html   j023.html  

Applications

RPN Calculator     School Assignment  

Developing Java Script

I used Mozilla's Tools>Web Development>Java Script Console. This gives the exact line number where the script is broken. After java-script breaks, from that point on further java-script may well be broken. The java-script is interpreted as the html is interpreted from top to bottom of a web page.

Place as much java-script in js files so it separate from html where possible or isolated.

<head>
...

<script type="text/javascript" src="orders.js"></script>
</head>

This reads in the java-script declarations and possibly executes code. Then later on you can call the java-script functions from within your html. One way is to use the script embedding.

<script type="text/javascript"> bannerright(); </script>

The same script tag can be used to embed java-script directly.

Using the validator also improves your java-script because it tells you when you are using absolute techniques. I validate with Strict html.

Accessing the Documents Elements

I use a simple mechanism. Give the whatever an id and grab the object through it.

Wrap the input inside a form and give the form no action.

<form id="CustomerDetailsForm" action="java-script:void(0)">

<p>Enter your address. <br/>
Street:   
<input id="AddressStreet" type="text" /><br/>
City:  
<input id="AddressCity" type="text" /> <br/>
Postcode:  
<input id="AddressPostCode" type="text" size="5" />
</p>

To access AddressPostCode, refer to document.getElementById("AddressCity").value . This is a string.

So the variable is accessed in java script by the above call to the document, but how is the java script triggered in the first place?

Here is an example of a button that triggers a java-script function call. The function does everything - its job is to read any data. The only thing the html input does is the trigger. This minimizes the amount of java-script in the html which makes the html easier to manage.

<p>
<input id="Submit" type="button" value="Submit" onclick="OrderSubmit()" />
</p>

Cookies

Cookies can be used in a couple of ways. One cookie for each value, or one cookie has a list of keys with values.

For the simple way of using a cookie, just bake it, access it and delete it. For example if (CookieGet("Target")==null) { ... the cookie does not exist.

Cookies can also be used to keep track of the state. e.g. redirecting to another page if the state is not good.


/*
http://home.cogeco.ca/~ve3ll/jstutor9.htm
*/

function CookieBake(name,value) {
   argv=arguments;
   argc=arguments.length;
   expires=(argc>2) ? argv[2] : null;
   path=(argc>3) ? argv[3] : null;
   domain=(argc>4) ? argv[4] : null;
   secure=(argc>5) ? argv[5] : false;
   document.cookie=name+"="+escape(value) +
     ((expires === null) ? "" : ("; expires="+expires.toUTCString())) +
     ((path === null) ? "" : ("; path="+path)) +
     ((domain === null) ? "" : ("; domain="+domain)) +
     ((secure === true) ? "; secure" : "");
}

function CookieEat(name) {
   arg=name+"=";
   alen=arg.length;
   clen=document.cookie.length;
   i=0;
   while (i<clen) {
      j=i+alen;
      if (document.cookie.substring(i,j) == arg) {
          return EatCookieVal(j);
          }
      i=document.cookie.indexOf(" ",i) + 1;
      if (i === 0) {break;}
   }
}
function CookieEatVal(offset) {
   endstr=document.cookie.indexOf(";",offset);
   if (endstr == -1) {endstr=document.cookie.length;}
   return unescape(document.cookie.substring(offset,endstr));
}

/* Debuged and fixed this code
 * by looking at the following websited. 
 * http://www.java-scriptworld.com/scripts/script12.05.html
 */
function CookieDelete(name) {
  expDate=new Date();
  expDate.setDate(expDate.getDate()-1);
  document.cookie=name+'=;expires='+expDate.toGMTString();
}



/**
 * From http://www.netspade.com/articles/java-script/cookies.xml
 *
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function CookieGet(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

Misc


/*  roundOff function from 
 *  http://java-script.internet.com/calculators/horsepower.html
 */
function roundOff(value, precision) 
{
  value = "" + value;
  precision = parseInt(precision);
  var whole = "" + Math.round(value * Math.pow(10, precision));
  var decPoint = whole.length - precision;
  if(decPoint != 0) 
  {
    result = whole.substring(0, decPoint);
    result += ".";
    result += whole.substring(decPoint, whole.length);
  }
  else
  {
    result = whole;
  };
  return result;
}


/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function echeck(str) 
{
  var at="@";
  var dot=".";
  var lat=str.indexOf(at);
  var lstr=str.length;
  var ldot=str.indexOf(dot);
  if (str.indexOf(at)==-1)
  {
    alert("Invalid E-mail ID");
      return false;
  }

  if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
  {
    alert("Invalid E-mail ID");
    return false;
  }

  if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
  {
    alert("Invalid E-mail ID");
    return false;
  }

  if (str.indexOf(at,(lat+1))!=-1)
  {
    alert("Invalid E-mail ID");
    return false;
  }

  if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
  {
    alert("Invalid E-mail ID");
    return false;
  }

  if (str.indexOf(dot,(lat+2))==-1)
  {
    alert("Invalid E-mail ID");
    return false;
  }
		
  if (str.indexOf(" ")!=-1)
  {
    alert("Invalid E-mail ID");
    return false;
  }

  return true;
}



function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   
  var i;
  var returnString = "";
  // Search through string's characters one by one.
  // If character is not in bag, append to returnString.
  for (i = 0; i < s.length; i++)
  {   
    // Check that current character isn't whitespace.
    var c = s.charAt(i);
    if (bag.indexOf(c) == -1) returnString += c;
  }
  return returnString;
}


Strings

A lot of java script does horrific things with strings. Quoting within a string is notorious in Unix and nesting of quotes is at times frustrating.

Here is an example of backslashes or escaping the " character. So you can include it in the one string.

  document.writeln(
"<img src=\"images/contact_off.gif\" id=\"menu05\"  alt=\"contact_off.gif\" /></a>"
  );

This results in the following html.

<img src="images/contact_off.gif" id="menu05"  alt="contact_off.gif" /></a>

Check Box Example

var dvdimgs = new Array();
var dvdtitle = new Array();
var dvdprice = new Array();


var dvdcount=0;
var dvdcurrent=0;

function init()
{
  var i=0;
  
  dvdtitle[i] = "Amusement Park";
  dvdprice[i] = 29.99;
  dvdimgs[i++] = 'images/dvd01s.jpg';

...



function dvdSubTotalcalculate()
{
  dvdsum=0.0;
  dvdCheckBox=document.getElementById("dvdform").dvdCheckBox;
  var i=0;
  for ( ; i<dvdcount; i++)
  {
    if (dvdCheckBox[i].checked)
      dvdsum += dvdprice[i];
  };
  dvdsum = roundOff(dvdsum,2);
}

function dvdorderscheckbox()
{
  document.writeln("<div class=\"float15\">");
  document.writeln("<form id=\"dvdform\" action=\"java-script:void(0)\" >");

  var i=0;
  for ( ; i<dvdcount; i++)
  {
    document.write("<input type=\"checkbox\" id=\"dvdCheckBox\" onclick=\"dvdSubTotalwrite()\" "); 
    document.write(" value=\"\"" + i);
    document.writeln(">" + dvdtitle[i] + " <br/>");
  }
  for ( i=0; i<20; i++)
    document.write("  ");
  document.writeln(" Sub-Total");

  document.writeln("</form>");
  document.writeln("</div>");

  document.writeln("<div class=\"float10\">");
  i=0;
  for ( ; i<dvdcount; i++)
  {
    document.writeln("$" + dvdprice[i] + "<br/>");
  }

  document.writeln("<form id=\"dvdSubTotalCart\" action=\"java-script:void(0)\">");
  document.write("<input type=\"button\" id=\"dvdSubTotalButton\" ");
  document.writeln("value=\"0.0\" onclick=\"dvdSubTotalwrite()\" />");
  document.writeln("</form>");

  document.writeln("</div>");
}

eval

Build a string an have it evaluated. e.g.
Let cmd have the value of "test1".
var t1 = "myfunc_" + cmd + "();";
eval(t1);

This produced the call to
myfunc_test1();

I used this to "program in the html" rather than the js script. e.g.
html:
<input type="button" value="-" onclick="calcpressedbutton('test1')"></input>
js script code:
function calcpressedbutton(cmd)
{
var t1 = "myfunc_" + cmd + "();";
eval(t1);
... }

OO Java Script

Object Orientated programming is about objects - and programming from their perspective. A object can also be called a class - even though java-script uses functions the idea is what is important, after you do OO you change the way you program in procedural languages.

An object/class mixes functions and data. Private variables are not necessary for OO - they are a convenience.

My Object Orientated Conventions

There are a few ways to do OO in java-script. Here are two approaches I have looked at. Further restrictions/use of java-script to achieve OO.

Approach 1

Object Orientated Java Script is easy to do if you reconsider the way you do things. For example instead of explicitly declaring public variables you can equivalently use this and define them within a function.

Consider the following class which has three variables name, id and position, two constructors (uniquely named) and a function toMyString.

See j007.html j007.js

function MyRow()
{
  
  /** Constructor - uninitialized state */
  this.empty= function()
  {
    this.name="";
    this.id="";
    this.position="";

    return this;
  }

  /** Constructor */
  this.nameIdPosition = function(name_,id_,position_)
  {
    this.name=name_;
    this.id=id_;
    this.position=position_;

    return this;
  }

  /** Write a row of a table */
  this.toMyString = function()
  {
    return ("<tr>"<td>" + this.name + ""</td>"<td>" + this.id + 
 ""</td>"<td>" + this.position + ""</td>"</tr>");
  }

}

Now while there are no fancy overloaded constructors to use, the object can be constructed in multiple ways.

this is returned as a technique to do initialization and construction on the one line.

(new MyRow()).nameIdPosition("Wilma",0,3)

Virtual Functions Equivalent

Call the same function signature on different objects.

Approach 2 has a better solution because this technique does not work with single inheritance - from within the classes own scope virtual functions are useful.

See j008.html j008.js

function A1()
{
  this.print = function()
    { document.writeln("print A1"); }
}

function A2()
{
  this.print = function()
    { document.writeln("print A2"); }
}

function B1()
{
  this.print = function()
    { document.writeln("print B1"); }
}

function A4()
{
  this.print = function()
    { document.writeln("print A4"); }
}


function test01()
{
  ai = new Array();

  ai.push(new A1);
  ai.push(new A2);
  ai.push(new B1);
  ai.push(new A4);

  var index;
  for (index in ai)
    ai[index].print();
  
}

Approach 2

In OO inheritance is not necessary - composition can do anything inheritance can do. However inheritance is simple and re-uses code. Mixing single inheritance and composition really gives you a lot.

Inheritance in java-script can be achieved through assignment.

/* Defining a class with a few functions. */
function B1() {}
B1.prototype.getName = function()
  { return "B1=" + this.getId(); }
B1.prototype.getId = function()
  { return 1; }
B1.prototype.getInfo = function()
  { return this.getName(); }
B1.prototype.getName2 = function()
  { return "B1=" + this.getId.call(this); }

/* Defining an inherited class */
function C1() {} 
C1.prototype = new B1();
...

See Testing OO Javascript - Inheritance

Compare the two approaches on the same code.     Approach 1: j007.html j007.js   Approach 2: j010.html j010.js

Passing by Reference

Programming languages with pointers pass the pointer or reference to the object as a variable in the function. With classes and global scope this can be achieved.

The variable is defined within a class(really a function). The variable is separated into two - a reference to the class - and then a text string to the property name.

For example t01.myarr to t01 and "myarr". See Reference

See Javascript Square Bracket Notation in the "String variables as Identifiers" section.

function setPropertyToValue(obj,objProp,value)
{
    obj[objProp] = value;
}

Navigating the DOM

Search for the div block with id="b01". All the elemnents in this div block with a "p" tag are found, then a color applied.

function blockchanged02()
{
    var x = document.getElementById("b01");
    var y = x.getElementsByTagName("p");
    for (var i = 0; i < y.length; i++ )
    {
        y[i].style.color = "#00FF00";
    }
}

Finding elements by class. Build a class iterator.

function getElementByClass(rootobj, classname)
{
    var temparray=new Array()
    var inc=0
    var rootlength=rootobj.length
    for (i=0; i<rootlength; i++)
    {
        if (rootobj[i].className==classname)
            temparray[inc++]=rootobj[i]
    }

    return temparray
}

Search all elements on class="float25". By convention these are in div tags.

/* w - the width e.g. w='30em' */
function blockchanged05(w)
{
    var x = getElementByClass(document.getElementsByTagName("*"),'float25');
    for (var i = 0; i < x.length; i++ )
    {
        x[i].style.width = w;
    }
}

See Dynamic Style

Accessing or reading html can be frustrating. Here is a way of reading a list in html and extracting its strings. First the list is gotten by a getElementById call. Then the li tags are extracted. Then their values are extracted and added to an array.

...
mymodel.Software = new Array();
var x = document.getElementById("software_list");
var y = x.getElementsByTagName("li");
var i;
for (i=0; i<y.length; ++i)
{
    mymodel.Software.push(y[i].lastChild.nodeValue);
}

Dynamic HTML

var table = document.getElementById("invoiceTable");
var tr = document.createElement('tr');
for (var i=0; i<5; ++i)
{
    var td = document.createElement('td');
    td.className = classname;
    var text = document.createTextNode(row[i]);
    td.appendChild(text);
    tr.appendChild(td);
}
table.appendChild(tr);

Creating html on the client side is critical. The above is an example of dynamically building a table row.

Here is a technique for updating the container. An outer tag wraps the container. Call the container and use its parent to delete it. Then recreate the container with the new data. Insert the new container back in using the outer tag. ie Model-View

html: <div id="invoiceDiv"> <table id="invoiceTable"> ...
var table0 = document.getElementById("invoiceTable");
if (table0)
    table0.parentNode.removeChild(table0);

See Dark Services for a bad example (no data/view separation) and see Dark Services 2 where the underneath data representation is in OO objects.

For example when a server wants to update parts some part of its page, it transfers the data as xml to the client. The client reads it and builds its model. The model is used to then write a view (e.g. the dynamic html). AJAX.

Popups and Redirection

<a href="javascript:var newWin=window.open ('http://natio.com.au/voyages/', 'mywindow','status=2,toolbar=1');"> test2 </a>

Cross Browser Issues

Firefox easier that IE - as has error console, MS is painful. Looking at what works in both browsers.