N341 Client Programming Overview

Modified

Getting Started

The W: drive on Windows systems will map files from the course Web server to your local computer. A few steps are required to setup the mapping.

IUS

  1. To map the W: drive:
    1. Computer
    2. Map Network drive
    3. Drive: W
    4. Folder: \\iu-uits-eiwp1.ads.iu.edu\username\wwwroot
    5. Finish
    6. Login using: ads\username
                        password
  2. Access files on Web server (the default file is index.htm): http://iu-uits-eiwp1.ads.iu.edu/username/index.htm

JHelloWorld.htm JavaScript
 
<H1>Hello World JavaScript</H1>

<SCRIPT LANGUAGE="JavaScript">
  for( i=1; i<=5; i++)
     document.write ("Hello World<br/>");
</SCRIPT>

 

Exercise 0 - JavaScript

  1. Open FrontPage. Look in Microsoft Office folder. 
  2. Open a new file by .
  3. Click on Code to see the HTML code:
  4. Delete all the existing HTML.
  5. Copy and paste the above JavaScript.
  6. Click Preview.

 

Key Script Programming Points

Mixed HTML/Script - Scripting languages are typically mixed with HTML in a single file. The HTML provides a user interface and the script program provide the logic. Consider the following JavaScript that displays Hello World 5 times.

<H1>Hello World JavaScript</H1>

<SCRIPT LANGUAGE="JavaScript">

   for( i=1; i<=5; i++)
     document.write ("Hello World<br/>" );

</SCRIPT>

 

<SCRIPT LANGUAGE> Tag

To distinguish script from HTML. Some possible languages are VBScript, JScript, JavaScript, and PerlScript.

 

document.write - Provides a way for the script to write to the browser with new HTML.

document.write ("Hello World<br/>");

 

Generating HTML - The document.write statement generates new HTML for the browser. For example, the following generates the HTML at right:

<SCRIPT LANGUAGE="JavaScript">

    document.writeln("<table border='1' cellspacing='0' cellpadding='0'>");
    document.writeln("<caption><center>4x3 Table</center></caption>");        

    for (row=1;row<=4;row++) {

         document.writeln("<tr>");

         for (col=1; col<=3; col++)

              document.writeln('<td>' + row + ',' + col + '</td>');

         document.writeln('</tr>');
    }

    document.writeln("</table>");

</SCRIPT>

4x3 Table
1,1   1,2   1,3  
2,1 2,2 2,3
3,1 3,2 3,3
4,1 4,2 4,3

<table border="1">
  <caption><center>
    <p>4x3 Table</p>
    </center></caption>
  <tr>
    <td>1,1</td>
    <td>1,2</td>
    <td>1,3</td>
  </tr>
  <tr>
    <td>2,1</td>
    <td>2,2</td>
    <td>2,3</td>
  </tr>
  <tr>
    <td>3,1</td>
    <td>3,2</td>
    <td>3,3</td>
  </tr>
  <tr>
    <td>4,1</td>
    <td>4,2</td>
    <td>4,3</td>
  </tr>
</table>

 

User-Interface

The user-interface HTML components, such as buttons, can interact with script code.

Consider the following JavaScript that displays the current time and the name entered in the text box when the button is clicked.

JHello.htm JavaScript

<SCRIPT LANGUAGE="JavaScript">

  function Button1_onClick() {
    document.write ("Hello " + document.NameForm.Text1.value + "<br/>")     
  }

</SCRIPT>

<FORM NAME="NameForm">

     Enter your name and click button: 

    <INPUT NAME="Text1" TYPE="TEXT" SIZE="10">

    <INPUT NAME="Button1" TYPE="BUTTON" 
              VALUE="Hello" onClick="Button1_onClick();">

</FORM>

Events

When a user clicks on a button, passes the mouse over a link, etc. an event is generated that can be used to execute a specific function. The examples above illustrate the onClick event handling, when Button1 is clicked a call is made to the Button1_onClick function.

The event handler must be explicitly designated (e.g. onClick="Button1_onClick()" ).

The event handler (function called) can be any name; Button1_onClick is the Button1 object and the onClick event.

 

Form Objects

User interaction occurs through buttons, text boxes, hyperlinks, etc. that can generate events to execute a script function, such as the onClick event. Buttons and text boxes are defined in a HTML form but can be referenced in a scripting language.

To define form ButtonInput with Button1 object as:

<FORM name=ButtonInput>
        <INPUT NAME="Button1" TYPE="BUTTON" VALUE="Button 1">
</FORM>

 

Form Object Access

Accessing a specific form object can be relatively simple. The following JavaScript changes the value of the Button1 object to "OK":

document.ButtonInput.Button1.value = "OK";
<SCRIPT LANGUAGE="JavaScript">

function Button1_onClick() {
   document.ButtonInput.Button1.value = "OK";
}

</SCRIPT>

<FORM NAME="ButtonInput">

   <INPUT NAME="Button1"   TYPE="BUTTON"  VALUE="Hello"   onClick="Button1_onClick();">
</FORM>

document.write

One common point of confusion is that:

The example below illustrates that behavior where any JavaScript outside a function is executed when the page is loaded; any function code is executed only when called, in this case only after the page is loaded and the user clicks the Hello button:

<SCRIPT LANGUAGE="JavaScript">

function Button1_onClick() {
   document.write( "Okey dokey <br/>");
}

</SCRIPT>

<FORM NAME="ButtonInput">

   <INPUT NAME="Button1"   TYPE="BUTTON" 
               VALUE="Hello"   onClick="Button1_onClick();">
</FORM>

displays the Hello button on the same page with any other HTML for the page.

The document.write executed when the button is clicked after the page is loaded causes the browser to generate a new page.

function Button1_onClick() {
   document.write( "Okey dokey <br/>");
}

 

Start Execution of Script

All scripting code outside of functions is executed when the form is loaded or refreshed. Function definitions are not executed until called.

Button1_onClick above is never executed until Button1 is clicked. In C++ and Java execution starts with a main function, in JavaScript, script execution starts with the first script code encountered outside of a function definition.

Any document.write statements encountered during loading the page are executed and added to the current window; this allows the script to construct the HTML displayed when the page is loaded by the browser.

Any document.write statements encountered after loading the page are executed and overwrite the current window; the effect is to overwrite the loaded HTML with new HTML, erasing the display and rendering the new HTML in the window.

Global variables - Any variable defined or first used outside of a function is globally accessible.

<SCRIPT LANGUAGE="JavaScript">

  n = 5;

 document.write( "n = " + n + "<br/>");

  function Button1_onClick() {
    sum = 0;
    for( i=0; i <= n; i++)
       sum = sum + i;
    document.write( "Summation of n = " + n + " is " + sum + "<br/>");
  }

</SCRIPT>

<FORM NAME="ButtonInput">
    <INPUT NAME="Button1" TYPE="BUTTON" VALUE="Sum" onClick="Button1_onClick();">
</FORM>

Exercise 1 - JavaScript Forms

Using the JavaScript program above as a starting point:

  • open the program to observe the effect when the page is loaded and when a new document.write is executed in Button1_onClick(),
  • add a Text input.

        <INPUT NAME="Text1" TYPE="TEXT" SIZE="10">
     

  • when the Sum button is clicked, compute the summation of the value in the text box (if 5 is in the text box, compute 5+4+3+2+1);

Hint: Trust the C++ or Java force, much of JavaScript has the same syntax. JavaScript data is dynamically typed so numbers and strings are interchangeable.

n = document.ButtonInput.Text1.value;

 

Passing Values to Script Functions

Values can be passed as function parameters. The following passes the document.TextInput.Text1.value to function Button1_onClick.

Button1_onClick( document.TextInput.Text1.value )

The Button1_onClick function accesses the document.TextInput.Text1.value object passed using the parameter name input.

function Button1_onClick( input )

Note that the parameter input is the value of document.TextInput.Text1.value or text.

Passing Values
<SCRIPT LANGUAGE="JavaScript"> 

  function Button1_onClick( input ) { 
    sum = 0;
    for( i=0; i <= input; i++)
       sum = sum + i;
    document.write( "Summation of " + input + " is " + sum + "<br/>"); 
} 

</SCRIPT> 

<FORM NAME="ButtonInput"> 
   <INPUT NAME="Button1" TYPE="BUTTON" VALUE="Sum" 
                         onClick="Button1_onClick(document.TextInput.Text1.value);"> 
</FORM> 

<FORM NAME="TextInput"> 
      <INPUT NAME="Text1" TYPE="TEXT" SIZE="10"> 
</FORM> 

 

Passing Objects to Script Functions

Objects (references) can be explicitly accessed, as above, or passed as function parameters.

Passing Objects
<SCRIPT LANGUAGE="JavaScript"> 

  function Button1_onClick( input ) { 
    sum = 0;
    for( i=0; i <= input.value; i++)
       sum = sum + i;
    input.size = 20;
    input.value = "Summation of " + input.value + " is " + sum ; 
} 

</SCRIPT> 

<FORM NAME="ButtonInput"> 
   <INPUT NAME="Button1" TYPE="BUTTON" VALUE="Sum" 
                         onClick="Button1_onClick(document.TextInput.Text1);"> 
</FORM> 

<FORM NAME="TextInput"> 
      <INPUT NAME="Text1" TYPE="TEXT" SIZE="1"> 
</FORM> 

 The following passes the document.TextInput.Text1 object to function Button1_onClick.

Button1_onClick(document.TextInput.Text1)

The Button1_onClick function accesses the document.TextInput.Text1 object passed using the parameter name input.

function Button1_onClick( input )

Note that the parameter input is precisely document.TextInput.Text1 so its attributes are only those of a text object.

The following assigns the value of the object passed.

input.value = "Summation of " + input.value + " is " + sum ;

 

The Document Object Model (DOM)

To access HTML objects in JavaScript, it is necessary to understand the hierarchical DOM structure, the model used to represent HTML (and XML, XSL, etc.) documents.

The following creates two objects named document.TextInput.Text1 and document.TextInput.Text2:

<FORM name=TextInput>
        <INPUT type="text" name=Text1 value="1">
        <INPUT type="text" name=Text2 value="2">
</FORM>

The DOM can be thought of as a tree with document at the root. The browser places all HTML tags (e.g. <b>, <FORM>, etc.) into the tree hierarchy for rendering. The above example can be represented as a tree structure as:

 

Access to the Text1 object is: document.TextInput.Text1

To change the value attribute of Text1 in JavaScript: document.TextInput.Text1.value = "42"

 

Arrays

JavaScript arrays, while similar to VB, C++ or Java arrays, are dynamically typed and created.

var color = ["Red", "Green", "Blue"];

defines an array color with the values:

color[0] = "Red";
color[1] = "Green";
color[2] = "Blue";

The following example uses an array to translate the colorNumber.value into the corresponding text. Note that the selection values are 0-2.

Arrays
<form name="SelectForm" action>
   <input name="colorNumber" type="text">
   <input name="print" value="Print Color" type="button"      
             onclick="printColor( colorNumber.value );">
</form>

<script language="JavaScript">
   var color = ["Red", "Green", "Blue"];

   function printColor( n ) {
      document.write( "Selected color: " + color[ n ] );
   }
</script>

Selected color: Green

 

Link Events

An example often used to simulate button presses using a graphic image is the mouseOver and mouseOut events.

The following switches between an image used as a link reference to another page. The name of the HREF (SYLLABUS.HTM in this case) is referenced, that could also be a parameter to the change function. The empty HREF="" and return=false are needed for some browsers, return false prevents processing of the HREF="".
 

 mouseOver.htm

<SCRIPT LANGUAGE="JavaScript">
    function change( newImage, name ) {
        name.src=newImage;
    }
</SCRIPT>

<H1>JavaScript Events</H1>
Moving the mouse over the image will switch from one image to another, and back when the mouse is out of the image. Clicking the image will load the page  referenced.

<A  HREF="Syllabus.htm"
   onMouseOver ="change('html_1.jpg', document.ONE)"
   onMouseOut   ="change('html_2.jpg', document.ONE)"
   onClick            ="change('html_3.jpg', document.ONE)">
   <IMG SRC="html_2.jpg" NAME=ONE WIDTH=15 HEIGHT=15 BORDER=0 ALT="SYLLABUS">
</A>


<A  HREF=""
  onMouseOver ="change('html_3.jpg', document.TWO)"
  onMouseOut   ="change('html_4.jpg', document.TWO)"
  onClick            ="change('html_3.jpg', document.TWO); return false;">
  <IMG SRC="html_4.jpg" NAME=TWO WIDTH=15 HEIGHT=15 BORDER=0 ALT="Nothing">
</A>

JavaScript Events

Moving the mouse over the image will switch from one image to another, and back when the mouse is out of the image. Clicking the image will load the page referenced.

 SYLLABUS Nothing

 

Explanation

<SCRIPT LANGUAGE="JavaScript">
   function change(newImage,name) {
      name.src=newImage;
   }
</SCRIPT>

Defines the function change but does not execute. When change is called by:

change('html_3.jpg', document.TWO)

the execution is:

document.TWO.src = 'html_3.jpg'

which makes the IMAGE SRC = 'html_3.jpg' for the HREF NAME=TWO.

Explanation

<A  HREF="Syllabus.htm">
<IMG SRC="html_2.jpg" NAME=ONE WIDTH=15 HEIGHT=15 BORDER=0 ALT="SYLLABUS"></A>

just defines a normal HREF link to "Syllabus.htm" that is has an image of  "html_2.jpg" and NAME=ONE.

The document.ONE can refer to this particular HREF.

 onMouseOver="change('html_1.jpg', document.ONE)"

executes the change function when the mouse is over the "html_2.jpg" image.

 

innerHTML

Clicking the anchor tag, <a HREF="Syllabus.htm"> Syllabus </a>, loads new HTML into the browser DOM, erasing the previously displayed page.

Selected parts of a page can change, leaving the rest unchanged. This is more natural than displaying a complete, new page to reflect small changes.

innerHTML
<span id="Example">Hello</span>

<form name="Example0">
    <INPUT type="button" value="Toggle" onClick="toggle()" />
</form>

<script language="JavaScript">
   var change = true;

   function toggle() {
      if( change )
         Example.innerHTML = 'Goodbye' ;
      else
         Example.innerHTML = 'Hello' ;
      change = !change;
}
</script>
Hello

The two parts that dynamically changes what the user sees is:

<span id="Example">Hello</span>

Example.innerHTML = "Goodbye"

where:

 

AJAX

AJAX (asynchronous JavaScript and XML) can load data from a file.

data.txt file contains 3 entries: name, photo and email each separated by ; to allow splitting into a string array.

data.txt file
Shato, William Paul;class2007_1749.jpg;wshato@ius.edu;
Wisman, Raymond F.;class2007_1746.jpg;rwisman@ius.edu;
Abourabine, Kristin M;class2007_1748.jpg;kabourab@ius.edu;
Adams, Vanessa Rene;class2007_1727.jpg;vadams@ius.edu;
Apple, William;class2007_1734.jpg;wapple@indiana.edu

The following loads the file into an array and displays the email of person 2, which is at array index 5:

<script type=text/javascript>
   var req = new ActiveXObject("Microsoft.XMLHTTP");

   req.open('GET', 'data.txt', false);
   req.send(null);

   s=req.responseText;

   var myArray = s.split(";");

   document.write( "email: " + myArray[5] );

</script>

 

email: rwisman@ius.edu

 

The important ideas are: