Script School Classroom

School Map:  Home / Enroll $ Student Records; Class  
$ News @ LIVE Tech Radio * Support/FAQ | Store | FORUMS

Script School Course #7 - JavaScript -  Week #5

Printable Version of this page HERE

More Information - Browsers, Referring Pages, Redirections, and Extra Goodies

In this, the final week of Script School's introductory course on JavaScript, we will cover:

Arrays

Arrays are built-in JavaScript Objects, which can hold multiple data values.  They can contain Strings, Numbers (integers & decimals), Objects (like other Arrays) and Booleans (true/false). Arrays are dynamic structures - they can change size as new data is added or removed. 

Creating Arrays

To create an Array, You can use:   reference = new Array(value1, valueN) or  reference = [value1, valueN]

Where italics indicates names or values You supply, bold indicates required structural elements.  The reference is a name (actually the name of a variable containing the Array) which becomes a 'handle' for the Array. Each element in an Array is separated by a comma. valueN indicates additional elements. You can add up to 4,294,967,295 elements, or values, to an Array.  However, extremely large Arrays will slow down Your programs - remember that JavaScript runs on Your client's computers - which may not be as fast as Yours!

Getting, Adding, Changing values in Arrays

Arrays are accessed by index integers, which begin at zero. You access the values in an Array with an index integer inside square brackets:

To get a value in an Array:  value = reference[0]
To add or change a value in an Array:  reference[0] = value; 

Web Site Array Example

In the code below You will notice that 'site1' is placed in Array element 0, site2 is in 1, and site3 is in 2. Also notice that the web addresses in the Array elements are quoted Strings. Each element is separated with a comma and an optional space.  We access the elements of the array with an index passed as the 'num' argument to the goToSite() function: (see Week #2 for a discussion on functions and Week # 3 on opening new windows)



   // In a script in the <HEAD>:
   
// Create an array containing web sites:
sites_array = new Array("http://www.site1.com", "http://www.site2.com", "http://www.site3.com");
// Create a function to open the sites in new windows: function goToSite(num) { window.open(sites_array[num],'site'+ num,'scrollbars=yes,resizable=yes,width=600,height=400'); } // In the <BODY>:
// access site1:
<a href="javascript:goToSite(0)">Go to site1</a> // access site2: <a href="javascript:goToSite(1)">Go to site2</a> // access site3: <a href="javascript:goToSite(2)">Go to site3</a> // Note: the above Links are Live

length and Array Methods

Click Here for a Description of length and several Array Methods

while loops

Often in scripts You will want to repeat a series of steps while certain conditions exist. The condition may involve a Boolean (true/false) flag or a value range that is changed by the user.  Or, You may want to access the elements of an Array by incrementing a counter that is also used as a conditional.  The while structure allows You to do this.  The lines within the French braces { } run any number of times while the conditional is true.  Be sure that at some point the condition becomes false, or You will create an endless loop that will crash computers.  A common mistake is to initiate a counter within the while loop, which will only reset the counter each time the loop repeats.


   while(conditional)
   {
      // do...
   }
   

To use with a counter:  Declare a Global variable for the counter, that is, declare it outside any French Braces...
Increment the counter.  You can use the shortcut  ++   which adds 1 to counter on each loop.

  
   var counter = starting_number;
   while(counter <= maximum)
   {
      // do...
      // using... myarray[counter] 
      // increment counter...
      counter++;
   }
   

The following example uses a while loop during a write to a new window. The new window will contain links with urls from an Array.  It also uses an Array for the text used in each link.  The advantage of this is that You can change all the links from one place, on the main page. Using advanced server scripts these links can be extracted from a database. 

View Example

do... while loops

do... while loops are similar to while loops except that the conditional occurs after the block of script.   This causes the block of script to run at least once.


   do {
      ...
   } while( conditional );
  

   var count = 0;        
   do {
      document.writeln("<TR><TD>"+ myarray[count] +"</TD></TR>");
      count++;
   } while (count < myarray.length);

for loops

for loops are also like while loops, but they have all the factors involved condensed into one structure, they include a place for the count variable - that runs once when the for loop begins, an area for the conditional - which is checked at the beginning of each loop, and an area to increment the count variable - an area which runs after every loop:


   for(initialize count variable; conditional statement; increment count)
{
statements to be executed }

For example: to quickly fill an Array with urls for Your site:


   myarray = new Array();
for(var i = 0; i < 10; i++)
{

myarray[i] = "www.mysite/page"+i+".com";
}

Or initializing and using two variables, so that the Array starts at 0, and the pages start at 1:


   myarray = new Array();
   for(var i = 0, j = 1; i < 10; i++, j++)
{ myarray[i] = "www.mysite/page"+j+".com"; }
Or we could have simply used the i variable, and added 1 to it to name the page. To do so we must use the top level Method  Number()  to add the 1 as a Number and not as a String, which would happen since we begin using the  +  character to join Strings.  Notice that the  +  character is being used as the String joiner and as the addition operator in the following code: 

   myarray = new Array();
for(var i = 0; i < 10; i++)
{

myarray[i] = "www.mysite/page"+Number(i+1)+".com";
}

for... in

The for... in structure allows You to easily get all the values of an array.  It automatically runs it's own internal counter, beginning at zero. It sequentially places the value of each of the Array's elements into a variable during each loop:


var total = 0; for ( var value in Array ) { total += value;
}

By using the  var  declaration in the structure, we are assuring that we will overwrite any Global variable that has the same name.  In the example above value is the name of a variable, You can use any allowable name You choose.  Array is any reference variable for - the name of - an Array You have created.  We have declared total as a Global variable, that is, outside the loop. Lines to be run within the loop are contained within French Braces  { }   Also notice that we are using  +=  this is the same as:  total = total + value 

switch - decision structure

The switch decision structure is a way to take actions when the comparison_variable is equivalent to a case value.  The optional  break;  causes the JavaScript interpreter to continue the script after the switch when a match is found, otherwise all of the do... statements following a match run also.  The optional  default :  do... statements are carried out if no matching case is found.  Note the required colons  :  used with the case and default lines.  Case values are literals, use quotes for Strings. 


switch ( comparison_variable )
{
case value1 :
    do... break; case value2 :
    do... break; default :
    do... }

switch example:


  switch ( page )
  { case "page1" :
showPage(1);
break;
case "page2" :
showPage(2);
break;
case "page3" : showPage(3); break;
default :
openWindow(0); }

  /* Notes:
- this case structure would be in a function called by a 'go' button
- page is a variable containing the selected value of a drop-down list
  - showPage() is a custom function that opens a page in a frame depending on it's argument
- default uses a custom function to open a special informative window,
if no choice was made but the 'go' button has been clicked
  */

switch structures are more limited than if structures since they cannot do comparisons on a range of values - such as:
 if( age < 18) { do... }  But, they can make code more readable.  switch structures are generally somewhat slower to execute than an equivalentif structure.

More on 'break' - About 'continue'

We have seen  break;  used in the switch structure, it can also be used in for, while, and do... while loop structures to stop execution of the loop and go on to process code following the loop. This may be done with an if inside the structure. 
 continue;  jumps out of a phase to the next loop phase within for, while, and do... while loop structures.  Again, this may be done with an if inside the structure.


  for(i=1; i <= 10; i++)
  { if(i == 5) { continue; }
document.write(i);
if(i < 10) {
document.write(", ");
}
  } // This results in writing: 1, 2, 3, 4, 6, 7, 8, 9, 10
// The 5 is skipped.

The navigator object - Identifying Your user's browser and other properties

JavaScript has a top level object known as navigator which contains various properties of the browser being used to view Your site.  If You write code that uses features only present in specific browsers You can redirect them to the right pages of Your site.  We'll see the use of some of these properties and discuss redirects in the next section.

Some frequently used properties of the navigator object are:

appName
Returns the name of the browser being used. Often 'Microsoft Internet Explorer' or 'Netscape'
appVersion
Returns a String in the format: releaseNumber (platform; country)
platform
String containing Machine type - Win32, Win16, Mac68k, MacPPC and various Unix.  This may be inaccurate due to emulators etc.

You can also find out about:

mimeTypes
Which mime types can be run on the user's machine.
Accessed as an Array:
    navigator.mimeTypes.length
    navigator.mimeTypes[0].description
    navigator.mimeTypes[0].enabledPlugin
    navigator.mimeTypes[0].enabledPlugin.name
    navigator.mimeTypes[0].suffixes
    navigator.mimeTypes[0].type
javaEnabled
Determines if they have the Java virtual machine running. Returns true or false.
language
Determine the browser's language version - usually a two character string, but this may vary - You can use this to provide a version of Your site in the user's language.

There are also other less useful properties and some that are only pertinent to older versions of Netscape.

Redirects

The location property of the window object allows You to set a window's URL or get information about the current URL.  Some important properties are: href - the full URL, replace - which replaces the history object's last entry and prevents users from using their back button to return to the previous page, reload - reloads the page, search - the part of a URL after a ? which contains variables added during a GET Form operation or when set in the URL. To cause the current window to load a different page:

   
window.location.href = "http://www.othersite.com";
// for the current window You don't need 'window.' : location.href = "http://www.othersite.com"; // leaving off .href defaults to the href property : location = "http://www.othersite.com"; // all of the above lines will do the same thing in the current window

Where window is either the word 'window' or a reference to another window or frame. (see week #3 of this course)

So, to redirect a link to a page according to the browser, call the following function from an onClick Event Handler passing the appropriate argument to the function call:


  // in the <HEAD> within <SCRIPT> tags:
function goToPage(num)
{
if(navigator.appName == "Microsoft Internet Explorer")
  { window.location.href = "http://www.mysite.com/IE/page"+ num +".html";
} else { window.location.href = "http://www.mysite.com/OtherBrowsers/page"+ num +".html"; }
}

// in the <BODY> :

<a href="javascript:void(0)" onClick="goToPage(2)">Page 2</a>

Which Page did they come from?

The document object has the property referrer that contains the full URL of the page that linked to the current page.  It could be empty if the user got to Your site by a bookmarked favorite or typed the URL into the Location box of their browser. 


   <html>
   <head>
   <title>Redirect</title>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
   <script language="JavaScript" type="text/JavaScript">
<!--
function checkReferrer(num) { // if the document.referrer property isn't blank: if(document.referrer) { // if they came from Your index check-in page... // Note: use the full URL: if(document.referrer == "http://www.mysite.com/index.htm") { // goToPage() redirects according to their browser goToPage(num); } else { // They came to this Navigation page from an 'illegal' external link... // send them to Your index check-in page: window.location.href = "http://www.mysite.com/index.htm"; } // no referrer: } else { // send them to Your index check-in page: window.location.href = "http://www.mysite.com/index.htm"; } } function goToPage(num) { // check which browser they are using: if(navigator.appName == "Microsoft Internet Explorer") { window.location.href = "http://www.mysite.com/IE/page"+ num +".htm"; } else { // send them to Your alternate browser page: window.location.href = "http://www.mysite.com/Alt/page"+ num +".htm"; } }
// --> </script> </head> <body> <a href="javascript:checkReferrer(1)">Page 1</a> <br><br> <a href="javascript:checkReferrer(2)">Page 2</a> <br><br> <a href="javascript:checkReferrer(3)">Page 3</a> </body> </html>

Breaking out of a Frameset

Within framesets,  top  refers to the topmost window that contains the frameset.  self  refers to the current document. We have seen the  location  keyword used in the discussion on  document.referrer  The code below can be read as if the top window does not contain this document (but perhaps is a frameset) then put the current page in the top (frameless) window:


if(top.location != self.location) {
top.location = self.location;
}

Bibliography

There are many good sources for information on JavaScript on the web
Some excellent sources that were still available when this course was written:

The original Netscape Client Side JavaScript Guide:
   http://developer.netscape.com/docs/manuals/js/client/jsguide/index.html
The original Netscape Client Side JavaScript Reference:
   http://developer.netscape.com/docs/manuals/js/client/jsref/
For the Microsoft-Centric 'JScript' version of JavaScript with features peculiar to Internet Explorer:
   msdn.microsoft.com/scripting/jscript/

For the most up to date books on JavaScript and many other topics, see the Script School Book Store.  New editions are always being added there. The prices are standard Amazon, and it will help keep Script School FREE!!!
At the time this course was written, the Principal of Script School: TDavid, and Your Instructor: logspirit, both recommended:
  "Visual Quickstart Guide - JavaScript for the World Wide Web" by Tom Negrino and Dori Smith  Peachpit Press

Assignments for this Week

Basic Assignment

Write a script that redirects users to a new page after 5 seconds.

Advanced Assignment

Use Arrays to hold a series of image links.  Create a 'slide show' that shows a new image every 5 seconds.
Show different sets of images, which are adjusted for Gamma, according to their platform - Windows or Apple.
(Images are much 'brighter' on Apples)

Final Words

Thank You for attending!  I hope this course will help You write more dynamic and exciting web pages.  Please continue to study, create and explore - to enhance Your own Life and the World.  As You gain wealth, please always remember to be Charitable to those who have had less fortunate circumstances.
    - logspirit -

Principal note: Logspirit was paid for writing this course material, as all authors have been. If you enjoyed the course material and found it particularly useful, perhaps you could give the author a tip? You can do that easily through PayPal by clicking the button to the left of this text.

If you are interested in writing and running a course at Script School, please contact the principal with your course ideas and outline and telephone contact number.

Need help with your assignment or have questions about this week's course?

About The Instructors

TDavid is co-owner, programmer and webmaster for several sites devoted to programming including his own http://www.tdscripts.com/ He has done custom programming in various programming languages for companies all over the world. Every Friday at 2pm PST you can catch his weekly radio show dedicated to the technical side of webmastering and programming at http://www.scriptschool.com/radio/

LogSpirit is a student of Script School, the co-author of this course and available for hire for custom programming.

Printable Version of this page HERE

School Map:  Home / Enroll $ Student Records; Class  
$ News @ LIVE Tech Radio * Support/FAQ | Store

Advertising | Link To Us | Privacy 
Copyright 2000-2002 Script School Productions / KMR Enterprises 
No part of this website may be reproduced, copied and/or distributed in any medium 
without express written permission