Free Certification Practice Tests and Study Guides
Join Us! | Login | Help




CIW JavaScript Study Guide


Tutorial Quick Links:
Introduction to Javascript
Working With Variables and Data
Functions, Methods, and Events
Controlling Program Flow
The JavaScript Object Model
Language Objects
Interactive Forms
Cookies and JavaScript Security
Controlling Frames in JavaScript
Client-Side JavaScript
Custom JavaScript Objects

Introduction to JavaScript
  • Netscape Corporation originally developed JavaScript. Originally named LiveScript, Netscape changed the name to JavaScript in order to utilize Java's name recognition. Server Side JavaScript is known as LiveWire. It is stored and executed on the server machine.
  • There are Currently 5 versions of JS 1.0, 1.1, 1.2, 1.3, and 1.4. First supported in Navigator version 2.0, Internet Explorer version 3.0, Moasaic 2.0 and Lotus Personal Web Client 3.0.
  • JavaScript, a language of objects, is not compiled and runs on the client machine.
Differences between JavaScript and Java
JavaScript Java
JavaScript is a client-side scripting Language which means that it is interpreted and not compiled to any particular machine/os, making it platform independent, however, only to a specific "user agent" (browser). Compiled on server before execution on the client.
Object-Based. Uses built-in, extensible objects, but no classes or inheritance. Object-Oriented. Applets consist of object classes with inheritance.
Not neccessary to declare variable data types. Variable data types must be declared.
Dynamic Binding. Object references checked at run time. Static Binding. Object references must exist at compile time.
Secure. Cannot write to hard disk. Secure. Cannot write to hard disk.
Code embedded in HTML.  
Event-driven = events trigger functions. e.g., mouseclick…  
Relatively easy to learn which enables quick development.  
Case Sensitive.  
  • JS and VBScript are scripting languages that are similar in purpose, however, JavaScript is a Netscape client side scripting language which relies on objects and their attendant methods and properties for a large part of its functionality. On the other hand, VBScript is similar to and based on Visual Basic. Microsoft relies less on traditional object classes and more on dynamic built in customizing functions.
  • Microsoft’s implementation of Netscape’s JS is called Jscript.
  • ECMAScript (European Comp Mfr’s Assoc) - EMCA in 1997 approved JS as an international standard which intends to diminish difference between JS and JScript.
  • JavaScript can be embedded into HTML via a <SCRIPT> tag within the head or body. Alternatively you can place code directly into your existing HTML tags, this method is known as inline scripting. It is then parsed and executed on the client machine.
  • You can also call an external script by referencing a .js file which must be in ASCII text format.

    Code sample:
    <SCRIPT LANGUAGE="JavaScript" SRC="myfile.js"></SCRIPT>

  • How JS code is used in a web page:

    Code sample:
    <html>
    <head>
    <title>Title</title>
    <script language="JavaScript">
    <!--
    JavaScript code goes here
    // -->
    </script></head>


    Note: the // goes before the --> because the ending comment tag contains JS operators.
Working With Variables and Data



Object - A package of data, a collection of properties and methods classed under a single name. A programming function that models the characteristics of abstract or real "objects" using classes.

Property - A descriptive characteristic of an object such as color, width or height that the programmer stipulates in the creation of the object. Always followed by a dot notation after object.

Example:
myObject.myProperty=”myValue”;

Method() - Object’s action. Must have parenthesis() at the end of the method. Any method that returns a value can also be called a function.

Example:
document.write();

Value -The specific color, width or height that belongs to the property of an object.

Statement - A single line of code to be executed in a script or program. Semicolons (;) are used in JS to seperate statements unless statements are combined, although it is still considered good coding practice to include them. Semicolons are required when using multiple statements in 1 line of code.

Concatenation - The synthesis of code to simplify it and reduce duplication; combining text strings/files especially in conjunction with prompt() and alert() as shown in the example below:

Example:
Alert(“Hello, ” + prompt(“What is your name?”,””) + “.”);

Note: prompt always comes before alert

Variables - These are symbols or names that stand for a value in your program. They are named memory spaces that contain values which you can access repeatedly and may change its own value as well as the values of other variables over the course of script sequence. In the expression x+y, x and y are variables. Variables can be used to represent numbers, characters, character strings or memory addresses. All variables are declared using the keyword var.

Example:
var Mynumber;.

Variables declared without value are undefined as they have no value althought is good practice to declare variables for the clarity of your code. Another way to declare a variable is to declare and assign it a value at the same time such as Mynumber = 10;. It is important to note that variable names must either start with a letter or and underscore (_) and the names are case sensitive.

Variable Data Types - There are 5 basic data types:
  • Number - Any numeric value such as 5 or 245.
  • Strings - Strings are set of characters grouped together by quotes and are the most commonly used data type. Examples are "Hello" or "Hello555". Single quotes can also be used, however, you need to make sure that you use the same type of quote at the beginning and end of the string.
  • Boolean true or false values - Mostly used to TEST conditions in JS such as with a check box.
  • A JavaScript element such as a function or object.
  • Null - A special keyword for the null value. Mostly used to determine the STATE of var.


  • Literals: These are the actual (fixed) data values assigned to variables in the script. There are several literal types:
    • Integer - These are numbers that are based on one of the following 3 formats:
      • Decimal (base 10) - 1-9 followed by any set of these same digits.
      • Octal (base 8) - 0 followed by any set of the digits 0-7.
      • Hexadecimal (base 16) - 0x or 0X followed by any combination of 0-9, a-f or A-F.
    • Floating-point - These numbers can be specified in either decimal format or engineering E-notation. This encompasses numbers that contain a decimal point or an exponent.
    • String literal: “any text”
    Keywords are the predefined identifiers that form the foundation of JavaScript. They achieve specific results and perform unique duties such as declaring variable and defining functions. Keywords and reserved words are for explicit use by the language and cannot be used as variables, functions, objects or methods names.

    Expressions are part of a statement that is evaluated as a value and rely on various operators. You can use any combination of variables, literals, operators and other expressions with the exception of assignment expressions, which assign a value to a variable. For example, a=1 a would be taken as a variable and the value assigned to it would be 1.

    Operators provide various ways of combining values (literals and variables) into expressions. Unary operators only require a single operand while binary operators require 2. There are 4 basic operator types outlined below.
    • Assignment Operators - The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. Aggregate operators can be created by adding another operator before the = sign to create shorthand for other operations. The table below shows examples of these operations.

      Shorthand operator Meaning
      x += y x = x + y
      x -= y x = x - y
      x *= y x = x * y
      x /= y x = x / y

    • Arithmetic (aka. Computational) Operators - Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), division (/) and remainder (%). These operators work as they do in other programming languages, as well as in standard algebra. Since programmers frequently need to add or subtract 1 from a variable, JavaScript has shortcuts for doing this. myVar++ adds one to the value of myVar, while myVar-- subtracts one from myVar.

      Examples:
      Let x = 3. x++ turns x into 4, while x-- makes x equal to 2.

    • Comparison Operators - A comparison operator compares its operands and returns a logical value based on whether the comparison is true or not. The operands can be numerical or string values. They are described in the following table:

      Operator Description Example
      Equal (==) Evaluates to true if the operands are equal x == y evaluates to true if x equals y.
      Not equal (!=) Evaluates to true if the operands are not equal. x != y evaluates to true if x is not equal to y
      Greater than (>) Evaluates to true if left operand is greater than right operand x > y evaluates to true if x is greater than y
      Greater than or equal (>=) Evaluates to true if left operand is greater than or equal to right operand x >= y evaluates to true if x is greater than or equal to y
      Less than (<) Evaluates to true if left operand is less than right operand. x < y evaluates to true if x is less than y.
      Less than or equal (<=) Evaluates to true if left operand is less than or equal to right operand. x <= y evaluates to true if x is less than or equal to y.

      Examples:
      3 == 3 would return TRUE because three is equal to three. 3 != 3 would return FALSE because the statement 'three is not equal to three.' is false. 3 <= 3 would return TRUE because three is less than or equal to three.

    • Logical Operators -
    • Logical operators take Boolean values as operands and return a Boolean value of true or false. These operators are shown in the following table:

      Operator Description
      and (&&) True only if both logical expressions true otherwise it is false.
      or (||) True if either (or both) logical expression is true. False when both expressions are false.
      not (!) Returns the opposite value. False if expression is true. True if expression is false.
    The different operators are used in conjuction with each other as shown in the examples below.

    Examples:
    If x = 6 and y = 9, ((x + y + 2) == 17) && (((x + y) / 3) == 3) returns FALSE.
    The best way to evaluate this is to compute the left and right sides separately and then compare them using the operator in the middle. On the left we have ((6 + 9 + 2) == 17). Since 6+9+2 are equal to 17 this side is TRUE. On the right side we would have (((6 + 9) /3) == 3) which gives ((15/3) == 3. Since 5 is not equal to 3, this side is FALSE. Essentially what we are left with is: TRUE && FALSE. && will only return TRUE if both expressions are TRUE. In this example only 1 expression is TRUE so overall we get a FALSE. Below are a couple more examples that you can work through.

    If x = 4 and y = 7, !((x/2 + y) == 9) || ((x * (y/2)) == 2) returns FALSE.
    If x = 4 and y = 7, ((y - x + 9) == 12) || ((x * y) == 2) returns TRUE.

    Note: Parenthetic expressions takes precedence over other expressions. In the example, (4+6)*2, the expression in parentheses is calculated first and then multiplied.

    Functions, Methods, and Events

    Functions group together a chunk of code under a named subroutine, allowing you to call the function whenever its action is required. Functions are important organizational tools that allow you to perform the same operation by calling the particular function instead of listing the function's code everywhere that you want to use it. Secondly, functions are used to link user actions on a web page with JavaScript code. It is important to remember the following about functions:
    • function and method are interchangeable. Tip: function returns values while method() does not.
    • Functions manipulate object properties and perform calculations.
    • Can improve program efficiency and readability by repeating the specific task throughout the program.
    • You define a function within the <SCRIPT>...</SCRIPT> tags. It is advisable to define all functions in the <Head> so that the function will load before any user events can occur that might call the function.
    • When defining a function, it is important that you pay close attention to the syntax. Unlike HTML, JavaScript is case sensitive, and it is very important to remember to enclose a function within brackets { }, separate parameters with commas, and use a semi-colon at the end of your line of code.
    Functions are defined in the following format:

    function funcName(argument1,argument2,etc)
    { statements; }


    Code Sample:
    function appear(){
    document.d1.visibility='show'
    }


    Notice the parentheses after the function name. It is very important that you include these parentheses, even if they are empty. If you want to pass a parameter into the function, you would include that parameter inside of the parentheses, otherwise they are left empty.

    Functions are called using a Calling Statement which is a statement that transfers program execution to a subroutine, procedure or a function. When the function is complete, execution transfers back to the call statement. If you specify arguments, the arguments will become the variables within the function body. Passing Arguments can be used to pass values/ expressions of data or code on to a function. Once the values are used, they are discarded.

    Calling a Function - A function’s statement is executed/processed when it is called by another function or a user event (e.g., onclick) or a separate <script> block.

    Built in functions - Parse() functions eliminate the + being interpreted as concatenation when you want it as math operator.
  • parseInt(): converts # to its integer equivalent
  • parseFloat(): floating-point decimal equivalent


  • Code Sample
    function addItems() {
    var x = prompt("How many ashtrays?");
    var y = prompt("How many tables?");
    var z = prompt("How many chairs");
    items = parseInt(x) + parseInt(y) + parseInt(z); // i/o x + y + z
    alert("You ordered " + items + "items."); }


    This function could then be called as follows:

    Code Sample
    <form><input type="button" value="order"
    onClick="addItems();"></form>


    Example:
    To see what this code produces, click the button below:



    Note: Global variables can by accessed from anywhere in the page's code and you may declare variables by assigning a value with the var statement. All variables declared outside of a function are global and variables declared inside a function by assigning a value are global. Global variables persist until the page is unloaded. Local variables are only visible inside the function that declared them, and disappear when the function terminates. You must use the var statement to declare a local variable.

    Event-Based Model
    An event is an action or occurrence detected by a program. It can be user actions, such as clicking a mouse button or pressing a key, or system occurrences, such as running out of memory. Users generated events include loading and unloading pages, mouse clicks, key strokes while navigating through a page or submitting form. Most modern GUI applications in Windows environments are considered event-driven, as they are designed to respond to events.

    Event Handlers
    Javascript can also execute on events, when something happens to the browser. All executions made by Javascript do not have to be made in a certain sequence. Event handlers are used to tell the browser what to do when a particular event occurs. Predetermined event handlers include onClick, onMouseOver, onBlur, onmouseout, etc.

    Example:
    <a href="#" onMouseOver="alert('This is a link.')">This is a link</a>

    onMouseOver in the above code is the event handler. This code would produce the following: This is a link. You will notice that when you move your mouse over the link you get an alert.

    An HTML element can have multiple event handlers -any combination of available event handlers can be included in a single tag, with each waiting for its own specific event to take action on.

    Events corresponding to user’s interaction are different from Window Event, in fact, event handlers are available for many HTML elements, from links to the browser window itself. Handlers associated with each HTML tag may differ depending on the HTML tag being used. Window-related event handlers are processed as attributes of the <body> tag rather than the <A HREF> tag: <body onLoad="window.alert('This is an alert.');">. The table below lists some of the most common events and descriptions.

    Event Description
    Load HTML document loads into browser window
    Unload HTML document in browser window is replaced by another document when a user exits the page.
    Focus The focused window is the window being viewed. If another window is selected, the focus is shifted to that window and the original window subsequently loses the focus.
    Blur Window's focus is moved to another HTML document
    Click User clicks on a specified object.
    Change User changes the value of a form field
    Mouseover User moves the mouse over top of a specified link.

    Controlling Program Flow

    JavaScript gives you access to conditional looping (such as for and while loops), decision-making statement(such as if and switch statements) and objects (such as arrays). A loop is a series of instructions that is repeated until a certain condition is met. Each pass through the loop is called an iteration. Conditions may exist when a script will be required to run different commands depending on different outcomes. Conditional statements direct program flow in specified directions. There are statements built into JS to help deal with different conditions which are explained below:
    • If Statement - This condition is used to conditionally execute a single block of code. The if statement can be used in conjunction with the else statement described next.

    • Else statement - Used to evaluate multiple conditions where any of an array could be true. When combined with an IF statement, a second block of code will execute if the first statement is false.

      Code Sample:
      Var userAnswer = "";
      userAnswer = prompt("Guess a number.","");
      if (userAnswer==25) {
      alert("You win");
      } else {
      alert("Try again");
      }
      If(i++ == 10) : var I would be increased in value by 1 the next time it is accessed.
      If(++i == 10) : var I would increase in value by 1 before being compared to 10.


    • Switch Statement - Matches an expression with a specified case and executes the corresponding statements. The switch statement acts as multiple “If” statements (compares a value against another value). However, it allows you to specify a default set of statements to execute if the script does not find a match. (Introduced in JS 1.2 specification which requires a browsers version 4 or higher to function.)

      Example:
      switch (expression/variable1) {
      case label0 :
      // do this, one or more statements
      break;
      case label1 :
      // do this, one or more statements
      break;
      case label2 :
      // do something else, one or more statements
      break;
      default : statement;}


    • While Statement - Statement(s) LOOPS as long as a certain condition remains true. If false, it may not execute the statements even once and the script skips to the next line. Misuse by not terminating the while loop can frustrate users.

      Example:
      var num = 0;
      while (num < 10) or (A==B) {
      document.write(num) or (“A is equal to B”);
      num++;
      }


    • Do…While Statement: Exactly like the “while” statement except it does not check the conditional expression until it executes the loop the 1st time which guarantees that the code is executed at least once. (Introduced in JS 1.2 specification which requires a version 4 or higher browser to function.)

      Example:
      do {
      // do this, one or more statements
      } while (condition e.g. A==B)


    • For Statement - Used to cycle through each property of an object or an array element. The primary purpose is to repeat a group of statements for some particular range of values until a test condition is false. The loop uses mathematical formulas, usually a counter, to increment / decrement a variable until the condition is not true.

      Example:
      var x=0

      for (i=0; i<5; i++) {
      x += i;
      }
      alert("x = " + x);

    • The Break Statement - Exits/stops a loop. If a certain condition is met the user is allowed to break outside of loop and go on to the next statement. Typically used inside of IF statement as well as w/in the FOR, SWITCH & WHILE statements. In the following example, the isNaN() method determines whether a value is a numeric data type. The loop will continue until a user enters a value other than a #.

      Example:
      if (isNaN(numericalData)) break;

    • The Continue statement - Aborts only this single iteration of the loop. Used only within “for” / “while” loops to force control back to the top of the loop i.e, skip / bypass command. When execution reaches a “continue” statement, all statements b/w it & end of the loop block are skipped and execution returns to the top/beginning of the loop again. In the following example note that: Result = “x = 10”. X increments by 1 until it reaches 5, therefore, 1 + 2 + 3 + 4 = 10

      Example:
      A = 1, B = 6, C = 3.
      while (condition A<B) {
      // do this, one or more statements. e.g. A++
      if (condition A>C) { continue }
      // do something else, one or more statements
      }


    The JavaScript Object Model
    JS was designed explicitly for web page use. It divides objects into 3 groups: browser objects, language objects (aka Built-in objects) and HTML objects. Objects have methods and properties that can be accessed using dot notation such as window.status. The various object types will be discussed in more detail below:

    Browser Objects Special browser objects have been built into the JS language to take advantage of the different features and capabilities provided by the browser. The primary browser objects are listed below:
    • Window Object: The windows object is the top subject and default in the JS object hierarchy. Therefore, there is NO need to reference by its name. Every browser window that is currently open has a corresponding window object and all other objects are children of one of the window objects. When opening an additional window, it can referenced by the window name. There are special window objects shown below.

      Target Description
      parent A window or frame whose frameset contains the current frame.
      Self The current window.
      Top The topmost browser window.
      Blank Loads the document into a new unnamed window.

      Common Window Methods
      Alert() Displays a dialogue box to communicate with users.
      Prompt() Requests user input in a text field via dialog box.
      Confirm() Allows users to confirm their response in the alert window dialog box.
      Open() Creates a new control window.
      Close() Closes the control window.

      Let's look a couple of examples that utilize window objects. The first is the very common popup window. In our example, the window would open when a link is clicked.

      Code Sample:
      <a href="#" onClick="MyWindow=window.open('http://www.myfavoritesite.com','MyWindow','toolbar=no,
      location=no,resizable=no,width=200,height=400'); return false;">click here</a>


      The next example will show how windows objects can be used with a with statement to relate several properties/methods to a single object which a more efficient approach. (Not supported in IE 3.0).

      Code Samples:
      Using with statement

      myWindow = open("","newwin","height=100,width=100");
      with (myWindow.document) {
      open();
      bgColor="blue";
      fgColor="white";
      write("Hello Sara"); }


      Without with statement

      MyWindow.document.open()
      MyWindow.document.bgColor=”blue”;
      MyWindow.document.fgColor=”white”;
      MyWindow.document.write=(”Hello Sara”);
      MyWindow.document.close() 10


    • Document Object: The document object contains properties for every link, anchor and form on a page and also subelements of those elements. It also contains properties for background color, title, foreground color, link colors and other page attributes. It is defined when the <body> tag is evaluated in an HTML page. The object exists as long as the pg is loaded. The document object has the following methods:

      Method Description
      clear() Completely erases a document window
      close() Displays the results of write operations on the page.
      open() Used with write operations to start buffered output.
      write(str) Used to write any string expression to the current document
      writeln(str) Same as write except it adds a carriage return after writing arguments.

      An example of the document object in action would be a page last modified script which will return the date and time document was most recently saved/modified.

      Code Sample:
      document.write(“This pg last updated “ + document.lastModified);

    • History Object: Allows you to access browser history through scripts. This is like using the browser’s back and forward buttons. The history object has a length property which indicates how many URLs are stored in the history list. The history object uses back(), forward() and go() methods. An example would be history.back();.

    • Location Object: Describes the URL of a document and has properties that represent the protocol, hostname, path and port. Can create buttons, hypertext, graphic, etc. links to send users to different targets. The table below lists the location objects:

      Property Description
      href Most frequently used property. Specifies the URL of a file or site
      Protocol http or ftp currently in use
      Host Refers to the
      Hostname Specifies the host name of the URL
      Port Specifies port # (if 1 is provided)
      Pathname Indicates the path to the desired file
      Search Returns the text following the ? character (if a search string is present)
      Hash Specifies the internal link of anchor name followed by (#) in the URL.

      Code Sample:
      location.href = http://www.ciwcertified.com;
      <form><input=”button” value=” onClick=” location.href=’http://www.ciwcertified.com’;></form>


    • Image Object: most popular use is for “mouseover” animated buttons in IE 4.0 and Netscape 3.0+. The image object loads as an array and has no built-in methods. The replaced new image must be less than or equal in size to the original.

      Examples:
      document.images[0].src = newImage.jpg;
      document.[imageName].src = "newImage.gif"


      To create an instance of the image object:

      imageVarName = new Image();
      To assign a source:
      imageVarName.src = "image.gif";


      Properties Event Handlers
      Src OnAbort: occurs when user cancels loading image
      Height and Width OnError: activates if img has become corrupted/ fails to load
      Length OnKeyDown
      Lowsrc: loads low-bandwidth imgs OnKeyPress
      Complete OnKeyup
      Hspace and vspace OnLoad: activates when img finished loading into the browser.
      Border Reflects the border attribute

    Language Objects

    JS utilizes HTML <forms> and its elements as objects that can be used to manipulate Date, Array, Math and String information in useful ways. These objects are also known as built-in objects and are not part of the containment hierarchy.
    • String Object: Information about each specific string is stored in properties. Can be a set of text, #, or combination of characters that acts as text, such as literals (“How are you?”) or variables (userName). Has methods that allow you to write strings of characters as well as test for the presence of certain characters. Form Validation using String Methods: (Important for client-side) can test for certain patterns in credit card #s as each cc have their specific starting #s. Validate Email address by checking whether or not it has @.

      1. extract a subset (called a substring) for a given string
      2. retrieve the number of characters from a string: length()
      3. find the position of given characters in a string: indexOf()

      The standard way to create a string is: var str = new String("Hello"); but can be typed loosely also: “hello”.bold();

      Commonly used string methods include:

      Method Description
      toLowerCase( ) Converts all characters in string to lowercase
      toUpperCase( ) Converts all characters in string to upppercase
      indexOf( string ) Searches forward through a string for the given string value
      lastIndexOf( string ) Searches backward through a string for the given string value
      Substring( A,B ) Returns a section of a string, defined by a beginning ( A ) and ending ( B ) index number
      charAt( # ) Returns a single character from a string at the index # specified

      Examples:
      “Hello, World!”.length;
      Will return the integer value of 13.

      “sarachoe@ABC.com.”indexOf(“choe@”,0);
      Would return a value of 4.

      “sarachoe@ABC.com.”indexOf(“choe@”,5);
      Would return a value of -1.

      “Abc1234xyz”.substring(3,7);
      Would return the value 1234

      “ABCDE”.charAt(3);
      Result is D

      String Object Formatting Methods: document.write(“insert the methods listed below”);

      Method Example HTML Equivalent
      Anchor("anchor name") "part 2".anchor("p2") <a name="p2">part 2</a>
      big() "Welcome".big() <big>Welcome</big>
      Blink() "New".blink() <blink>New</blink>
      Bold() "Hot".bold() <b>Hot</b>
      Fixed() "Name Phone".fixed() <TT>Name Phone</TT>
      fontcolor("color") "savage".fontcolor("blue") <TT>Name Phone</TT>
      fontcolor("color") "savage".fontcolor("blue") <font color="blue">savage</font>
      Fontsize(size) "Dude".fontsize(6) <font size="6">Dude</font>
      italics() "Other".italics() <I>Other</I>
      link("url") "NASA".link("http://nasa.gov") <a href=http://nasa.gov>NASA</a>
      Small() “Don’t look”.small() <small> Don’t look</small>
      Strike() “Don’t look”.strike() <strike> Don’t look</strike>
      sub() “H” + “2”.sub() + “0” H<sub>2</sub>0
      sup() “E=MC” + “2”.sup() E=MC<sup>2</sup>
      ToLowerCase() “Hello”.toLowerCase() hello
      ToUpperCase() “Hello”.toUpperCase() HELLO

      String Object Special Characters

      Character Description
      \b Backspace
      \f Form Feed
      \n New Line
      \r Carriage Return
      \t Tab
      \" Double Quote
      \' Single Quote
      \\ Backslash

    • Array Object
      The array object is used to group related data to be associated with a single variable. An array is a series of objects all of which are the same size and type. Each object in an array is called an array element. For example, you can have an array of integers or an array of characters or an array of anything that has a defined data type. Each element in the array has the same data type and can have the same or different values, and the entire array is stored contiguously in memory with no gaps in between. An empty array is created using the syntax: Myarray = new Array();. New is a keyword used to initialize the array, similar to the var keyword in variable. Once the array is declared, you assign multiple values to the elements of the array as shown in the example below:

      Examples:
      var questions = new Array(10); // there will be a total of 11 elements
      question[0] = ”What is…?”;
      question[1] = ”What is…?”;
      alert(questions.length): // will return 11


      To declare and assign a value at the same time, try the following:

      mybook = new Array("book1", "book2", "book3");

      Some objects have built-in arrays: e.g., window objects has a built-in frames array that allows you to reference frames by their index # within that array.

    • Date Object
      The date object is used to deal with the conversion back and forth between our calendar dating system and the computers date system. The date object one has 1 property (prototype) which allows you to add additional properties.

      A date instance can be created in one of the following ways:

      new Date()
      new Date( datestring )
      new Date( yr, mon, day )


      Date object’s built-in Methods

      Method Description
      getDate() Retrieves the day number(1-31)
      GetDay() Retrieves the day-of-week value (0-6; 0 is Sunday)
      getMonth() Retrieves the month number (0-11; 0 is January)
      getYear() Retrieves the number of years since 1900
      getHours() Retrieves the hour number (0-23; 0 is midnight)
      getMinutes() Retrieves the number of minutes (0-59)
      getSeconds() Retrieves the number of seconds (0-59)
      getTime() Retrieves the number of milliseconds that have elapsed since midnight on Jan 1, 1970
      setDate(value) Assigns the date within the month (1-31)
      ToLocaleString() Returns the date in the local system's format

    • The Math Object:
      The math object is used for various forms of mathematical calculation and is useful for working in scientific fields of study. The math object is a static object that contains some constant values (e.g. PI) as properties. You do not need to create a new instance and cannot reassign values as with Date object.

      Examples:
      var num=5.2;
      alert(num);
      var newnum = Math.round(num);
      alert(newnum);
    Interactive Forms
    1. retrieves users’ inputted data
    2. launches script (event handlers)
    3. can create drop-down box of URL choices
    4. can create check box to control the appearance of next pg

    There are 2 ways of referring to Form Objects:
    1. 1. By name:
      <form name="myForm" >
      <input type="text" name="firstName" >
      </form>
      document.myForm.firstName.value;
    2. By index number in the form elements array:
      document.forms[0].elements[0].
    Features of form objects:

    Properties Description
    Action specifies the URL for the data submission
    Elements array of objects
    Encoding String containing the MIME encoding of the form (specified in the ENCTYPE attribute)
    Length # of elements in the form
    Method submission method of data to a server
    Name as defined in the <form> tag
    Target name of the window to where submissions are directed

    Forms utilize several HTML objects that are listed below.
    • Button Object
      This is the simplest of all objects and can be used to activate a function or open a URL (among other things).

      Properties    Methods    Event Handlers
      Name    Click()    onClick
      Value          

      Example:
      <input type="button" value="do action" onClick="function();">
      document.formName.buttonName.value="New Value";
      document.formName.buttonName.value;


    • Checkbox Object
      The checkbox object creates a box that returns a Boolean value of true or false depending on whether or not it is checked.

      Properties    Methods    Event Handlers
      checked    Click()    onClick
      DefaultChecked          
      Name          
      Value          

    • Text and Textarea objects
      The text object creates a textbox that can only display a single line of text whereas Textarea objects can display multiple, scrolling lines of text.

      Properties    Methods    Event Handlers
      defaultValue    Blur()    onBlur: processes when the cursor is moved away from this object
      Value    focus()    onFocus: processes when cursor is moved to this object
      Name    select()    onSelect: processes when text in this object is highlighted

      Example:
      Name:<BR>
      <INPUT TYPE="text" SIZE="30" NAME="name" value="Your name here"><BR>


      This would create:
      Name:


      Example:
      <textarea cols='25' rows='5' name='name'></textarea>

      This would create:


    • Radio Button Object
      Used to select among mutually exclusive options; yes/no. Not both.

      Properties    Methods    Event Handlers
      DefaultChecked    Click()    onClick
      checked          
      Value          
      Name          
      Length          

    • The Select Object
      A drop-down list or a list box of items used in an HTML form. Common event handlers are onChange, onBlur and onFocus.
    FORM Validation
    Used to verify correct/valid form submissions, increase end-user satisfaction and conserve bandwidth. Not entirely possible to validate all form submissions, but some validation is better than none. You should note that some users may get frustrated by intervening validation.

    Form Validation Event Handlers
    Form validation with Javascript is efficient as validation takes place on the client machine (so there is no delay in order to contact a remote server). Form validation is accomplished by integrating form event handlers and other program flow structures, such as if else statements, for loop...etc.

    Event handlers for forms

    Onblur Executes JavaScript whenever a user, using the mouse, moves the focus away from a form element. You use it to check each element individually and ask the user to fix the invalid input before moving on.
    Onsubmit Executes JavaScript whenever someone clicks the "submit" button. No validation takes place until the user submits the form.

    Example:
    Sample code fragment for password field validation:
    <script Language="JavaScript">
    <!--
    function Form1_Valid(theForm) { // check to see if the field is blank
    if (theForm.Alias.value == "") }
    {
    alert("You must enter an alias.");
    theForm.Alias.focus();
    return (false);
    } // require at least 5 characters be entered
    if (theForm.Alias.value.length < 5)
    {
    alert("Please enter a minimum of 5 characters in the \"Alias\" field.");
    theForm.Alias.focus();
    return (false); } // check if both password fields are identical
    {
    alert("The two passwords are different.");
    theForm.Password2.focus();
    return (false); } //--></script>
    You will need to specify the form action as the JavaScript:
    <form action="javascript.asp" method="POST" onsubmit="return Form1_Valid(this)" name="Form1">


    Cookies and JavaScript Security

    Cookies were developed by Netscape and are text files stored on the user's computer and sent to the user’s browser when a user generates an HTTP request. Referred to as "persistent client state HTTP cookies" and "persistent HTML". Help maintain state, aid authentication, remove redundant steps and track user behavior. There are 2 actions can occur:

    1. Small memory-resident pieces of information, are originally stored in the system memory or files of your computer. A server can deposit cookies on the user's hard drive
    2. Any cookies already on the user's system that match the server's domain can be passed along in the request header.

    Most browsers have options that allow the user to determine how they wish to deal with cookies. Netscape Navigator 4.0 has the following options:
    1. Accept all cookies
    2. Accept only cookies that get sent back to the originating server. Disables “shared” cookies.
    3. Disable cookies
    4. Warn before accepting a cookie

    Who can Send Cookies?
    Cross-domain posting is impossible (i.e., 1 domain cannot deposit a cookie for another). Some domains "share" cookies because some sites (Amazon, Yahoo, DoubleClick…) belong to the same network as subdomains (which allows another network member to load content onto its another member’s main search page). For example, whenever a user accesses Yahoo’s main page, the user is also accessing Amazon. Even though the user may have only visited Yahoo, the cookie can be set from another site.

    Storing Cookies
    There are rules that govern the use of cookies. Internet Explorer limits you to 1 cookie per domain, whereas Netscape allows up to 20 pairs per domain. A user can store no more than 300 cookies on their hard drive. HTTP header for cookie can be no larger than 4 kb. Netscape stores in a single text file named cookies.text. ProgFiles\Netscape\Users\Username directory. IE 4.0 stores them in Windows\Temporary Internet Files\*directory. Cookies will persist until their expiration date. The user can also write their “autoexec.bat” file to delete cookie files every time the machine boots. They can also be reassigned by adding an expiration date that has already passed.

    Why use Cookies?
  • Authentication -no need to enter the password again. Hazard is other user can access the page without permission.
  • Storing user information e.g., os/browser type, ISP, IP address, history of sites visited.
  • State maintenance with cookies. When user returns, they can resume at the point where they left. For example, it could be used to save your spot in an online game or allow a visitor to click only once to make a purchase in an online store.


  • JavaScript and Cookies
    Cookies can be assigned using the following methods:

    document.cookie = "name=value"; // this is all that’s required but, can also br written as:
    document.cookie = "name=value;expires=date;secure";


    You can test for cookie presence using the following method:

    alert(document.cookie);

    JavaScript Security Issues
    JS can launch “Helper” programs which hackers can manipulate. Malicious and accidental programs can generate infinite sequences that may cause the browser to hang. User must quit the browser to stop.

    Controlling Frames in JavaScript

    Frames help to maximize the sophistication of your web site by allowing you to leave some information with the user at all times. This technique provides both ease of navigation, and a means to control the users' paths and destinations.

    Understanding Frames and Targets
    Frames exist within framesets and will usually have a default source file. The example below shows a simple frameset that would create 2 frames on the page, each covering 50% of the page.

    Example:
    <HTML>
    <HEAD>
    <TITLE>Master Page</TITLE>
    </HEAD>
    <FRAMESET COLS="50%,50%">
    <FRAME SRC="pagea.html">
    <FRAME SRC="pageb.html">
    </FRAMESET>
    </html>


    To create a more complex arrangement of web pages you can place a frameset and its associated frames within another frameset, which is known as nesting frames. The following example shows one way in which this can be done:

    Example:
    <FRAMESET ROWS="*,50%">
    <FRAMESET COLS="25%,25%,*">
    <FRAME SRC="one.htm">
    <FRAME SRC="two.htm">
    <FRAME SRC="three.htm">
    </FRAMESET>
    <FRAME SRC="four.htm">
    </FRAMESET>


    Break Out of Frames
    To ensure that users load your page in the browser's main window, instead of loading in another site's frame, you add the following script into the HEAD portion of your document:
    if (window != top) top.location.href = location.href;

    2 ways to Target Frames
    1. By target name - denoted by the frame’s “NAME” attribute:
      • Parent = the file containing the frameset in which the currently selected frame is defined. It loads the file into the immediate parent(the frame, itself) of the document the link is in.
      • Top = highest window object in the hierarchy and the parent of all parents. It loads the document into the topmost window. If the topmost page doesn't use a frame, the object model has only one level of window objects, which means that top = window. Case-sensitive.
    2. By number in the frames array:
      You may control navigation between frames using the following HTML codes to create different navigational links:

      <A HREF="javascript:history.reload()">Reload (this frame)</A>
      <A HREF="javascript:history.back()">Back (this frame)</A>
      <A HREF="javascript:history.forward()">Forward (this frame)</A>
      <A HREF="javascript:parent.frames[2].history.reload()">Reload (bottomrow frame)</A>
      <A HREF="javascript:parent.frames[2].history.back()">Back (bottomrow frame)</A>
      <A HREF="javascript:parent.frames[2].history.forward()">Forward (bottomrow frame)</A>
    Changing two or more frames

    <form><input type=”button” value=”Change Frames”
    onClick=”changeFrames();”></form>
    <script> function changeFrames() {
    parent.rightTop.location.href=”banner.htm”;
    parent.rightBottom.location.href=”main.htm”; } </script>


    Client-Side JavaScript

    Two popular uses of client-side JavaScript are the use of image maps and browser detection.

    Defining Image Maps:
    Image maps are used to divide an image into sections that can have individual links associated with them. In other words multiple links can be associated with 1 image. The URL that you are taken to when clicking on the image depends on which part of the image you click on.

    Example:
    <map name=”myMap”>
    <area coords=”0,0,77,75” href=home.html”>
    </map>


    In the above example, the first 2 numbers (0 and 0) represent the upper-left corner (x and y coordinates) of the rectangle. The second set of numbers (77 and 75) represent the bottom-right corner (x and y coordinates) of the rectangle.

    Scripts can be added to Image Maps. For example you could add inline scripts with onClick (event handlers) to the <area> tag or alert().

    Example:
    <map name=”myMap”>
    <area coords=”0,0,77,75” href=home.htm”
    onMouseOver="status='Visit Senegal'; return true;"
    onMouseOut="status=’ ‘;return true;">
    </map>


    Navigator Object
    The Navigator object is used to detect a user’s browser and operating system. The Navigator object is stand-along so it does not contain other objects nor is it contained within other objects.

    Property Description
    AppName Browser name
    AppVersion Browser Version
    appCodeName Browser codename (e.g. Mozilla for Netscape)
    userAgent Operating system. Returns appCodeName/appVersion

    Example:
    <HTML>
    <HEAD>
    <TITLE>Browser Detector</TITLE>
    <SCRIPT>
    <!--
    function showInfo() {
    var info=""
    info += "\nWelcome, " + navigator.appCodeName
    info += " user!\nYou are using the "
    info += navigator.appName + " browser,\nversion "
    info += navigator.appVersion + ".\nYour user agent "
    info += "information is " + navigator.userAgent
    alert(info)
    }
    //-->
    </SCRIPT>
    <link rel="STYLESHEET" type="text/css" href="jsclass.css">
    </HEAD>
    <BODY>
    <A HREF="javascript:void(showInfo());">Click Here</A>
    </BODY>
    </HTML>


    This would produce the following:
    Click Here

    Custom JavaScript Objects
    • Advantages:
      1. You can create sophisticated solutions with a minimum of coding
      2. You can represent programming constructs as objects allowing U to code efficient schemes for evaluating forms / creating client-side databases.
    Creating a Custom JavaScript Object:
    The object is similar to a database record in that it contains various fields or properties that are shared among instances of that object. A Constructor is a special function that enables you to define or create instances and a custom JavaScript object. It is the building block of all custom objects. It defines the properties and methods of your object. Defining a constructor is the 1st step in creating an object. Specifically, a constructor creates an empty template from which real-time objects called instances can be generated.

    Example:
    Function productObject(id, item, description,material,price) {
    This.id = id;
    This.item = item;
    This.myDescription = description; //2 words don’t have to match. But
    “description” must match the function’s argument list parameter.
    This.material = material;
    This.price = price;
    }


    The above example is a constructor. Id, item, description, material and price are parameters.

    Creating an Instance
    Instantiation - Once the constructor is defined, you need to create new instances of the object. After you instantiate new copies of the object, you will then populate the object properties with info. To instantiate and populate the properties of new instance with actual data, you must declare variables.

    Example:
    Ashtray = new productObject(“hf-01”,”Make Ashtray”,”Senegal ashtray”,”wood”,”$30.00”);

    Var declared parameters are defined.

    In the above example we declare our variable Ashtray and then define parameters such as Make Ashtray, Senegal Ashtray, etc. It is more sensible to use array variables rather than creating individual variables as above. The example below shows how this can be done.

    Example:
    Var product = new Array();
    Product[0] = new productObject(“hf-01”,”mask ashtray”,”Senegal ashtray”,”wood”,”$30.00”);
    Product[1] = new productObject(“hf-02”,”mask chair”,”ivory sculptor”,”mahogany”,”$130.00”);


    Creating Object Methods:
    To retrieve (view) the info you just stored in instances, you shud define a method (as many, as simple or as sophisticated as you want as you want). If you don’t create function as method, you cannot use the “THIS” keyword and the calling statement would be different. First, add the method “This.displayOne = displayone” to the initial constructor. Note that there are no parentheses after this method. If there were, the code would call the function at that moment.

    Example:
    Function productObject(id, item, description,material,price) {
    This.id = id;
    This.item = item;
    This.myDescription = description;
    This.material = material;
    This.price = price;
    This. displayOne = displayOne;
    }
    <select name=”itemName”>
    for (I=0;I<product.length;I++) {
    document.write(“<option>” + product[I].item);
    }
    <input type=”button” value=”Get info” onClick=”var I =
    document.prodForm.itemName.selectedIndex;
    product[I].displayOne(); ’>

    function displayOne() {
    content=””; content+=<html><head><title>” + this.item +”</title></head>”;
    content+=”<body>…”;
    content+=<tr><TD>Description: “ + this.description; …
    newWindow(oneWindow);
    }

    Creating Functions for your Objects
    When you need to retrieve/view multiple objects in an array, you need to create a function, e.g., “if…else”, as well as “window.open” that shows all products. Methods operate only on a single instances of objects rather than all objects.





    IT Showcase