Lesson Plan

ITCSS Home Student Center TallTech Home
 

February 25, 2000

Details

Title

More statements, alerts, prompts, strings, & math.
Some practical examples of JavaScript

Time Allotment

6 hrs

Reading / References

  • Tutorial 7 - Programming with JavaScript  - New Perspectives Manual (NP)
  • Tutorial 8 - Programming with JavaScript  - New Perspectives Manual (NP)

Supplemental Web Sites

WebMonkey
http://www.hotwired.com/webmonkey/javascript/tutorials/tutorial1.html (beginner)
http://www.hotwired.com/webmonkey/javascript/tutorials/tutorial2.html (advanced)

Cut & Paste Javascript
http://www.infohiway.com/javascript/indexf.htm 

FreeSite
http://www.thefreesite.com/freejava.htm

Objectives (Morning)

Objectives (Afternoon)

Coursework / Lab Work (Morning)

Coursework / Lab Work (Afternoon)

Homework

Exercises (Morning)

Using the previous exercises as a reference:

Exercises (Afternoon)

Solutions

EXERCISE: LOOP EXERCISE WITH PROMPTS

<HTML>
<HEAD>
</HEAD>
<BODY>  
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide from older browsers
      
       var InitBal = prompt("What is the initial balance?", 1000);
       var IntRate = prompt("What is the initial interest rate?", 12);
       var Months = prompt("Calculate for how many months?", 12);
 
       document.write("Initial balance: " + InitBal + "<BR>");
       document.write("Interest rate: " + IntRate + "<BR>");
       document.write("Month&nbsp;&nbsp;&nbsp;&nbsp;Balance<BR>");
 
       var AccumBal = InitBal*1; //ensure that it is thinking it is a number
 
       for(i=1; i<=Months; i++)
       {
              AccumBal = AccumBal + (AccumBal * (IntRate/12/100) );
              document.write(i);
              document.write("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
              document.write(AccumBal + "<BR>");
       }
 
       document.write("Final balance is: " + AccumBal);                 
      
// End Hide -->
</SCRIPT>
 
</BODY>
</HTML>

Demo (Morning)

Alert Boxes

        alert ("A message to the user");

Prompting the user

var myvariable = prompt("Question goes here?", "Default Value");  

External references

         <SCRIPT LANGUAGE="Javascript" SRC="http://www.mydomain.com/myscript.js">
         </SCRIPT>
 

Looping through an array – compatibility?

         for count in myArray
         {
                  write(myArray[count]);
         }
 
Breaking out early

         count = 0;
         while (count < 10)
         {
           if (count == 5)
             break;
 
           write(count + "...");
           count++;
         }

Jumping to the next iteration
        for iteration in myArray
         {
            if (Math.odd(iteration))
              continue;
 
            writeln(myArray[iteration]);
         }
 
Strings
                Concatenation
                String methods
                                i.e. toUpperCase(), toLowerCase
                                changing attributes 

Working with the math functions
                Math functionality / methods
                               i.e. abs - absolute value, min, max, etc.

Demo (Afternoon)


Window Manipulation

Controlling the status bar

<a href="javascript:void(0)" onMouseOver="window.status='Display Text'; return true">
hyperlink viewed by the user
</a>

Default Status

window.defaultStatus = “message in bar”;

Document background & foreground colors

document.bgColor = “color”;
document.fgColor = “color”;

DEMO: Different hyperlinks to change colors of background

Opening New Windows

HTML
<A HREF="newwindow.htm" TARGET="mywindow">open window</a>
<A HREF="newwindow2.htm" TARGET="mywindow">open window</a> - opens to same window

JavaScript
window.open("URL","name","features");
<a href="#" onClick="window.open('javascript_window_1.html','javascript_1');">Here's a window named javascript_1</a>.  

open with
window.open("http://www.talltech.com ","window_name","location,menubar"); 

sizing
window.open("http://www.talltech.com","window_name"," location,height=100,width=100"); 

for a list of features see:
http://www.hotwired.com/webmonkey/98/03/index3a_page5.html?tw=javascript

Another Window Example

<!-- JavaScript: The Window Gallery -->
<html>
<head>
    <title>Windows</title>
<script language="JavaScript">
<!-- hide me
function defaultWindow()
{
  default_window = window.open("http://www.hits.org/","default");
}
 
function plainWindow()
{
  plain_window = window.open("http://www.hits.org/","plain","width=50,height=50");
}
 
function locationWindow()
{
  location_window = window.open("http://www.hits.org/","locate","location,resizable");
}
 
// end hide -->
</script>
</head>
 
<body>
<h1>Here are a bunch of different windows</h1>  
<a href="#" onClick="defaultWindow();">The default window</a><br>
<a href="#" onClick="plainWindow();">A small, plain window</a><br>
<a href="#" onClick="locationWindow();">A resizable window with a location box</a><br>
 
</body>
</html>


Image rollover

Step #1

Create two sets of graphics. The first graphic appears in it’s normal state, the other appears in it’s hovered state. 

Step #2

Insert HTML code to: (1) Insert the graphic, name the graphic, and trap mouse events.

<A HREF="URL" onMouseOver="document.myimage.src='hover.gif';" onmouseout="document.myimage.src='normal.gif';">
  
<img SRC="normal.gif" name="myimage" border="0">
</A>  

Step #3

Create a script that will preload the graphics 

<script language="JavaScript">
<!--
   function loadgrx()
   { 
       
g1 = new Image();
        g1.src = "hover.gif";
    }
//-->
</script> 

Step #4

Call the graphic preload on document load.

<body onLoad="loadgrx()">

Another Preload Example

Usage:

WM_preloadImages('image 1 URL', 'image 2 URL', 'image 3 URL', ...);

Script:

<script language="JavaScript">
<!--

function WM_preloadImages() {
  // Don't bother if there's no document.images
  if (document.images) {
    if (typeof document.WM == 'undefined'){
      document.WM = new Object();
    }
    document.WM.loadedImages = new Array();
    // Loop through all the arguments.
    var argLength = WM_preloadImages.arguments.length;
    for(arg=0;arg<argLength;arg++) {
      // For each arg, create a new image.
      document.WM.loadedImages[arg] = new Image();
      // Then set the source of that image to the current argument.
      document.WM.loadedImages[arg].src = WM_preloadImages.arguments[arg];
    }
  }
}
// -->
</script>
 


Determining the Browser  / Custom Browser Code

navigator.appName

Microsoft Internet Explorer
Netscape 

Navigator.appVersion

Example 1(browser differences):

<SCRIPT Language="JavaScript">
<!--hide language from non-compatable browsers
if (navigator.appName == "Microsoft Internet Explorer")
{
    document.writeln('<TD WIDTH=80>&nbsp;</TD>')
}
else
{
    document.writeln('<TD WIDTH=200>&nbsp;</TD>')  
}
// end hiding script-->
</SCRIPT>         

Example 2 (a little biased):

<script Language="JavaScript">
<!--hide language from non-compatable browsers
document.writeln(“You are using “ + navigator.appName + "!");
if (navigator.appName == "Netscape")
{
    document.writeln(" How could you?!");
} 
else
{
    document.writeln(" Fine choice.");
}             
// end hiding script-->
</script> 

Example 3 (browser redirection):

<script Language="JavaScript">
<!--hide language from non-compatable browsers
document.writeln(“You are using “ + navigator.appName + "!");
if (navigator.appName == "Netscape")
{
    location = "ns_version.html";
} 
else
{
    location = "ie_version.html";              
}             
// end hiding script-->
</script>


Setting form contents

Response to mouseover of anchors (edit controls):

<form name="first_form">
    <input type="text" name="first_text" value="Are you happy?">
</form>

<a href="#" onMouseOver="window.document.first_form.first_text.value='Clap clap!';">Yes, and I know it.</a>
<a href="#" onMouseOver="window.document.first_form.first_text.value='Sour puss!';">No!</a>

Response to mouseover of anchors (text area):

<script language="JavaScript">
<!-- hide me 

var first_part = "Now I'm the king of the swingers\nOh, the jungle VIP\nI've reached the top and had to stop\nAnd that's what botherin' me";

var second_part = "I wanna be a Webmonkey, mancub\nAnd stroll right into town\nAnd be just like the other Webmonkeys\nI wanna start monkeyin' around!";

// show me -->
</script>

<form name="form_two">
<textarea name="the_textarea" rows=10 cols=60>
Mouse over below to see the first verse of The Webmonkey song, adapted from"I Wanna
Be Like You" (The Monkey Song)from Walt Disney's The Jungle Bookwritten by
Richard M. Sherman and Robert B. Sherman
</textarea>
</form> 

<a href="#" onMouseOver="window.document.form_two.the_textarea.value=first_part;">Part 1</a>
<a href="#" onMouseOver="window.document.form_two.the_textarea.value=second_part;">Part 2</a>


Responding to form actions

<FORM METHOD=POST
      ACTION=""
      NAME="comments"
      onSubmit="
               if (this.name.value == '')
               {
                   alert('Please enter your name')
                   return false
               }
               else if (this.email.value == '')
               {
                   alert('Please enter your email address')
                   return false
               }
               else if (this.email.value.indexOf('@',0) < 0)
               {
                   alert('Please enter a valid email address')
                   return false
               }
               ">  

Name:    <INPUT NAME="name" SIZE=30><P>
Email:   <INPUT NAME="email" SIZE=30><P>
Checkbox <INPUT NAME="check"
                TYPE=checkbox
                onClick="alert('You clicked the checkbox')"><P>  

Checkbox2 <INPUT NAME="check2"
                TYPE=checkbox
                onClick="if (this.checked == true)
                         {
                             alert('Checkbox is checked.')
                         }
                         else
                         {
                             alert('Checkbox is cleared.')
                         }
                        "><P>

Radio Control:<BR>
<BLOCKQUOTE>
   <INPUT NAME="radio" TYPE=radio onClick="alert('Option 1')" CHECKED>Option 1<BR>
    <INPUT NAME="radio" TYPE=radio onClick="alert('Option 2')">Option 2<BR>
    <INPUT NAME="radio" TYPE=radio onClick="alert('Option 3')">Option 3<BR>
</BLOCKQUOTE>
<HR>
<INPUT TYPE=SUBMIT><INPUT TYPE=RESET>
</FORM>


Using other libraries of JavaScript

Form completion

Usage:

IsFormComplete("theFormName") 

Script:
 
<script language="JavaScript">
<!--
function IsFormComplete(FormName)
{
var x       = 0
var FormOk  = true
 
while ((x < document.forms[FormName].elements.length) && (FormOk))
   {
     if (document.forms[FormName].elements[x].value == '')
     {
        alert('Please enter the '+document.forms[FormName].elements[x].name +' and try again.')
        document.forms[FormName].elements[x].focus()
        FormOk = false
     }
     x ++
   }
return FormOk
}
// -->
</script>


Email entry validation

Usage:  

IsEmailValid("FormName","ElemName") 

Script:

<script language="JavaScript">
<!--
function IsEmailValid(FormName,ElemName)
{
var EmailOk  = true
var Temp     = document.forms[FormName].elements[ElemName]
var AtSym    = Temp.value.indexOf('@')
var Period   = Temp.value.lastIndexOf('.')
var Space    = Temp.value.indexOf(' ')
var Length   = Temp.value.length - 1   // Array is from 0 to length-1
 
if ((AtSym < 1) ||                     // '@' cannot be in first position
    (Period <= AtSym+1) ||             // Must be atleast one valid char btwn '@' and '.'
    (Period == Length ) ||             // Must be atleast one valid char after '.'
    (Space  != -1))                    // No empty spaces permitted
   { 
      EmailOk = false
      alert('Please enter a valid e-mail address!')
      Temp.focus()
   }
return EmailOk
}
// -->
</script>