JAVASCRIPT REFS:
    http://Bignosebird.com/
    http://javascript.internet.com/
    http://www.javascriptguide.com/
alert_red.gifNOTE: I am beginning to integrate FIBs into this LM, so you will see text, like  browser (), which is simply a reminder to me to turn this into an FIB, e.g. ___________(10) when I rewrite the module.  Don't let this confuse you; you are lucky; the answer is there in front of you, but future students will have to refer to hints/answers to find this after I rewrite.
{ADD SAQS}

alert_red.gifDrafted: 4/26/00; major rewrites: 3/20/01, 4/14/01;  11/20/02alert_red.gif
Currently being created!

COSC 330

LEARNING MODULE VII
INTRODUCTION TO JAVASCRIPT

   JavaScript is a very high level, object based scripting language that was specifically designed to provide interactivity and animation to Web pages.  It currently is used in two contexts, for client-side scripts embedded in HTML documents (the primary use) and for server-side scripts. It has the same language syntax as Java (and C and C++); however, being a VHLL (1) it is much more limited than these HLL.  In particular, it does not have the object-oriented facility of access control of inheritance (characteristic of Java and C++); for this reason JavaScript is usually called an "object-based" language rather than an "object-oriented" language. (Some texts say that the OOP facility of Inheritance can not be implemented in JavaScript, but this is not true; see section....{EXPAND}To see the distinction between object-based and object-oriented languages see "THE EVOLUTION OF SOFTWARE DEVELOPMENT" in COSC 390, LM I.)( However this distinction is debated by some, and the language is evolving so perhaps this distinction will change.  In any case, this technical point does not affect the use of JavaScript.) See the Study Guide {to be expanded more} for this learning module. It is CRITICALLY important to understand that JavaScript uses several terms differently than they are used in other object oriented languages; in order to avoid confusion I have addressed this inconsistency in OO termanology in the study guide and reinforced it in the learning module itself.)

The Objectives of this learning module are to:

  1. compliment the tutorial-like introduction to JavaScript in Moncur, Teach Yourself JavaScript in 24 Hours
  2. present the basics of client side scripting using JavaScript
  3. help the non-programmer learn to use JavaScript to add interactivity and dynamic features to Web pages
  4. help computer science students
    1. understand how JavaScript fits within the family of programming languages
    2. understand how JavaScript compares to C++ and Java in particular.
TPQ 1: Rewrite the preceding objectives in terms of personal accomplishments to be attained after finishing the study of this learning module.

This LM follows the sequence of chapters in Moncur, Teach Yourself JavaScript in 24 Hours, (hereafter referred to simply as Moncur) but modifies this in order to better associate related techniques. The sequence of presentations in this learning module is as follows.   You can click on any link to jump directly to that section.

  1. GETTING STARTED (Moncur, Part I)
  2. JAVASCRIPT BASICS (Moncur, Part II)
  3. ADVANCED JAVASCRIPT FEATURES (Moncur, Part III)
  4. JAVASCRIPT OBJECTS (Moncur, Part IV)
  5. SCRIPTING ADVANCED WEB FEATURES (Moncur, Part V)
  6. JAVASCRIPT APPLICATIONS (Moncur, Part VI)
TheAppendices of this LM form a concise summary of the most useful features of JavaScript, focusing on the Browser-independent constructs that we will emphasize in this course.  They present JavaScript as a programming language (unlike this LM which introduces JavaScript in a user-friendly introduction paralleling Moncur.) so it will not be very intuitive to learners who have no programming  experience.  However, it is recommended that you  look over this appendix before proceeding with the sections of  the following LM; this is especially true for computer science students who have experience with C++.

I recommend that, while reading the chapters of  Moncur, you open an HTML editor in which you can create scripts (Netscape 6 Composer, Dreamweaver, or Microsoft FrontPage) so you can code and test Moncur's examples as you encounter them.

GETTING STARTED (Moncur, Part I)

1 Understanding Client Side JavaScript (Supplements Moncur Hour 1):
  1. JavaScript is a very high level language (VHLL) specifically designed to write event driven scripts that compliment HTML.  Review the overview of JavaScript in LM VI.  In general JavaScript has three manifestations (explained in more detail in section 1.1.A of the appendix.):
    1. Core JavaScript, the base JavaScript language, manifested in ECMAScript specified by the ECMA, the European association for standards.  Unfortunately, despite these efforts to standardize Javascript, this has only partially occured in the specifications of ECMA.  The latest stanard JavaScript 1.5 follows the ECMA-262 revision 3; it is supported with Netscape 6 and later.  Microsoft has charateristically tried to usurp JavaScript by creating a version called "JScript" which is partially compatible with the standard version; however, Internet Explorer 5.5 and later supposedly supports "most of the features of JavaScript 1.5".
      1. Ref: Netscape's Core JavaScipt Guide.
      2. Ref: Netscape's Core JavaScipt Reference.
    2. Client-Side JavaScript (CSJS), an extension of Core JavaScript that is used to write code that is embedded within HTML documents that are to be viewed by browser (the "client"). CSJS is, by far, the most commonly use of JavaSript.Virtually all of Moncur and this LM focus on client-side scripting.
    3. Server-Side JavaScript (SSJS), an extension of Core JavaScript that enables access to file systems and databases located on servers in a distributed computer system.  In server side scripting, like CGI scripting, the processing occurs in                                  (2) programs, compiled from JavaScript, that reside on the server.  JavaScript can be used this way to reduce the dependence on the user's system. (However, this is not nearly as popular as CSJS.)
    In COSC 330 we will be primarily concerned with Core JavaScript and CSJS.For more information on the distinction of these three versions of JavaScript see: http://developer.netscape.com/viewsource/husted_js/husted_js.html
SAQ 1 : What is the (a) similarity and (b)  difference between Core JavaScript, CSJS, SSJS?
  1. The uses of JavaScript are restricted to Web pages because the language was esplicitly designed for this purpose. Moncur, Hour 3 gives a nice overview of the primary uses of Javascript including, in order of importance (according to Tony,):
    1. improving the human interface of a Web site,
      1. incorporating user interactivity, e.g. automating and/or validating forms, interactive banners
      2. providing output messages on a Web page, in alert boxes, in the browser status line, on the pointer (as it passes over a Web page element), etc.
    2. validating input from HTML forms (which can also be completely processed by JavaScript).
    3. creating complex applications.
    4. animating graphics like responsive (rollover) buttons or a cursor that leaves a trail of bubbles,
    5. provide interactive Web page elements, like add banners
    6. detecting installed plug-ins and notifying the user if a particular plug-in is required, and
    7. detecting the type of browser and displaying content customized for that particular browser.
  2. Where CSJS is used:  JavaScript, being designed to complement                    (3), is inherently associated with HTML so it appears in three distinct places:
    1. within an HTML document, where it is manifested three ways:
      1. Scripts normally appears within the body of an HTML document.  Such JavaScript code is delimited with the <script>...</script> tags.  An example of the syntax of an embedded script is
        1.  
          <script language="JavaScript 1.5">
          <!--
          document.write("Hello Web Surfer!");
          //-->
          </script>
           
        2. This "scripting" distinguishes CSJS from other programming languages, which are typically used to write stand-alone programs, i.e. there are no CSJS programs, only scripts within HTML documents. These are processed when the page is loaded and the output is typically displayed as part of the document itself.
        3. Note that, in the preceding code, the only JavaScript is "document.write("Hello Web Surfer!");"; the rest is                (4) that tells the browser that the tags enclose JavaScript, which must be passed to the browser's JavaScript interpreter to be executed.  If the browser does not have a JavaScript interpreter, the browser does not support JavaScript.
        4. Scripts should be coded within HTML comment fields (delimited by the tags <!-- and //-->) so that old browsers, that do not support JavaScript, will ignore the JavaScript.  This is, in fact optional, but is a good habit, even if you do not expect the users of your Web site to have old browsers.
        5. Any number of scripts may be embedded within an HTML document, using multiple script tags.
      2. Functions are written by the HTML author and are typically defined within the head of an HTML document; they are thus independent of the scripts within the HTML program.  Note that functions are not executed when the HTML document is first displayed in the Browser; instead, they are invoded (called) from the scripts within the body.  Being independently placed in the head, they can be called any number of times from any script in the HTML document body or by other functions.   (See Moncur, Hour 4. and use Find in Frame on Appendix A to see the many references to "function".)
      3. event handlers are JavaScript statements that  respond to events that may occur while an HTML document is being displayed.  Examples include a mouse click (the handler is onClick), the mouse being moved, the page being loaded, etc. (See the list of events and handlers in Appendix A, section 5.E.) The event handler defines the JavaScript response to the event; they are generally coded as functions.  Event handlers are typically invoked from within HTML tagsFor example, if you want a hyperlink to change colors when the cursor passes over it, you could define a JavaScript function called changeColor(), and call (invoke) it from within the hyperlink tag, using the onMouseOver event handler, e.g.
        <a href="" onMouseOver="changeColor();">
SAQ : What is the (a) similarity and (b) difference between scripts,  functions, and event handlers in JavaScript.
    1. in separate files. that have a .js extension.  This allows the scripts and functions, coded within these files,  to be accessed by any HTML document (unlike JavaScript embedded within a single HTML document) i.e. JavaScript in .js files can be called from any HTML document, but JavaScript within an HTML document can only be called from within that document.  All of the JavaScript constructs mentioned in the previous section,            ,                 , and                         (5) can be used in these files.
  1. JavaScript implements all the "constructs" of structured programming languages, the predecessor of object-based and object oriented programming languages.  ("Constructs" is simply a term to describe the programming elements from which programs are "constructed".)
    1. Large programs are broken down into smaller modules (the objects and functions of JavaScript).
    2. JavaScript has standard control structures (sequence, selection, and repetition) of structured programing languages and uses ANSI Standard C syntax, the same syntax for these as in C, C++, Java and others.
    3. COSC 330 students, who are not computer science majors need not worry about the theoretical details of such languages.  They can be comfortable in the fact that all the JavaScript code they develop will be structured, and object based (but NOT object oriented!).
  2. The termanology of JavaScript overlaps that of other languages (especially Java and C++) but, unfortunately, there are confusing inconsistencies between these languages.  See the Appendix, Section 1.B.a and the Study Guide, item 3 for details.  (Unfortuantely this is not mentioned in Moncur.)
  3. Alternatives to JavaScript include the scripting languages mentioned in LM I.  Moncur only mentions the most popular:
    1.               (6) , the HLL designed for distributed object oriented processing.  It is a more general language; Web applets are only one of its applications.
    2.                    (7) and            (8) are specifications rather than languages.  These were discussed in LM I, section 4.1.C and section 4.2.B.e.
  4. Be sure to do the Exercises at the end of Moncur Hour 1.
SAQ : What is the difference between  (a) JavaScript and Java (b) JavaScipt and DHTML?
2. Creating a Simple Script(Supplements Moncur Hour 2.):
  1. To create JavaScript, one needs an editor, e.g.
    1. a simple text editor like Notepad or WordPad in Windows or
    2. an HTML editor like Netxcape 6 Composer (and later versions), Microsoft FrontPage, Macromedia Dreamweaver, etc., which make script development more efficient and user friendly.
  2. Any script, e.g. JavaScript, VBscritp, etc., is delimited by the HTML tags, <script> and </scipt>.
    1. To designate JavaScript, so that the browser knows to start the JavaScript interpreter, the language parameter must be specified, e.g.
    <script language="JavaScript">
      1. A particular version of Javascript can be specified, e.g. languge="JavaScript1.5".  If a script does not use a new feature of a version of JavaScript later than 1.0, this is unnecessary.
      2. {expand?}
  3. Semicolons are used to end JavaScript statements, like most other programming languages. Although this is not "required" (the enter key is recognized by the JavaScript interpreter as the end of a statement.), it is good practice to include semicolons, so  semicologns ARE required in scripts written in this course.
  4. Variables are identifiers used to store values that can be accessed by including the variable name in a JavaScript statement.  The use of variables in JavaScript is virtually identical to their use in other programming languages.
    1. Moncur oversimplifies the introduction of variable when he uses, now = new Date() as an example.  This defines the variable now to be an "instance" of an object of type Date; this is an advanced feature of variables (involving the JavaScript's Object Model) that is not covered until Hour 9.  It is worth noting how the "dot notation" is used, in the OM, to designate specific methods belonging to a specific object, e.g. now.toString() is a built-in JavaScript method, belonging to the Date(8) object that can used by the now object because it is of type Date (9).  This actually leads to one of JavaScript's downsides, it's misuse of the word "object"; this is discussed, where it is more appropriate, in
    2. Variables are covered in more detail in Moncur's Hour 5 and section 5.C.  "Variables" is a very commonly used term; to find these, in this learning module, use the Find in Frame... facility.
  5. Output, from javaScript, to a Web page is provided by the built-in method, document.write(argument), of the document (10) object; the argument of this method (a text literal or variable containing text) is displayed.
  6. The JavaScript Console, in Netscape 6 and later, is a handy tool to practice writing JavaScript.  It accesses the JavaScript interpreter directly, allowing the user to experiment with JavaScript expressions, methods, objects, etc.  (This is a convenient feature of interpreter based languages; in compiler based languages, one has to write a complete program and debug it before seeing the results of executing an expression or functions.) To try an expression, one only has to type it in the convenient code input field on the console  It is most convenient to display results using JavaScript's alert() function, where you place the value to be output as an argument; this will display the result in a pop-up alert box.
  7. To test a script, simply load the HTML page where the script is embedded (11).
  8. Errors in a script can have two distinct results:
    1. an error message will be displayed, or
    2. nothing will happen.  (This "user friendly feature" prevents scripts with errors from "bombing" a Web page, but also is of no help in finding the offending error, or, what is worse, will not remind the developer that an error has occured!)
    alert_red.gifBefore Navigator 4.5, error messages display in a pop-up window; starting with version 4.5, errors are displayed in the JavaScript Console.  It is advisable to set the browser preferences to automatically display the JavaScript Console when errors occur;  this is accompllished in vaious ways, depending on the browser vesion.
  9. To hide scripts from older browsers that do not handle javaScript (now rare), simply enclose the script with JavaScipt comment tags, just inside the <script> and </script>. tags.  The JavaScript supporting browsers are smart enought to recognize that the JavaScript is not a comment and should be exceuted.
  10. Workshop: This is a very simple exercise on hiding scripts, as indicated in the preceding item.
  11. The second Q&A question in Moncur focuses on an troublsome mistake that can be very frustrating.
3. Exploring JavaScirpts's Capabilities(Supplements Moncur Hour 3.):
  1. The status line (at the bottom of the browser (12))of a browser can display three things:
    1. the URLs of hyperlinks when the cursor passes over them and
    2. the function of  browser toolbars components (menus and buttons) .
    3. the output of JavaScript scripts.  (See the Workshop of this hour and Hour 6.)
  2. Hour 3 is actually only a preview ofd JavaScript uses in subsequent Hours.  These include
    1. drop-down lists, used to get data with forms; see Hour 14.
    2. pop-up messages (alerts, confirmations, and prompts), covered in Hour 10.
    3. separate browser windows (with JavaScript controlled content), covered in Hour 13.
    4. DHTML features like layers (independent, movable areas within a Web page), covered in Hour 18.
    5. simple dynamic images, e.g. rollovers and mouseovers, that change without reloading a page, covered in Hour 15.  (More complex images require Shockwave, Quicktime, etc.)
    6. client-side processing of data entered in forms, one of the the simplest but most useful of JavaScript's capabilities, covered in Hour 14.
    7. detecting browser versions so that incompatibilities of different browsers can be accommodated in HTML, scripts, plug-ins, etc., covered in Hour 16.
    8. detecting, working with, or installing plug-ins for multimedia playback on the client, covered in Hour 20.
    9. creating complex scripts, like embedded game, covered in Hour 23.
  3. This Hour's workshop illustrates the useful technique of copying and customizing scripts, in this case a scrolling message displayed in the browser status line.  With the plethora of scripts readily available on the Web this can be a powerful tool for incorporating scripts in a Web site.
4. How JavaScript Programs Work (Supplements Moncur Hour 4.):
  1. JavaScript is typically incorporated into HTML documents by invocations (calls) to functions and methods that define the behavior of scripted Web page elements.  The order of execution of scripts is:
    1. Scripts (JavaScript code within <script> tags) in the the <head> section of the HTML document are the first to be executed.  Since these cannot output to the Web page, these scripts are usually used to define functions and  methods.
    2. Scripts within the <body> section, in sequential order, while the page loads and displays.
    3. Event handlers are executed when their associated event, e.g. mouseOver, occurs.
  2. Functions are, along with methods, one of the primary means of defining the behavior of JavaScript controlled Web page elements. These were covered in in Appendix A.
    1. Moncur uses the word "parameters" for what are more properly called arguments (13).
  3. JavaScript objects, defined in various "object models", e.g. the core object model (COM) and document object model (DOM), are built-in generic Web page elements.
    1. Objects encapsulate:
      1. properties ( "attributes (15)", is a more proper, object oriented term) which specify the object's state and
      2. methods (functions specifically associated a particular object) which specify the object's behavior.
    2. JavaScript supports three types of objects:
      1. built-in objects which are part of the language; these are covered in Hour 9.
      2. browser objects which specify browser elements like windows, frames, buttons, etc., covered in Hour 10.
      3. custom objects, covered in Hour 11.
  4. The JavaScript Event Model, covered in Appendix A, section 7, which  facilitates event-driven programming is a relatively simple protocol for handling user interactions with Web pages.
    1. Event handlers, associated with particular Web page elements, are specified by an attribute in the tag that defines the element.
    2. Being simple, the JavaScript event model is a good way to introduce students to event-driven programming techniques.
  5. As with all programming languages, programs are developed using two types of control structures that modify the normal sequential execution of statements:
    1. selection constructs (called conditional statements by Moncur; see the SAQ below) exemplified by by if statements; see Appendix A, section 4.
    2. repetition constructs which are of two types, iteration (called  loops (16) by Moncur), covered in Appendix A, section 4 and recursion, covered in Appendix A, section 4.
  6. This Hour's workshop is a trivial exercise in using comments in JavaScript scripts.
SAQ: Moncur's term "conditional" statements for if statements is imprecise because it applies to iterative (looping) statements as well.  Explain this.

LEARNING JAVASCRIPT BASICS (Moncur, Part II):

5. Using Variables and Functions (Supplements Moncur Hour 5):
  1. This hour introduces modularization and abstraction in JavaScript.  Modularization means to group related statements into a self-contained module and abstraction means to give that model a descriptive name, i.e. the module can be referenced (invoked or called) via that name.
    1. Modularization and abstraction, in JavaScript, are implemented with functions, a structured programing construct.  (Note that functions that are associated with JavaScript objects are called methods ().  See section 4.C.ii, above.)
    2. Abstraction is also implemented via the variable construct.  Values are represented by a variable in a manner identical to mathematics.
  2. Functions are a named collection of self-contained program statements that are executed together when the JavaScript interpreter encounters the function name in a JavaScript statement. (See Appendix A, Section 2.E.b and Section 3.)
    1. In JavaScript, like C and C++, functions have two forms, those that return a value (true functions) and those  that perform a specific task like printing (null functions).   (Strickly speaking, functions, in programming languages, return a value via their name, i.e. the results of their execution replace their name in the instruction they are called.)
      1. True functions, in JavaScript, are coded to return values via the return statement at the end of the function definition; see Moncur, Listing 5.5. and the function factorial in Appendix A, Section 3.B.d.)
      2. Null functions do not return values; instead they they perform a task.  See the null function GreetListing 5.4 of Moncur and the null function warning in Appendix A, Section 3.B.d.ii.
    2. Data values are passed to functions via arguments (sometimes inappropriately called "parameters") placed within parentheses after the function name.  Multiple arguments are separated by commas.
SAQ:  (a) In Appendix A, Section 3.B.d, (a) what is the argument of the function factorial and (b) what values are returned by the two versions of factorial.
    1. Functions are usually placed within the header of an HTML document.  Since statements within the header are executed first, this insures that functions defined within the header are defined before they are called.
    2. Functions are invoked (called) by using the function name in a JavaScript statement.  These can be invoked from within a script in the body of the HTML document (e.g. the function Greet Listing 5.4 of Moncur) or from within another function (e.g. the built-in function alert within Greet of Listing 5.4) or method.
  1. Variables, introduced in section 2.D, above, are identifiers used to store data values that can be accessed by including the variable name in a JavaScript statement; the use in JavaScript is like that in other lanugages.
    1. Variables in JavaScript are global unless they are declared within a function in which case they are local variables with a scope limited to the function were they are defined.
    2. Unlike strongly typed languages (like Java, C++, etc.), JavaScript variables do not have to be declared, i.e. their type does not need to be specified.  This is a user-friendly feature, but is dangerous because typing of variables, in strongly typed languages, is means of detecting and removing programming errors. See the warning in Appendix A.
    3. Specifics of JavaScript variables and their use are presented in Appendix A, section 2.B.
  2. JavaScript is a weakly typed language. which means that variable types do not have to be declared because the JavaScript interpreter will automatically manage this.  Specifics of JavaScript types and their use are presented in Appendix A, section 2.C.
  3. This Hour's workshop illustrates the Input of strings, using the assignment of the prompt() function to variables.  This may seem a little mysterious to beginners so consider this carefully.
SAQ:  What three things does line 7 of Listing 5.7 in Moncur do?
6. Using Strings and Arrays(Supplements Moncur Hour 6.):
  1. This hour introduces the built-in data structures, string and array, of JavaScript; they are, in fact, JavaScript "objects".
    1. Note that, conceptually strings and arrays are both "indexed" data structures, i.e. they are collections of data where individual elements or sequences of elements can be designated or accessed by their index.
      1. String elements are alphanumeric characters (letters, numbers, and symbols on a keyboard).
      2. Array elements can be any homogeneous data type, including other arrays.
      These definitions are independent of JavaScript or any computer language.  These are concepts that can be  implemented in computer languages, often in subtly different ways.  In JavaScript the data types of an array are JavaScript objects.
    2. Strictly speaking, in JavaScript, both strings and arrays are objects (equivalent to OOPL classes()), but  JavaScript's user-friendly character makes this really of little practical importance - but only for people who just want to use JavaScript as a "tool" to enhance their Web pages. Anyone who uses or plans to learn other OOPL should be VERY careful in relating JavaScript to those languages, e.g., in this case, JavaScript misuses the word "object"; see the Study Guide, section 3.2 and Appendix A, section 5 .
      1. Moncur does not consistently use object based syntax, I will use object based syntax in this LM and try to point out the differences.
  2. String objects implement the string data type in JavaScript.
    1. Strings, in any programming language, are a data type for manipulating text data; see the JavaScript's string data type in Appendix A.
    2. Strings are an indexed sequence of alphanumeric characters; the first element has an index of zero.  (Irritatingly confusing characteristic taken from C/C++!!)
    3. String operations and properties (See App. A.5 . to view these from the context of the overall JavaScript language.):
      1. Creating  strings can (unfortunately) be done two ways.  Moncur's example is:
      2. text = "This is a test.";
        text = new String("This is a test.");
        The first statement is an oversimplified version of the second, a proper object based statement.  Actually the first statement is an assignment statement (See the next item.), but JavaScript automatically creates an object if one does not already exist.  Anyway, although the last instruction is the most proper, the strings that are created are identical.
      3. Assignment is accomplished by setting a string equal to a variable, e.g.
      4. textVariable = "This is a new string.";
        overwrites() the previous value of textVariable with "This is a new string".  As mentioned in the previous section, if an object text does not already exist, JavaScript creates one when this assignment is executed.
      5. To change the case of a string, invoke the String object methods:
        1. toUpperCase() converts all the characters of the object associated with this method to uppercase, and
        2. toLowerCase() converts all the characters of the object associated with this method to lowercase
        e.g. textVariable.toUpperCase()would return "THIS IS A NEW STRING." ().
      6. To determine the length of a string, simply access its length property, e.g. textVariable.length will give the length of the string of the object textVariable.  ( Note, Moncur's section heading "Calculating the String's Length" is misleading.  "Calculating" is an operation and would be accomplished by calling a method or function.  Instead length is a "property" of the string object; therefore, length has a value, although this may not be obvious.)
      7. To access and manipulate substrings:
        1. To access a substrings of a string, invoke the method substring(beginning, end) of the object string, where beginning is the index of the beginning of the substring to be returned and end is the index of the character that is NOT included.  For example, if a NumString is "123456", then numString.substring( 3, 5) will return "45"(). which is NOT intuitive; you just have to get used to this stupid convention!  (Remember, JavaScript indices start with zero; this applies to strings as well as arrays!)  To get used to the string indices, do the exercises on p.78 of Moncur.
        2. To access a specific stringelement, invoke the method charAt(index)().
        3. To locate the beginning of a particular substring of a string, invoke the method indexOf(stringToFind, startLocation)(). where the second, optional, argument indicates the index where the search is to begin.
        4. To divide a string into substrings, invoke the method split(divider)().  To store these separated parts of a string, an array of strings is automatically created by JavaScript; see section C.d.ii, below.
      8. String methods not mentioned in Hour 6 (See Moncur, Appendix D.):
        1. lastIndexOf
        2. methods associated with HTML: link and anchor
        3. methods associated with string appearance in HTML documents: big, blink, bold, fixed, fontcolor, fontsize, italics, small, strike, sub, and sub.
SAQ: Which of the preceding string manipulations are (a) accessing object properties and (b) returning values via object methods?
  1. Array objects implement the array data structure in JavaScript.
    1. Arrays, in any programming language, are a data type for manipulating homogeneous data, represented, in JavaScript, by primitive data types (e.g. integers, real numbers, characters, etc.) or objects (e.g. string, other arrays, etc.).
    2. Unlike strings, arrays must be instantiated, i.e. to create an array of 10 elements called "arrayOfThings" one would write the JavaScript instruction
    3. var arrayOfThings = new array(10);
      where the index of the first element, as in strings, is 0 ().  (Compare this to the declaration of a string, above.)  Note that the type of the elements in this array is not specified.  Also note that, although arrayOfThings is instantiated (It exists.)  it is NOT initialized, i.e. the values of its elements have not been specified.  Initialization involves assigning a value to each array element.
    4. Individual array elements may be accessed by specifying their index enclosed in bracket following the array name, e.g.
    5. fifthThing = arrayOfThings[4]; ()
    6. Array elements can be any primitive data type or object in JavaScript.  The most common include:
      1. Numeric arrays are created by declaring each element to be a number type, e.g. integer or real.
      2. String Arrays
    7. Array operations
      1. Operations with string equivalents: instantiation and assignment.
      2. Splitting of an array is accomplished by invoking the  method of the array object; see the preceding section on strings.  JavaScript automatically creates enough arrays to accommodate the number of
      3. Sorting of arrays is accomplished by invoking the sort() method of the array object.
      4. Array operations not mentioned in Hour 6:
        1. the method join(array elements separated by commas) concatenates the specified elements into a single string.  (See Moncur, Appendix D.)
        2. the method reverse(arrayName) reverses the order of the elements of the array argument.  (See Moncur, Appendix D.)
        3. Five ECMA-262 methods that are not in Moncur include: charAt(), charCodeAt(), fromCharCode(), toString(), and valueOf().  (You are not responsible for these.)
  2. Hour Six's workshop illustrates the use of strings to create the dynamic Web page effect of a scrolling message in the status line of a browser window.
    1. Note that there is a more sophisticated script for a scrolling message on page 259 of Moncur.
    2. The Workshop in this Hour uses a recursion function, ScrollMessage, which (I think) is premature, i.e. recursion, a form of repetition, has not been covered; in fact  ignores recursion all together, so I don't think it should be used in an example.  See recursive functions in Appendix A and
SAQ: If a string is an array, what is the point of creating an array of strings?
7. Selection control structures (Supplements Moncur Hour 7, Testing and Comparing Values.):
  1. This hour, along with Hour 8, is straightforward because control structures are not associated with objects and therefore, have no inconsistencies in terminology that we've had to deal with previously.  In fact for those who have experience with C, C++, or Java, already know everything in this chapter because JavaScript, like those languages, uses ANSI standard C syntax.
  2. There are only two fundamental structured control structures, selection and repetition(See Appendix A, section 4.)  This hour introduces the selection construct (See Appendix A, section 4.A.).  Repetition will covered in Moncur Hour 8, below.
  3. All control structures, selection and repetition  test boolean expressions and thus control the flow of execution of program instructions.  Such Boolean expressions can consist of:
    1. a simple constant, either true or false
    2. a single Boolean variable, which can have only two values, 1  (for "true") or 0 (for false").
    3. a complex conditional statement containing comparison operators (==, !=, <, >, >= or <=; called "conditional operators" by Moncur.  Also,see Appendix B, section 2.) and/or  Boolean operators (&&, ||, !; called "logical operators" by Moncur.  Also, see Appendix B, section 2.)  For example the conditional statement represented by the following Boolean expression
    4. (Grade >= 0) && (Grade <=100)
      would select the values of Grade between 0 and 100 ()
  4. Selection, in JavaScript (as well as C, C++, Java, and most programming languages) is implemented with three constructs.
    1. most fundamental selection construct is the if-else statement (called if-then-else in some languages); see Appendix A, section 4A.
    2.  the switch statement, which is a concise, useful "simplification" of what would be a complex nesting of if-else statements.
    3. the rarely used Conditional operator, ?, which I will ignore.
  5. Hour Seven's workshop illustrates the use of the switch statement to create mechanism for user input.  Various text strings typed by the user in response to the prompt function are categorized by the switch statement.
SAQ: Code an equivalent to Listing 7.4 that uses nested if-else statements instead of a switch  statement.  ( This should be easy for anyone who has taken COSC 200; if you havent' simply look at the answer to see an example of the difference between the if-else and switch constructs.)
8. Repeating Yourself; Using Loops (Supplements Moncur Hour 8.):
  1. This hour, along with Hour 7, is straightforward because control structures are not associated with objects and therefore, have no inconsistencies in terminology.  In fact for those who have experience with C, C++, or Java, already know everything in this chapter because JavaScript, like those languages, uses ANSI standard C syntax.
  2. This hour extends coverage of structured control structures with the iteration (looping) constructs one of the two repetition constructs; the second, recursion, is not covered in this hour.  In fact, recursion is not presented at all in Moncur as a distinct control structure, although is used in some examples.
  3. Repetition control structures are based on Boolean expressions, just as selection control structures are.  (See Section 7.C, above.)
  4. Iteration control structures repeat a "block" of instructions (delimited by "{" and "}"), governed by a well defined Boolean condition or by an index the counts the number of times a loop is executed.  These two ways of governing a loop define two fundamentally distinct categories:
    1. Indefinite loops  are governed by a "looping condition", a Boolean expression.  In JavaScript, loops execute while their looping condition is true.
      1. While loops evaluate their looping condition at the beginning of the loop; if the condition is true the body of the loop will be executed.  However, if the condition is initially false, the loop body will not execute at all.  (This is the primary destinction between a while loop and a do...while loop.)  If the condition is initially true, the loop body will be executed over and over until something happens, within the loop body, to change the looping condition to false; when the body is finished the
      2. Do...while loops execute the instructions in the loop body block once and then evaluates the looping condition (at the end of the loop), repeating if it is true or exiting if it is false.
SAQ: 9a) What is the fundamental difference between a while loop and a do...while loop?  (b) Which is the most general?
    1. Definite loops are governed by an index or counter.
      1. For loopsfacilitate counter-controlled loops by optionally (1) initializing the counter (2) specifying the exit condition, and (3) specifying how the counter changes.  Although all of these are optional, for loops typically contain all of these.  Like the while () loop the exit condition (usually an maximum value of the counter) is evaluated at the beginning of the loop, i.e. before the loop body is executed.
      2. For...in loopsare specifically designed to be used to repeat a specified operation on all the properties of an object.  This will become more clear when we cover JavaScript's object models; Moncur returns to this in Hour 16.  It is important to code an execute the for (i in navigator)... example on Moncur, page 105.
  1. Infinite loops occur when the loop body contains no way to change the looping condition to false, i.e. the loop body is executed "forever".
    1. This can be a design decision, i.e. writing whiletrue () {instruction of loop body} creates a "loop forever" if the loop needs to be run continuously until an application is closed.  In other situations a break instruction (See the next section.) can be used to execute
  2. JavaScript has two instruction that can alter the execution sequence of the loop body.
    1. The break instruction can be used to "break out of" a loop body (or any block of instructions).  This makes it possible to discontinue the execution of the loop body and go immediately to the first instruction after the end of the loop construct.  This can be done anywhere within the the loop body and/or at several different points within that body.
SAQ: Under what conditions would an infinite loop with a break statement be preferred to a pure while loop or  pure do...while loop (i.e. loops without break statements)?
    1. The continue instruction allows the developer to set a condition under which the execution of the loop body can be aborted and starte over.
  1. Two constructs, normally assoicated with repetition, are not covered in Moncur, Hour 8:
    1. recursion, mention in section 8.B, above.
    2. the with statement which is used to specify a default object to be associated with a block of statements.  Moncur discusses the with statement when he introduces objects in Hour 9.
  2. Hour Eight's workshop is a good, useful example of JavaScript.  It illustrates how a script can prompt the user for imput and then respond to that input; this is a task that is used very frequently, so it is work studying this example carefully.
SAQ: Why was an indefinite loop used for the input part of Listing 8.7 and a definite loop used for the outpart part?

MOVING ON TO ADVANCED JAVASCRIPT FEATURES: (Moncur, Part III):

9. Using Built-In Objects(Supplements Moncur Hour 9):
  1. Unfortunately JavaScript uses some terms for object oriented features that differs from standard OO terminology. To avoid confusion, refer to the comments in the study guide about inconsistencies in OO terminology. This applies to all the "Hours" of Moncur's Part III, i.e. hours 9, 10, 11, and 12, below.)
    1. The "bottom line" is that, to relate the object based JavaScript, to OOPL
      1. think of JavaScript "objects" as either:
        1. "abstract" objects (equivalent to OOPL/UML "classes") or
        2. "real" objects, i.e. instances of "abstract" objects (equivalent to C++ "objects" which are instances of C++ "classes").
      2. think of JavaScript "properties" as OOPL/UML "attributes".
    2. This is essential for those who have used C++ or Java or for those who plan to learn these languages at FSU, where C++ is the language of choice in COSC 200 and COSC 201.  It is less important for those who have never programmed before and are only interested in using JavaScript as a "tool" to enliven their Web pages.
    3. See the study guide for Hour 9 for more discussion of this problem.
  2. What is an object (in JavaScript)?  This question, when posed in Moncur, refers to JavaScript, not other OOPL.
    1. JavaScript objects (classes) are software constructs that encapsulate:
      1. properties (attributes) which specify the state of the object.  An instance of the object has particular values defined for every property.
      2. methods which specify the behavior of the object.
      Properties (attributes) and methods are often collectively called object "elements".
    2. Abstract JavaScript objects are all built-in, i.e. are part of the language.  The developer can use these built-in "abstract" objects (classes) in scripts or functions by instantiating them, i.e. making them "real" objects when displayed by a browser.
      1. JavaScript, unlike OOPL, can not create new objects (classes).  This is what prevents it from being an object oriented language, i.e. the essential feature of all OOPL is the "class" construct, the ability to encapsulate state (attributes) and behavior (methods) within self-contained classes.  The creation of classes and relating them to each other, in an object oriented software "architecture", is the essence of object oriented software development.  This is beyond the scope of JavaScript.
      2. The built-in objects of JavaScript are equivalent to the class libraries of Java (called the "Core Java API"),  C++, etc.    Therefore, the use of JavaScript objects, e.g. the core JavaScript object model and the document object models (DOMs), are entirely equivalent to using the class libraries to create real objects in Java or C++ software.
    3. "Real" JavaScript objects are created by instantiating "abstract" JavaScript objects of the core object model or DOMs.  The syntax used is:
    4. real object = newabstract object;
      for example, from Moncur p 114, myname = new String("Figby");

      where myname is a real object () and String  is the abstract object () instantiated by this declaration.  This syntax and example use the simplified syntax allowed in JavaScript; a more rigorous form (that is equivalent to instantiation in Java and C++) is given in section 5.A  of Appendix A.

    5. Using the with Keyword: with is a term used to simplify coding Javascript.  It is used to specify an object that is used within a block of statements, i.e. the properties (attributes) and methods in the with block are assumed to be those of the specified object.  See Moncur's example on page 115 and Appendix A, section 4.
  3. The Math Object (See Moncur, Appendix D and Appendix A, section 5.E.):
    1. JavaScript's  Math object, like all JavaScript object, is built-in; it is part of the core JavaScript object model.
    2. The Math object is not an abstract object because it can not be instantiated, i.e. a new object, of "math type" can not be created.  The  object is used exclusively to perform simple math operations such as trigonometric, logarithmic, statistical, etc.
    3. The Math object has eight properties which are numerical constants:
      1. none are covered in Hour 9.
      2. All eight are covered in Moncur, Appendix D.
        1. five provide constants associated with logarithms (E, LN2, LN10, LOG2E, and LOG10E.
        2. one, circle constant, PI, and
        3. two square root constants (of 2 and 1/2).
      These are specified, in JavaScript code, by writing Math.propertyName().
    4.  Methods of the JavaScript Math object:
      1. The Math object has, according to Wilton, has 17 methods, all of which are in ECMA 262.
        1. six trigonometry methods (sin(x), cos(x), tan(x), asin(x), acos(x), and atan(x) ()) that return the trigonometric values of their argument, x.
        2. two logarithmic methods (exp(), and log()) that return  ex () and natural logarithm(). of the argument, x, respectively.
        3. two statistical methods (max(x,y), and min(x,y)) that return the maximum () and minimum (). of the arguments, x and y.
        4. four float to integer conversion methods (round(x), abs(x), ceil(x), and floor(x)) that
        5. two exponential methods (pow(x), and sqrt(x)) that return the power () and square root (). of the argument, x.
        6. one random number generating method, random(x),  that returns a random number between 0 and 1().
        These are specified, in JavaScript code, by writing Math.methodName().
      2. Four methods (ceil(x), floor(x), round(x) and random(x)) are covered in Hour 9.
      3. All 17 are covered in Moncur, Appendix D.
  4. The Date Object (See Moncur, Appendix D and Appendix A, section 5.E.):
    1. JavaScript's Date object, also part of the core JavaScript object model, provides developers with built in tools, assoicated with the host computer's clock, that can manipulate things associated with times and dates.
    2. The Date object has only two properties, it's constructor and prototype which returns the prototype of the object, used to extend the object's interface.
    3. The methods of the Date object may be used to set, get, and convert dates and times.  The Date object has, according to Wilton, has 44 methods (42 of which are in ECMA 262), but Moncur covers only 19 of them.
      1. Nineteen are covered in Hour 9.
        1. seven "set" methods (setTime(), setDate(), setSeconds(), setMinutes(), setHours(), setMonth(), and setFullYear())that specify a time or date
        2. eight "get" methods (getTime(), getDate(), getSeconds(), getMinutes(), getHours(), getMonth(), getFullYear()  and getTimezoneOffset() ()) that retrieve the current time, date, and time zone difference.
        3. four "convert" methods (parse(),  UTC(), toGMTString(), and toLocaleString()) that change between the various formats of time, date, and time zone (compared to the UTC (GMT) standard).
      2. The same nineteen are collectively itemized in Moncur, Appendix D.
      3. ECMA 262 Methods not covered in Moncur include:
        1. nine additional "set" methods (setMilliseconds(), setYear(), setUTCDate(), setUTCMilliseconds(), setUTCSeconds(), setUTCMinutes(), setUTCHours(), setUTCMonth(), and setUTCFullYear())
        2. eleven additional "get" methods (getDay(), getUTCDay(), and the "get" equivalent of the preceding "set" methods.)
        3. three additional "convert" methods (toSource(), toString(), and ValueOf()).
  5. Hour Nine's workshop is a useful exercise to test JavaScript's random number generator, but it doesn't really require the use of the other methods.
10. Working with the Document Object Model(Supplements Moncur Hour 10.):
  1. Moncur Hour 10 introduces a very limited subset of JavaScript's implementation of the W3C standard "document object model" (DOM) which represents every HTML element as an object, thus allowing programming languages to access the elements and manipulate them.  In this case, of course, we will use the DOM as the means for JavaScript to access Web page elements.  This technique allows Web developers to treate any Web page element (window, frame, link, graphic, etc.) as an object and to manipulate such objects with JavaScript.
  2. Understanding the Document Object Model (DOM) introduces the DOM, a hierarchically related collection of abstract objects, that  are object oriented "components" that are special cases of the class libraries of OOPL.  Unfortunately because there are many versions of the DOM and inconsistencies in terminology this is one of the most confusing subjects in JavaScript.
    1. To distinguish between various types of DOMs I have defined a simple terminology in Appendix A; I will focus on the browser independent version of the DOM, that I call DOM/BI.
    2. Diagrams of the DOM are given in many texts, but they are seldom accurately described, i.e. the relationships between DOM objects, represented by the diagram's lines between the objects, are not discussed much less defined.  I think this is inexcusable (After all Confucius said "...a picture is worth a thousand words...") because the lines do not all represent the same kind of relationship between objects.
      1. Compare my PLATFORM INDEPENDENT W3C DOCUMENT OBJECT MODEL (W3C DOM) to Figure 10.1 in Moncur (which is typical of DOM diagrams in JavaScript texts).
        1. The major differences is that I label the relationships "Has-A" (the OOPL "aggregation") and "Is-A" (the OOPL "inheritatnce" or "generalization").  I believe it is essential to distinguish these.  From a practical point of view, you can think that, with the exception of the frames object, the lines between most objects represent aggregation which can be viewed as "containership" of the lower level object within the parent.  For example a window object contains (or has-a) document object.  (Note that frames has an is-a relationship with the window object, but the window object can also have a has-a relationship with frames objects.)
        2. Moncur uses the "parent and child" description of object relationships in a DOM (used in many JavaScript texts).   If you think about it, this is obscure, if not meaningless!  He doesn't descibe this term anywhere (that I can remember), but, obviously, parent objects do NOT "give birth to" child objects.  Instead higher level objects "can" contain lower level objects.  (In OOPL texts the term "superclass" and "subclass" are used so perhaps one could use "superobject" and "subobject", but I have never encountered these terms.)
        3. A second difference is that my diagram contains all the W3C standard objects of the first three levels, but Moncur's omits the objects Frames and Navigator (covered elsewhere).  That is an acceptable approach in a user-friendly presentation like Moncur, but I think the omissions should, at least, be mentined.
    3. Like all abstract objects, DOM objects are OO constructs that encapsulate the object's "elements()", i.e. properties (attributes)() that describe the object state and methods() that describe the object behavior represented by operations on the state of the object.
    4. The History of the DOM has been an evolution of rival implementations.  Netscape invented JavaScript; Microsoft stole the idea and modified it to suit Windows; and both Netscape and Microsoft developed competing DOMs.
      1. Fortunately all DOMs support, in a consistent way, a basic DOM that I call "Browser Independent DOM" or "DOM/BIC".  This is all that is covered in this Hour. (Specifically we present the DOM levels 0, 1, and 2.) The platform specific DOMs are covered, in a minimal way, later.
  3. Using window Objects introduces the DOM/BI's window object. the highest level object of all browser oriented DOMs, i.e. the one that can contain all lower level objects.  Note that since a frames[] object is-a window object, everthing that applies to windows applies to frames.
  4. Working with Web Documents introduces the DOM/BI's document object., the most used object in the DOM.  The  object refers to the HTML page() displayed in the current browser window().
    1. Getting Information About the Document covers two Internet address properties (URL and referrer) and two document information properties (title and lastModified).
    2. Writing Text in a Document introduces the very useful output methods write and writeln.
SAQ: What output methods are available that are not associated with document, i.e. do not output to a specified location in the HTML document?
    1. Clearing an Rewriting Documents explains how the open and close methods can be used to allow output from write and writeln to be changed without actually closing the browser window.  (Note that window.open and window.close actually open and close a browser window, BUT document.open and document.close do NOT open and close a document.  Instead the document is cleared and rewritten "on the fly" by write and writeln methods.
      1. The rewritten document is not displayed until a document.close is executed.
      2. The document.open instruction can specify a MIME document which makes it possible to open any MIME file, e.g. an image or files of plug-in applications.
    2. Using Links and Anchorsintroduces the array basics of the HTML link mechanism with the abstract links[] and anchors[] objects.
      1. The links[] and anchors[] objects contain all hyperlinks and targets in the current HTML document.
      2. links are abstract location objects so they have all their members.
      3. the length property of all arrays give the number of elements in that array.
  1. Accessing Browser History introduces the DOM/BI's history object.
    1. Moncur is referring to the NN/4 DOM when he list the current, next, and previous properties; current is the only property that is the same in NN/4 and IE/5.
  2. Working with the location Object introduces the DOM/BI's location object
  3. Readin Information about the Browser introduces the DOM/NN4's navigator object that represents the browser version being used.  This is not part of the ECMA specification, and, therefore, is not included in Appendix A.  It is essential for writing browser independent JavaScript, i.e. after detecting the browser version, scripts can select different blocks of code for different browsers.
  4. Hour Ten's workshop is an exercise on using the DOM/BI's history object to create Back and Forward buttons in on a Web page.
11. Creating Custom Objects (Supplements Moncur Hour 11.): Currently being created!
  1. In Hour 11, Moncur  covers JavaScript's object creation facility, a restricted analog of the OOP class definition feature which is limited to encapsulation.  This means that
    1. properties (attributes) and methods CAN be encapsulated within abstract objects (classes),
    2. properties CAN be declared to have a type that is another abstract object; this implements the "aggregation" (i.e. has-a()) relationship, and
    3. methods CAN use abstract objects as:
      1. arguments of of methods
      2. the return type of methods
      These implement the "dependency" (i.e. uses-a()) relationship between abstract objects, i.e. the abstract object that has such a method "depends on" the abstract objects used as arguments or as the return value of that method.
    However, there is an important OOPL facility, "access control", associated with encapsulation, that are not available in JavaScript:
    1. In JavaScript, a user-defined abstract object CANNOT inherit the members of another object, i.e. JavaScript can not implement the inheritance or generalization (i.e. is-a()) relationship.
    2. Access to an abstract object's members can not be controlled by the developer (a defining characteristic of OOPL).  For example, in an OOPL, a member that is defined to be "private" can not be used outside the class, but, in JavaScript, this can not be done; any object member can be used in scripts, functions, or other abstract objects.
    This means that JavaScript is an object based() language but NOT an object oriented() language.  Note that many texts say that JavaScript can not implement Inheritance, THE essential feature of OOP.  (Moncur doesn't even mention inheritance.)   This is NOT true; in fact
    1. Inheritance is implemented in the built-in abstract objects of the DOM, presented in the preceding Hour, where, for example, the frames[] object is-a window() object, the images[] object is-a array[ ]() object, etc.
    2. User-defined inheritance can be implemente with the prototype property or the core object object.  This is covered in Appendix A, section {add this}.  To see how this works, view this simplified example.
SAQ (for COSC 200 veterans): What are the (a) similarities and (b) differences between abstract object creation in JavaScript and class creation in C++?
  1. Using (abstract) Objects to Simplify Scripting
    1. Defining an (abstract) Object is accomplished by defining a constructor function with the name of the object.  (See Developer Defined Objects in Appendix A.)  It should be noted that constructors are a fundamental construct in all OOPL.  However, constructor facilities in most OOPL are much more sophisticated than the rudimentary JavaScript constructor function, e.g.  there are default constructors (which means that a constructor need not be explicitly defined) and user-defined constructors are much simpler than in JavaScript (where they must contain the definition of every member).
      1. Note that a "real" object can be created by instantiating the built-in object object.  I call this the creation of a "real" object because creation and instantiating are combined.  See Appendix A, section 5.G.a.
      2. The constructor, in JavaScript, must contain all the properties and methods of the abstract object.  In OOPL, the constructor is a method of the class.  In fact the JavaScript constructor is actually equivalent to the class definition of OOPL, i.e. the construct where all the attributes and methods are defined. This is another inconsistency to add to the confusing differences of OOPL, but don't worry to much about it.  Just think of the JavaScript constructor as the abstract object definition, equivalent to the class definition in OOPL.
    2. Defining an (abstract) Method, in JavaScript, is more clumbsy than in OOPL.  Encapsulation of a method within a JavaScript object (real or abstract) is a two step process:
      1. define a function
      2. encapsulate the function within the object constructor by  assigning that function to a method.
      See Appendix A, section 5.G.b.i for an example.
    3. Creating an Object Instance explains how a "real" object is created from an "abstract" object by instantiating that abstract object.  This is accomplished by the instruction
    realObjectName = new abstractObjectName;
  2. Customizing Built-In (abstract) Objects is a rather innocent looking introduction to "adding a method to an abstract object".  (See the title to Listing 11.2 in Moncur.), but it opens up the complex subject of JavaScript's object object and the not-well-know facility of inheritance in JavaScript (provided via the prototype property of object; see Listing 11.2 in Moncur.).  (I honestly don't know if Moncur even knows this exists, because he makes no mention of inheritance.  I'll be charitable and assume that he decided to avoid the complex issue.)
    1. What Moncur does in instruction 13, of Listing 11.2 is add a user defined function to the built-in abstract object String of JavaScript.  This effectively "extends the definition of String" by creating a new method (Remember that functions that are part of an object are called methods, so when we "add" a function to an abstract object it becomes a method.) In OOPL terminology, extending a class implements inheritance.
    2.  example A SIMPLE JAVASCRIPT INHERITANCE EXAMPLE.
  3. Hour Eleven's workshop extends the "business card" example developed during the Hour by adding a method PrintCard to the user-defined abstract object Card.
12. Responding to Events (Supplements Moncur Hour 12.):
  1. Hour 12, Moncur  introduces the JavaScript Event Model which allows the Web user to interact with the JavaScript embedded within an HTML document.
  2. Understanding Event Handlers introduces the remarkably simple JavaScript Event Model as a simple way to make HTML documents interactive.  The JavaScript terms that respond to events are called "event handlers"; Moncur focuses on mouse and keyboard events.
    1. objects and Events
      1. Each event is associated with a DOM object.
      2. An event has a unique name, and an associated eventhandler. that is built into the language. To define an event handler, one concatenates "on" to the beginning of the event name. e.g. the event mouseOver has a associated event handler onMouseOver()that is built into the language.   Moncurmakes a careless mistake, on page 150, when he calls "onMouseOver" an event; don't let this confuse you.
    2. Creating an Event Handler shows how an event handler is used as an HTML tag attribute to make the tag respond to an event by either
      1. assigning a sequence of statements to the event handler or
      2. assigning a previously defined function to the event handler.
      However Moncur neglects to mention that an event handler can also be defined as an abstract object's property (attribute).
    3. Changing Event Handlers with javaScript describes the most fundamental way of associating a function with an event handler i.e. by using the event handler property of an object.  It is a way of associating a developer-defined function with a particular event handler of an object.  Moncur's example
      1.  
        Function mousealert(){
           alert("You clicked the mouse!");
        }
        document.onMouseDown = mouseAlert;
      can "change" the onMouseDown event handler of the document object, but  only if it had already been defined.  However, the same syntax can be used for an unspecified event handler, in which case, it "creates" that event handler.
    4. Using the event Object introduces the built-in DOM object that defines all events for a particular browser, i.e. each event sends an event object to the event handler, which receives the event object as a parameter.  However, Moncur uses the Netscape Navigator 4.0.  Of the properties listed my Moncur,
      1. only type (the kind of event, e.g. mouseOver) and screeX and screenY (cursor location coordinate on the monitor) are platform independent.
      2. target, which modifiers, data, pageX, PageY, layerX and layerY are
  3. Using Mouse Events (See the table of Commonly Used, Platform Independent JavaScript Events):
    1. Over and Out:mouse movement can be responded to, in JavaScript, by using three event handlers:
      1. onMouseOveris called when the cursor is moved over an object displayed by a browser.
      2. onMouseOut is called when the cursor is moved out of the borders of a displayed object.
      3. onMouseMove is called when the cursor is moved; however, because this is so common, this handler is not available by default; event capturing ( beyond the scope of this introductory presentation) must be used.
    2. Ups and Downs discusses what happens when a mouse button is clicked.  The particular mouse button may be specified by the which property of the event object; 1 for the left button or 3 for the right button.
      1. onClick (or onDblClick )is called when the a mouse button is clicked (or double clicked) while over the object containing the event handler.
      2. onMouseDown and onMouseUp represent the two halves of  onClick; these give you more control over the clicking response.
    3. Using Keyboard Events shows how the developer can control what happens when the user uses the keyboard.
      1. onKeyPress is called when a designated key is held down.
      2. onKeyDown is called when a designated key is hit.
      3. onKeyUp is called when a designated key is released.
    4. Page Events (Moncur's Using the onLoad Event) give the developer control of what happens when the page in current browser window is opened or closed or an error occurs.
      1. onLoad is called when a document or multimedia file is displayed or presented by a browser.
      2. onUnoad is called when a document or multimedia file is unloaded from the browser display.
      3. onError is called when an error occurs when a document or multimedia file is loaded by a browser
  4. Hour Twelve's workshop covers how the developer can cause a message to be displayed in the browser status line (at the bottom of the browser window) when the cursor moves over a page element.  This is an effective way to annotate links or add prompts.  {FINISH}


WORKING WITH WEB PAGES (Moncur, Part IV):

13. Using Windows and Frames(Supplements Moncur Hour 13):
  1. Hour 13, Moncur  introduces JavaScripts facilities for manipulating Web page elements that are covered throughout  Part IV; this hour focuses on Windows and Frames.  In particular, the hour covers:
    1. creating a window,
    2. opening and closing windows,
    3. delaying statement executions using the setTimeout method of the abstract object window,
    4. displaying dialog boxes, and
    5. manipulating HTML frames.
  2. Controlling Windows with Objects  takes a closer look at the DOM (actually what I call the "DOM/BI", introduced in Hour 10), in particular the abstract object window. which, when instantiated, produces a real window in the browser displayThe real window always refers to the window currently displayed by the browser; theselfkeyword is a synonym for the current window.
    1. Creating a New Window is accomplished by calling the method open() of the window() object with the statement window.open().
      1.  
        WindowObject = window.open("URL", "window name", "property list separated by commas")
      where, as usual, the italicized words must be replaced by developer-defined words, in this case arguments of the open() method, i.e. discriptive names, used in our example, that must be replaced with actual values in real code, e.g. URL might be "cnet.com" and window name might be "myWindow".   Note that you must give the new window you open a name because you need to reference the window, by name, in order to manipulate it, e.g. to close the window; see the syntax of the  method in the next section.
      1. NOTE: Moncur uses inconsistent terminology again here; he calls the property list "features" which is misleading; the correct term is "properties", which specify the state of the window object (In OOPL like Java and C++ these would be called "attributes".).
      2. The most interesting capability of the open() method is the ability to customize the appearance of the opened windows by specifying its size, whether or not it has various menus; these, as Moncur says, can be "floating windows" that look nothing like a typical browser window.
      3. See the examples in Moncur; they are good ones.
    2. Opening and closing Windows
      1. A window is closed by calling the method close() of the window object with the statement myWindow.close(),  where my window is the name of the window being closed.  (Note that this syntax is NOT consistent with the open() method syntax, i.e. you do NOT write window.close(myWindow)!)
      2. Comments about Moncur, Listing 13.1:
        1. This listing has NO script!  The JavaScript is all contained in event handlers, within HTML tags.
        2. Lines 10-14 are all one HTML tag which contains two JavaScript onclick event handlers.
        3. The empty quote (' ') argument of of open() means not URL so a blank window is opened.