javascript notes(2)

Upload: charles-otwoma

Post on 05-Apr-2018

229 views

Category:

Documents


3 download

TRANSCRIPT

  • 8/2/2019 Javascript Notes(2)

    1/54

    SDBIT 506: FUNDAMENTALS OF WEB USING JAVASCRIPTLECTURE NOTES

    By Peter Wanyama

    1. INTRODUCTION

    1.1 BASIC CONCEPTS

    What is JavaScript?JavaScript is Netscape's cross-platform, object-based scripting language for client andserver applications.

    Types of JavaScript: Brief HistoryNetscape Communications developed two related scripting languages in November1995 as LiveWire and LiveScript. In December the same year NetscapeCommunications and Sun Microsystems (creators of Java) jointly renamed LiveScript asJavaScript.Microsoft developed its own related scripting language and named it Jscript.

    Presently there are two types of JavaScript:i) Navigator JavaScript, also called client-side JavaScriptClient-side JavaScript is interpreted by a the Navigator run-time machineii) Livewire JavaScript, also called server-side JavaScript

    LiveWire is an application development environment that uses JavaScript for creatingserver-based applications similar to CGI (Common Gateway Interface) programs. Incontrast to Navigator JavaScript, LiveWire JavaScript applications are compiled intobytecode executable files.

    Features of JavaScript

    JavaScript:- Is a scripting language i.e. a lightweight programming language with simpler

    syntax- Is an interpreted language i.e. scripts execute w/o preliminary compilation- Is the most popular scripting language i.e. supported by all the major browsers

    such as Netscape and IE

    Uses of JavaScriptNavigator JavaScript was designed to add interactivity to HTML pages. Specifically,JavaScript:

    - Gives HTML designers a programming tool.

    -Can put dynamic text into a HTML page

    - Can react to events- Can read, write and change the contents of a HTML element- Can be used to validate form data before it is submitted to a server, saving the

    server extra processing

    Versions of JavaScript:Each version of Navigator supports a different version of JavaScript. To help you writescripts that are compatible with multiple versions of Navigator, this manual lists theJavaScript version in which each feature was implemented.

    The following table lists the JavaScript version supported by different Navigatorversions. Versions of Navigator prior to 2.0 do not support JavaScript.

  • 8/2/2019 Javascript Notes(2)

    2/54

    JavaScriptversion

    Navigatorversion

    JavaScript 1.0 Navigator 2.0

    JavaScript 1.1 Navigator 3.0

    JavaScript 1.2 Navigator 4.0-4.05

    JavaScript 1.3 Navigator 4.06-4.5

    Each version of the Netscape Enterprise Server also supports a different version ofJavaScript. To help you write scripts that are compatible with multiple versions of the

    Enterprise Server, this manual uses an abbreviation to indicate the server version inwhich each feature was implemented.

    Abbreviation

    Enterpriser Serverversion

    NES 2.0 Netscape EnterpriseServer 2.0

    NES 3.0 Netscape EnterpriseServer 3.0

    Compatible browsers:The browsers and browser versions can execute JavaScript code:

    - IE 3.0 and later versions- Netscape Navigator 2.0 and later versions- Opera- Mozilla (Open source browser)-

    Safari (for Macintosh O/S)

    1.2 JAVASCRIPT AND JAVA

    JavaScript and Java are similar in some ways but fundamentally different in others. Thefollowing table summarizes the fundamental distinctions between the two languages.

    JavaScript Java

    Interpreted (not compiled) by client.Compiled bytecodes downloadedfrom server, executed on client.

    Object-based. Uses built-in, extensibleobjects, but no classes or inheritance.

    Object-oriented. Applets consist ofobject classes with inheritance.

    Code integrated with, and embedded in, Applets distinct from HTML

  • 8/2/2019 Javascript Notes(2)

    3/54

    HTML. (accessed from HTML pages).

    Variable data types not declared (loosetyping).

    Variable data types must bedeclared (strong typing).

    Dynamic binding. Object referenceschecked at runtime.

    Static binding. Object referencesmust exist at compile-time.

    1.3 OTHER WEB TECHNOLOGIES

    - html, xhtml, dhtml

    - CSS: A style sheet defines the layout, colours, fonts and other visualcharacteristics for presenting the contents on a web page. This eliminates a lotof attribute information inside HTML/XHTML/DHTML tags

    - Plug-ins: Are independent applications embedded in browsers to assist in the

    viewing of information of diverse formats on client computers. Different plug-ins exist for different file formats. The most commonly available plug-ins are:Adobe Acrobat Reader, Flash (Macromedia Corporation)

    - Java Applets: are small programs that are meant to run on a page in a Webbrowser.

    2. SCRIPTING

    2.1 BASIC SCRIPTING CONCEPTS

    What You Should Already Know

    This course assumes you have the following basic background:

    A general understanding of the Internet and the World Wide Web (WWW).

    Good working knowledge of HyperText Markup Language (HTML).

    Some programming experience with a language such as C or Visual Basic isuseful, but not required.

    Where to Put the JavaScriptJavaScript in a page will be executed immediately while the page loads into thebrowser. This is not always what we want. Sometimes we want to execute a script whena page loads, other times when a user triggers an event.Scripts in the head section:Scripts to be executed when they are called, or when an event is triggered, go in thehead section. When you place a script in the head section, you will ensure that thescript is loaded before anyone uses it.

    ....

  • 8/2/2019 Javascript Notes(2)

    4/54

    Scripts in the body section:Scripts to be executed when the page loads go in the body section. When you place ascript in the body section it generates the content of the page.

    ....

    Using an External JavaScript

    Sometimes you might want to run the same JavaScript on several pages, without havingto write the same script on every page.To simplify this, you can write a JavaScript in an external file. Save the externalJavaScript file with a .js file extension.

    Note: The external script cannot contain the tag!To use the external script, point to the .js file in the "src" attribute of the tag:Note: Remember to place the script exactly where you normally would write the script!

    Using the SCRIPT tagThe tag is an extension to HTML that can enclose any number of JavaScriptstatements as shown here:

    JavaScript statements...

    A document can have multiple SCRIPT tags, and each can enclose any number ofJavaScript statements.

    Specifying the Scripting Language

    Accomplished using the type attribute of the script tag with the value being the nameof the scripting language in use.

    document.write("Hello World!")

    Ending Statements with a Semicolon?

    With traditional programming languages, like C++ and Java, each code statement hasto end with a semicolon.

  • 8/2/2019 Javascript Notes(2)

    5/54

    Many programmers continue this habit when writing JavaScript, but in general,semicolons are optional! However, semicolons are required if you want to put morethan one statement on a single line.

    Specifying the JavaScript version

    The optional LANGUAGE attribute specifies the scripting language and JavaScriptversion:

    JavaScript statements...

    JavaScriptVersion specifies one of the following to indicate which version of JavaScriptyour code is written for:

    - specifies JavaScript for Navigator 2.0.- specifies JavaScript for Navigator 3.0.

    Statements within a tag are ignored if the user's browser does not have the

    level of JavaScript support specified in the LANGUAGE attribute; for example:

    - Navigator 2.0 executes code within the tag; itignores code within the tag.

    - Navigator 3.0 executes JavaScript code within either the or tags.

    If the LANGUAGE attribute is omitted, Navigator 2.0 assumes LANGUAGE="JavaScript".Navigator 3.0 assumes LANGUAGE="JavaScript1.1"

    Hiding scripts within comment tags (From older browsers)

    Only Netscape Navigator versions 2.0 and later recognize JavaScript. To ensure thatother browsers ignore JavaScript code, place the entire script within HTML commenttags, and precede the ending comment tag with a double-slash (//) that indicates aJavaScript single-line comment:

    Since browsers typically ignore unknown tags, non-JavaScript-capable browserswill ignore the beginning and ending SCRIPT tags.

    Specifying a file of JavaScript code

    The SRC attribute of the tag lets you specify a file as the JavaScript source(rather than embedding the JavaScript in the HTML). The source file cannot contain the tag and must be saved as a .js file. For example:

    My Page

    ...

  • 8/2/2019 Javascript Notes(2)

    6/54

    ...

    This attribute is especially useful for sharing functions among many different pages.The closing tag is required.

    Using JavaScript expressions as HTML attribute values

    UsingJavaScript entities, you can specify a JavaScript expression as the value for anHTML attribute. Entity values are evaluated dynamically. This allows you to create moreflexible HTML constructs, because the attributes of one HTML element can depend oninformation about elements placed previously on the page.You may already be familiar with HTML character entities by which you can definecharacters with special numerical codes or names by preceding the name with anampersand (&) and terminating it with a semicolon (;). For example, you can include agreater-than symbol (>) with the character entity > and a less-than symbol (

  • 8/2/2019 Javascript Notes(2)

    7/54

    Because JavaScript must ignore comments, there is an appropriate syntax fordemarcating text as a comment. For single line comments, simply precede the line withtwo backslashes. For multi-line comment blocks, begin the comment with /* and closewith */.

    //A lonely ol' single line comment /* A dense thicket of commentary, spanningmany captivating lines of explanation and intrigue. */

    2.2 JAVASCRIPT: THE LANGUAGE2.2.1 FundamentalsLexical Structure

    The lexical structure of a programming language is the set of elementary rulesthat specify how you write a program. It is the lowest level syntax of alanguage and specifies such things as what identifier names look like. Some ofthe basic rules for JavaScript are:

    - JavaScript is case sensitive.- Whitespace, tabs, and newline characters are ignored except when part of

    string constants. Whitespace can be added as needed for readability.- Block comments begin with /* and end with */ [preferred over single liners]- Single line comments begin with //- Identifiers are names for variables, functions and loop labels. The firstcharacter must be an ASCII letter, underscore or dollar sign. Following characterscan also include digits. Letters are A to Z and a to z.- Reserved words (or keywords) have special meanings within the languagesyntax.- Statements terminate in semicolons! Make sure to always terminatestatements with a semicolon.

    Java Script Elements

    JavaScript code, much like other programming languages, is made up of statementsthat serve to make assignments, compare values, and execute other sections of code.By and large, programmers will already be familiar with JavaScript's usage of variables,operators, and statements. Below is a chart summarizing the main elements ofJavaScript grammar.

    Variables

    Labels that refer to a changeable value.

    Operators

    Actors that can be used to calculate or compare values.

    Expressions Any combination of variables, operators, and statements that evaluateto some result.Statements

    As in English, a statement pulls all grammatical elements together intoa full thought. JavaScript statements may take the form of conditionals,loops, or object manipulations.

    Objects Containing constructs that possess a set of values, each value reflectedinto an individualpropertyof that object.

    Functions andMethods

    A function is a discrete set of statements that perform some specificaction. A method is a function used with objects.

    2.2.2 Data Types

    A value, the data assigned to a variable, may consist of any sort of data. However,JavaScript considers data to fall into several possible types. Depending on the type ofdata, certain operations may or may not be performed on the values. For example, you

  • 8/2/2019 Javascript Notes(2)

    8/54

    cannot arithmetically multiply two string values. Variables can be these types:

    Numbers

    3 or 7.987, Integer and floating-point numbers. Integers can bepositive, 0, or negative.

    Booleans True or False. The possible Boolean values are true and false. Theseare special values, and are not usable as 1 and 0. In a comparison,any expression that evaluates to 0 is taken to be false, and anystatement that evaluates to a number other than 0 is taken to be

    true.Strings "Hello World!" Strings are delineated by single or double quotation

    marks. (Use single quotes to type strings that contain quotationmarks.)

    Objects Used to create user-defined objects. E.g. myObj = new Object();Null Not the same as zero - no value at all. A null value is one that has no

    value and means nothing.Undefined A value that is undefined is a value held by a variable after it has

    been created, but before a value has been assigned to it.

    Note:

    JavaScript is a loosely typed language -- you do not have to specify the data type of avariable when you declare it, and data types are converted automatically as neededduring script execution. By and large, you may simply assign any type of data to anyvariable.

    The only time data-typing matters is when you need to perform operations on the data.Certain operators behave differently depending on the type of data being deal with. Forexample, consider the + operator:

    "5" +"10"

    yields "510" (string concatenation)

    5 + 10 yields 15 (arithmetic sum)Data Type Conversion

    JavaScript is a dynamically typed language. That means you do not have to specify thedata type of a variable when you declare it, and data types are converted automaticallyas needed during script execution. So, for example, you could define a variable asfollows:var answer = 42And later, you could assign the same variable a string value, for example,answer = "Thanks for all the fish..."Because JavaScript is dynamically typed, this assignment does not cause an error

    message.In expressions involving numeric and string values with the + operator, JavaScriptconverts numeric values to strings. For example, consider the following statements:x = "The answer is " + 42 // returns "The answer is 42"y = 42 + " is the answer" // returns "42 is the answer"In statements involving other operators, JavaScript does not convert numeric values tostrings. For example:"37" - 7 // returns 30"37" + 7 // returns 377

    2.2.3 Reserved words, Variables,Literals/ Constants and Identifiers

    Reserved WordsReserved words in this list cannot be used as JavaScript variables, functions, methods,or object names. Some of these words are keywords used in JavaScript; others arereserved for future use.

  • 8/2/2019 Javascript Notes(2)

    9/54

    abstractbooleanbreakbytecase

    catchcharclassconstcontinuedebuggerdefaultdelete

    dodouble

    elseenumexportextendsfalsefinalfinally

    floatforfunctiongotoifimplementsimportin

    instanceofintinterfacelongnative

    newnullpackageprivateprotectedpublicreturnshortstatic

    super

    switchsynchronizedthisthrowthrowstransient

    truetrytypeofvarvoidvolatilewhilewith

    Literals /Constants

    You use literals to represent values in JavaScript. These are fixed values, not variables,that you literallyprovide in your script. This section describes the following types ofliterals:

    Array Literals

    An array literal is a list of zero or more expressions, each of which represents an array

    element, enclosed in square brackets ([]). When you create an array using an arrayliteral, it is initialized with the specified values as its elements, and its length is set tothe number of arguments specified.The following example creates the coffees array with three elements and a length ofthree:coffees = ["French Roast", "Columbian", "Kona"]If an array is created using a literal in a top-level script, JavaScript interprets the arrayeach time it evaluates the expression containing the array literal. In addition, a literalused in a function is created each time the function is called.Array literals are also Array objects.

    Extra Commas in Array LiteralsYou do not have to specify all elements in an array literal. If you put two commas in arow, the array is created with spaces for the unspecified elements. The followingexample creates the fish array:fish = ["Lion", , "Angel"]This array has two elements with values and one empty element (fish[0] is "Lion",fish[1] is undefined, and fish[2] is "Angel"):If you include a trailing comma at the end of the list of elements, the comma is ignored.In the following example, the length of the array is three. There is no myList[3]. Allother commas in the list indicate a new element.myList = ['home', , 'school', ];In the following example, the length of the array is four, and myList[0] is missing.myList = [ , 'home', , 'school'];In the following example, the length of the array is four, and myList[3] is missing. Onlythe last comma is ignored. This trailing comma is optional.

  • 8/2/2019 Javascript Notes(2)

    10/54

    myList = ['home', , 'school', , ];

    Boolean Literals

    The Boolean type has two literal values: true and false.Do not confuse the primitive Boolean values true and false with the true and falsevalues of the Boolean object. The Boolean object is a wrapper around the primitiveBoolean data type.

    Floating-Point LiteralsA floating-point literal can have the following parts:

    A decimal integer

    A decimal point (".")

    A fraction (another decimal number)

    An exponent

    The exponent part is an "e" or "E" followed by an integer, which can be signed(preceded by "+" or "-"). A floating-point literal must have at least one digit and either adecimal point or "e" (or "E").Some examples of floating-point literals are 3.1415, -3.1E12, .1e12, and 2E-12

    Integers

    Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base8). A decimal integer literal consists of a sequence of digits without a leading 0 (zero). Aleading 0 (zero) on an integer literal indicates it is in octal; a leading 0x (or 0X)indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-fand A-F. Octal integers can include only the digits 0-7.Some examples of integer literals are: 42, 0xFFF, and -345.

    Object LiteralsAn object literal is a list of zero or more pairs of property names and associated valuesof an object, enclosed in curly braces ({}). You should not use an object literal at thebeginning of a statement. This will lead to an error.The following is an example of an object literal. The first element of the car objectdefines a property, myCar; the second element, the getCar property, invokes a function(Cars("honda")); the third element, the special property, uses an existing variable(Sales).var Sales = "Toyota";function CarTypes(name) {

    if(name == "Honda")return name;else

    return "Sorry, we don't sell " + name + ".";}car = {myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales}document.write(car.myCar); // Saturndocument.write(car.getCar); // Hondadocument.write(car.special); // ToyotaAdditionally, you can use an index for the object, the index property (for example, 7), ornest an object inside another. The following example uses these options. These

    features, however, may not be supported by other ECMA-compliant browsers.car = {manyCars: {a: "Saab", b: "Jeep"}, 7: "Mazda"}document.write(car.manyCars.b); // Jeepdocument.write(car[7]); // Mazda

  • 8/2/2019 Javascript Notes(2)

    11/54

    String Literals

    A string literal is zero or more characters enclosed in double (") or single (') quotationmarks. A string must be delimited by quotation marks of the same type; that is, eitherboth single quotation marks or both double quotation marks. The following areexamples of string literals:

    "blah"

    'blah'

    "1234"

    "one line \n another line"

    You can call any of the methods of the String object on a string literal value--JavaScriptautomatically converts the string literal to a temporary String object, calls the method,then discards the temporary String object. You can also use the String.length propertywith a string literal.You should use string literals unless you specifically need to use a String object.

    Using Special Characters in StringsIn addition to ordinary characters, you can also include special characters in strings, asshown in the following example."one line \n another line"The following table lists the special characters that you can use in JavaScript strings.Table 2.1 JavaScript special characters

    Character

    Meaning

    \b Backspace

    \f Form feed

    \n New line

    \r Carriage return

    \t Tab

    \' Apostrophe or single quote

    \" Double quote

    \\ Backslash character (\)

    \XXX The character with the Latin-1 encoding specified by up to three octal digitsXXXbetween 0 and 377. For example, \251 is the octal sequence for thecopyright symbol.

    \xXX The character with the Latin-1 encoding specified by the two hexadecimaldigitsXXbetween 00 and FF. For example, \xA9 is the hexadecimal sequencefor the copyright symbol.

    \uXXXX The Unicode character specified by the four hexadecimal digitsXXXX. For

    example, \u00A9 is the Unicode sequence for the copyright symbol.Escaping Characters

    For characters not listed inTable 2.1, a preceding backslash is ignored, with theexception of a quotation mark and the backslash character itself.

    http://research.nihonsoft.org/javascript/ClientGuideJS13/ident.html#1008383http://research.nihonsoft.org/javascript/ClientGuideJS13/ident.html#1008383
  • 8/2/2019 Javascript Notes(2)

    12/54

    You can insert a quotation mark inside a string by preceding it with a backslash. This isknown as escaping the quotation mark. For example,var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."document.write(quote)The result of this would beHe read "The Cremation of Sam McGee" by R.W. Service.To include a literal backslash inside a string, you must escape the backslash character.

    For example, to assign the file path c:\temp to a string, use the following:var home = "c:\\temp"

    Variables

    Variables are temporary data holders. Variable names (or identifiers):Must begin with a letter, underscore or dollarsign, use ASCII characters andunderscore only.are case sensitive.They can not be one of the JavaScript reserved words.

    Variables are declared with the reserved word var.

    At the same time variables are declared they may or may not be assigned or takeon a value ofboolean, numeric or string type. JavaScript is said to be a looselytyped language as the variable can take on a different type later in the scriptdepending on its 'assigned' value.

    Variables have scope, ie. they are either global (defined outside any function) orlocal to the function they are defined within).

    var name; /* variable created but undefined */var signal_flag = true; /* boolean */

    var counter = 1; /* numeric */var first_name = 'fred'; /* string using single quotes */var last_name = "fred"; /* string using double quotes */

    Identifiers

    2.2.5 JavaScript Operators

    Operators are actions that manipulate, combine or compare variables. They fall intoseveral categories as follows:

    Arithmetic Operators

    Operator Description Example Result

    + Addition x=2y=2x+y

    4

    - Subtraction x=5y=2x-y

    3

    * Multiplication x=5y=4x*y

    20

    / Division 15/5 3

  • 8/2/2019 Javascript Notes(2)

    13/54

    5/2 2.5

    % Modulus (division remainder) 5%210%810%2

    120

    ++ Increment x=5x++

    x=6

    -- Decrement x=5x-- x=4

    Assignment/Compound Operators

    Operator Example Is The Same As

    = x=y x=y

    += x+=y x=x+y

    -= x-=y x=x-y

    *= x*=y x=x*y

    /= x/=y x=x/y

    %= x%=y x=x%y

    Comparison Operators

    Operator Description Example

    = = is equal to 5==8 returns false

    = = = is equal to (checks for both value andtype)

    x=5y="5"

    x= =y returns truex= = =y returns false

    != is not equal 5!=8 returns true

    > is greater than 5>8 returns false

    < is less than 5= is greater than or equal to 5>=8 returns false

  • 8/2/2019 Javascript Notes(2)

    14/54

    txt2="nice day!"txt3=txt1+txt2

    Conditional Operator

    JavaScript also contains a conditional operator that assigns a value to a variable based

    on some condition.Syntax

    variablename=(condition)?value1:value2

    Example

    greeting=(visitor=="PRES")?"Dear President ":"Dear "

    If the variable visitor is equal to PRES, then put the string "Dear President " in thevariable named greeting. If the variable visitor is not equal to PRES, then put the string"Dear " into the variable named greeting.

    Others: Typeof: typeof Object specific: new, delete Void: void [returns undefined regardless of expression]

    Statements and Expressions

    Statements define the flow of a script, known as "program flow." A statement, like afully grammatical English sentence, is made up of smaller expressions which,altogether, evaluate into a cogent meaning. In JavaScript, statements are organized aseither conditionals, loops, object manipulations, and comments.

    Good practice suggests that each JavaScript statements should be terminated with asemicolon (;). This is often not strictly necessary, as a new line also serves to separatestatements, but when multiple statements reside on the same line the semicolondelimiter is mandatory.

    A set of statements that is surrounded by braces is called a block. Blocks of statementsare used, for example, in functions and conditionals.

    Normally statements are executed sequentially:x = 1; y = 2; z = x + y; but this can be

    altered by some statements which test a condition and branch or loop according to theresult.

    3. CONTROL FLOW

    Control flow statements are known as control structures. Control structures serve todirect the order of statement execution in a program. Java Script defines thefollowing classes of control structures:

  • 8/2/2019 Javascript Notes(2)

    15/54

    3.1 Conditional/ Selection/ Decision Statements

    Very often when you write code, you want to perform different actions for differentdecisions. You can use conditional statements in your code to do this.In JavaScript we have the following conditional statements:

    If Statement

    You should use the if statement if you want to execute some code only if a specified

    condition is true.Syntax

    if (condition){code to be executed if condition is true}

    Example 1

    //Write a "Good morning" greeting if//the time is less than 10var d=new Date()var time=d.getHours()

    if (time

  • 8/2/2019 Javascript Notes(2)

    16/54

    else{document.write("Good day!")}

    If...else if...else Statement

    You should use the if....else if...else statement if you want to select one of many sets oflines to execute.

    Syntax

    if (condition1){code to be executed if condition1 is true}else if (condition2){

    code to be executed if condition2 is true}else{code to be executed if condition1 andcondition2 are not true}

    Example

    var d = new Date()

    var time = d.getHours()if (time10 && time

  • 8/2/2019 Javascript Notes(2)

    17/54

    case 2: execute code block 2break

    default:code to be executed if n isdifferent from case 1 and 2

    }

    This is how it works: First we have a single expression n (most often a variable), that isevaluated once. The value of the expression is then compared with the values for eachcase in the structure. If there is a match, the block of code associated with that case isexecuted. Use breakto prevent the code from running into the next caseautomatically.

    Example

    //You will receive a different greeting based//on what day it is. Note that Sunday=0,//Monday=1, Tuesday=2, etc.

    var d=new Date()theDay=d.getDay()switch (theDay){case 5:document.write("Finally Friday")break

    case 6:document.write("Super Saturday")break

    case 0:document.write("Sleepy Sunday")break

    default:document.write("I'm looking forward to this weekend!")

    }

    3.2 Loops/ Repetitions/ Iterations

    Very often when you write code, you want the same block of code to run over and overagain in a row. Instead of adding several almost equal lines in a script we can use loopsto perform a task like this.In JavaScript there is two different kind of loops:

    for - loops through a block of code a specified number of times

    while - loops through a block of code while a specified condition is true

    The for Loop

    The for loop is used when you know in advance how many times the script should run.Syntaxfor (var=startvalue;var

  • 8/2/2019 Javascript Notes(2)

    18/54

    Explanation: The example below defines a loop that starts with i=0. The loop willcontinue to run as long as i is less than, or equal to 10. i will increase by 1 each timethe loop runs.Note: The increment parameter could also be negative, and the

  • 8/2/2019 Javascript Notes(2)

    19/54

    The do...while Loop

    The do...while loop is a variant of the while loop. This loop will always execute a blockof code ONCE, and then it will repeat the loop as long as the specified condition istrue. This loop will always be executed once, even if the condition is false, becausethe code are executed before the condition is tested.

    do{ code to be executed}while (var

  • 8/2/2019 Javascript Notes(2)

    20/54

    Continue

    The continue command will break the current loop and continue with the next value.Example

    var i=0for (i=0;i

  • 8/2/2019 Javascript Notes(2)

    21/54

    When a prompt box pops up, the user will have to click either "OK" or "Cancel" toproceed after entering an input value.If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" thebox returns null.Syntax:

    prompt("sometext","defaultvalue")

    5. FUNCTIONS

    5.1 Introduction

    To keep the browser from executing a script as soon as the page is loaded, you canwrite your script as a function.A function contains some code that will be executed only by an event or by a call tothat function.You may call a function from anywhere within the page (or even from other pages ifthe function is embedded in an external .js file).

    Importance of using functions

    There are 2 main categories of functions in Java Script programming:

    5.2 Built-In Functions

    In order to help the programmer, JavaScript includes several useful built-in

    functions. Their names and usage follows:escape() Many special characters cause problems when submitting information

    to a 0CGI server. These characters include $ # ! spaces and tabs. Anexample of a safely encoded string is coded = escape('& '). [returns"%26%20"]. See also unescape.

    eval() Evaluates a string and returns a numeric value. An example is eval(x)+ eval(y); If x and y are strings '1' and '2' the result is three. Withoutthe eval function the value would be 12!

    isFinite() Tests whether the variable is a finite number. Returns false if contents

    is not a number or is infinite. An example of usage is flag =isFinite(var_name);

    isNaN() Tests whether the variable is nota number. Returns true if contents isnot a decimal based number. An example of usage is flag =isNaNum(var_name);

    Number() Converts the object argument to a number representing the object'svalue. If the value cannot be represented by a legitimate number, the"Not-a-Number" value, NaN is returned.Note the inconsistency in case!!

    parseFloat() Turns a string into a floating-pointnumber. If the first character can'tbe converted the result is NaN. Otherwise the conversion stops at firstcharacter that can't be converted. The function is decimal base only!an example of usage is n = parseFloat('23.45');

  • 8/2/2019 Javascript Notes(2)

    22/54

    parseInt()

    Turns a string into an integernumber. If the first character can't beconverted the result is NaN. Otherwise the conversion stops at firstcharacter that can't be converted. If a second parameter is included,the numeric base can be binary, octal, decimal or hexadecimal. Anexample is n = parseInt('55'); which places the number55 into thevariable n.

    unescape() Recovers an escaped string. An example is decoded =unescape('%26%20') [returns "& "].

    new Creates a copy or instance of an object for use or modification within aprogram. For example now = new Date; creates a Date object callednow that can be affected by all the Date properties and methods.Technically new is an operator but it works very much like a function!

    this A shorthand convention to allow working with the currentobjectmethod without naming it. This is used to save retyping a methodname.

    with A shorthand convention to allow working with the currentobjectwithout naming it. This is used to save retyping a long object name.An example is:

    with (document) {writeln(lastmodified);writeln(location);writeln(title);}

    5.3 User-Defined functions

    A function is a JavaScript procedure--a set of statements that performs a specifictask. A function definition has these basic parts:

    The function keyword. A function name. A comma-separated list of arguments to the function in parentheses. The statements in the function in curly braces.

    User-defined functions are defined at the beginning of a page, in the section.

    How to Define a Function

    The syntax for creating a function is:

    function functionname(var1,var2,...,varX){some code

    }var1, var2, etc are variables or values passed into the function. The { and the }defines the start and end of the function.Note: A function with no parameters must include the parentheses () after thefunction name:

  • 8/2/2019 Javascript Notes(2)

    23/54

    function functionname(){some code}

    Note: Do not forget about the importance of capitals in JavaScript! The word functionmust be written in lowercase letters, otherwise a JavaScript error occurs! Also notethat you must call a function with the exact same capitals as in the function name.

    The return Statement

    The return statement is used to specify the value that is returned from the function.So, functions that are going to return a value must use the return statement.

    Example

    The function below should return the product of two numbers (a and b):

    function prod(a,b){x=a*b

    return x}

    calling functionsWhen you call the function above, you must pass along two parameters:

    product=prod(2,3)

    The returned value from the prod() function is 6, and it will be stored in the variablecalled product.

    Example

    function displaymessage(){alert("Hello World!")}

    If the line: alert("Hello world!!"), in the example above had not been written within afunction, it would have been executed as soon as the line was loaded. Now, the scriptis not executed before the user hits the button. We have added an onClick event to

    the button that will execute the function displaymessage() when the button isclicked.You will learn more about JavaScript events in the JS Events chapter.

  • 8/2/2019 Javascript Notes(2)

    24/54

    Example 2

    document.write("The function returned ", square(5), ".")

    All done.

    6. JAVASCRIPT OBJECTS6.1 Object TechnologyJavaScript is an Object based Programming (OOP) language. An OOP language allowsyou to define your own objects and make your own variable types.

    An object is just a special kind of data, with a collection of properties and methods.Let's illustrate with an example: A person is an object. Properties are the valuesassociated with the object. The persons' properties include name, height, weight,

    age, skin tone, eye color, etc. All persons have these properties, but the values ofthose properties will differ from person to person. Objects also have methods.Methods are the actions that can be performed on objects. The persons' methodscould be eat(), sleep(), work(), play(), etc.

    Properties

    The syntax for accessing a property of an object is:

    objName.propName

    You can add properties to an object by simply giving it a value. Assume that thepersonObj already exists - you can give it properties named firstname, lastname,age, and eyecolor as follows:

    personObj.firstname="John"personObj.lastname="Doe"personObj.age=30personObj.eyecolor="blue"document.write(personObj.firstname)

    The code above will generate the following output:

    John

    Methods

    An object can also contain methods.

    You can call a method with the following syntax:objName.methodName()

    Note: Parameters required for the method can be passed between the parentheses.To call a method called sleep() for the personObj:

  • 8/2/2019 Javascript Notes(2)

    25/54

    personObj.sleep()

    6.2 Built-in Objects

    Array Object

    JavaScript does not have an explicit array data type. However, you can use thepredefined Array object and its methods to work with arrays in your applications. TheArray object has methods for manipulating arrays in various ways, such as joining,reversing, and sorting them. It has a property for determining the array length andother properties for use with regular expressions.An arrayis an ordered set of values that you refer to with a name and an index. Forexample, you could have an array called emp that contains employees' namesindexed by their employee number. So emp[1] would be employee number one,emp[2] employee number two, and so on.

    Creating an Array

    To create an Array object:1. arrayObjectName = new Array(element0, element1, ..., elementN)2. arrayObjectName = new Array(arrayLength)arrayObjectName is either the name of a new object or a property of an existingobject. When using Array properties and methods, arrayObjectName is either thename of an existing Array object or a property of an existing object.element0, element1, ..., elementN is a list of values for the array's elements. Whenthis form is specified, the array is initialized with the specified values as its elements,and the array's length property is set to the number of arguments.arrayLength is the initial length of the array. The following code creates an array of

    five elements:billingMethod = new Array(5)Array literals are also Array objects; for example, the following literal is an Arrayobject. See "Array Literals" on page 37 for details on array literals.coffees = ["French Roast", "Columbian", "Kona"]

    Populating an Array

    You can populate an array by assigning values to its elements. For example,emp[1] = "Casey Jones"emp[2] = "Phil Lesh"emp[3] = "August West"

    You can also populate an array when you create it:myArray = new Array("Hello", myVar, 3.14159)

    Referring to Array Elements

    You refer to an array's elements by using the element's ordinal number. For example,suppose you define the following array:myArray = new Array("Wind","Rain","Fire")You then refer to the first element of the array as myArray[0] and the secondelement of the array as myArray[1].The index of the elements begins with zero (0), but the length of array (for example,myArray.length) reflects the number of elements in the array.

    Array Methods

    The Array object has the following methods:

    concat joins two arrays and returns a new array.

    http://research.nihonsoft.org/javascript/ClientGuideJS13/ident.html#1011655http://research.nihonsoft.org/javascript/ClientGuideJS13/ident.html#1011655
  • 8/2/2019 Javascript Notes(2)

    26/54

    join joins all elements of an array into a string.

    pop removes the last element from an array and returns that element.

    push adds one or more elements to the end of an array and returns that lastelement added.

    reverse transposes the elements of an array: the first array element becomes

    the last and the last becomes the first.

    shift removes the first element from an array and returns that element

    slice extracts a section of an array and returns a new array.

    splice adds and/or removes elements from an array.

    sort sorts the elements of an array.

    unshift adds one or more elements to the front of an array and returns the newlength of the array.

    For example, suppose you define the following array:myArray = new Array("Wind","Rain","Fire")myArray.join() returns "Wind,Rain,Fire"; myArray.reverse transposes the array so thatmyArray[0] is "Fire", myArray[1] is "Rain", and myArray[2] is "Wind". myArray.sortsorts the array so that myArray[0] is "Fire", myArray[1] is "Rain", and myArray[2] is"Wind".

    Two-Dimensional Arrays

    The following code creates a two-dimensional array.a = new Array(4)for (i=0; i < 4; i++) {

    a[i] = new Array(4)for (j=0; j < 4; j++) {

    a[i][j] = "["+i+","+j+"]"}

    }The following code displays the array:for (i=0; i < 4; i++) {

    str = "Row "+i+":"for (j=0; j < 4; j++) {

    str += a[i][j]

    }document.write(str,"

    ")}This example displays the following results:Row 0:[0,0][0,1][0,2][0,3]Row 1:[1,0][1,1][1,2][1,3]Row 2:[2,0][2,1][2,2][2,3]Row 3:[3,0][3,1][3,2][3,3]

    Arrays and Regular Expressions

    When an array is the result of a match between a regular expression and a string, the

    array returns properties and elements that provide information about the match. Anarray is the return value of regexp.exec, string.match, and string.replace. Forinformation on using arrays with regular expressions, see Chapter 4, "RegularExpressions."

    Boolean Object

    http://research.nihonsoft.org/javascript/ClientGuideJS13/regexp.html#1010922http://research.nihonsoft.org/javascript/ClientGuideJS13/regexp.html#1010922http://research.nihonsoft.org/javascript/ClientGuideJS13/regexp.html#1010922http://research.nihonsoft.org/javascript/ClientGuideJS13/regexp.html#1010922
  • 8/2/2019 Javascript Notes(2)

    27/54

    The Boolean object is a wrapper around the primitive Boolean data type. Use thefollowing syntax to create a Boolean object:booleanObjectName = new Boolean(value)Do not confuse the primitive Boolean values true and false with the true and falsevalues of the Boolean object. Any object whose value is not undefined or null,including a Boolean object whose value is false, evaluates to true when passed to aconditional statement. See "if...else Statement" on page 80 for more information.

    Date Object

    JavaScript does not have a date data type. However, you can use the Date object andits methods to work with dates and times in your applications. The Date object has alarge number of methods for setting, getting, and manipulating dates. It does nothave any properties.JavaScript handles dates similarly to Java. The two languages have many of the samedate methods, and both languages store dates as the number of milliseconds sinceJanuary 1, 1970, 00:00:00.The Date object range is -100,000,000 days to 100,000,000 days relative to 01January, 1970 UTC.

    To create a Date object:dateObjectName = new Date([parameters])where dateObjectName is the name of the Date object being created; it can be a newobject or a property of an existing object.The parameters in the preceding syntax can be any of the following:

    Nothing: creates today's date and time. For example, today = new Date().

    A string representing a date in the following form: "Month day, yearhours:minutes:seconds." For example, Xmas95 = new Date("December 25,1995 13:30:00"). If you omit hours, minutes, or seconds, the value will be setto zero.

    A set of integer values for year, month, and day. For example, Xmas95 = newDate(1995,11,25). A set of values for year, month, day, hour, minute, andseconds. For example, Xmas95 = new Date(1995,11,25,9,30,0).

    JavaScript 1.2 and earlier versions.The Date object behaves as follows:

    Dates prior to 1970 are not allowed.

    JavaScript depends on platform-specific date facilities and behavior; thebehavior of the Date object varies from platform to platform.

    Methods of the Date ObjectThe Date object methods for handling dates and times fall into these broadcategories:

    "set" methods, for setting date and time values in Date objects.

    "get" methods, for getting date and time values from Date objects.

    "to" methods, for returning string values from Date objects.

    parse and UTC methods, for parsing Date strings.

    With the "get" and "set" methods you can get and set seconds, minutes, hours, day

    of the month, day of the week, months, and years separately. There is a getDaymethod that returns the day of the week, but no corresponding setDay method,because the day of the week is set automatically. These methods use integers torepresent these values as follows:

    http://research.nihonsoft.org/javascript/ClientGuideJS13/stmtsov.html#1008323http://research.nihonsoft.org/javascript/ClientGuideJS13/stmtsov.html#1008323
  • 8/2/2019 Javascript Notes(2)

    28/54

    Seconds and minutes: 0 to 59

    Hours: 0 to 23

    Day: 0 (Sunday) to 6 (Saturday)

    Date: 1 to 31 (day of the month)

    Months: 0 (January) to 11 (December) Year: years since 1900

    For example, suppose you define the following date:Xmas95 = new Date("December 25, 1995")Then Xmas95.getMonth() returns 11, and Xmas95.getFullYear() returns 95.The getTime and setTime methods are useful for comparing dates. The getTimemethod returns the number of milliseconds since January 1, 1970, 00:00:00 for aDate object.For example, the following code displays the number of days left in the current year:today = new Date()

    endYear = new Date(1995,11,31,23,59,59,999) // Set day and monthendYear.setFullYear(today.getFullYear()) // Set year to this yearmsPerDay = 24 * 60 * 60 * 1000 // Number of milliseconds per daydaysLeft = (endYear.getTime() - today.getTime()) / msPerDaydaysLeft = Math.round(daysLeft) //returns days left in the yearThis example creates a Date object named today that contains today's date. It thencreates a Date object named endYear and sets the year to the current year. Then,using the number of milliseconds per day, it computes the number of days betweentoday and endYear, using getTime and rounding to a whole number of days.The parse method is useful for assigning values from date strings to existing Dateobjects. For example, the following code uses parse and setTime to assign a datevalue to the IPOdate object:IPOdate = new Date()IPOdate.setTime(Date.parse("Aug 9, 1995"))

    Using the Date Object: an Example

    In the following example, the function JSClock() returns the time in the format of adigital clock.function JSClock() {

    var time = new Date()var hour = time.getHours()

    var minute = time.getMinutes()var second = time.getSeconds()var temp = "" + ((hour > 12) ? hour - 12 : hour)temp += ((minute < 10) ? ":0" : ":") + minutetemp += ((second < 10) ? ":0" : ":") + secondtemp += (hour >= 12) ? " P.M." : " A.M."return temp

    }The JSClock function first creates a new Date object called time; since no argumentsare given, time is created with the current date and time. Then calls to the getHours,getMinutes, and getSeconds methods assign the value of the current hour, minute

    and seconds to hour, minute, and second.The next four statements build a string value based on the time. The first statementcreates a variable temp, assigning it a value using a conditional expression; if hour isgreater than 12, (hour - 13), otherwise simply hour.

  • 8/2/2019 Javascript Notes(2)

    29/54

    The next statement appends a minute value to temp. If the value of minute is lessthan 10, the conditional expression adds a string with a preceding zero; otherwise itadds a string with a demarcating colon. Then a statement appends a seconds valueto temp in the same way.Finally, a conditional expression appends "PM" to temp if hour is 12 or greater;otherwise, it appends "AM" to temp.

    Function Object

    The predefined Function object specifies a string of JavaScript code to be compiled asa function.To create a Function object:functionObjectName = new Function ([arg1, arg2, ... argn], functionBody)functionObjectName is the name of a variable or a property of an existing object. Itcan also be an object followed by a lowercase event handler name, such aswindow.onerror.arg1, arg2, ... argn are arguments to be used by the function as formal argumentnames. Each must be a string that corresponds to a valid JavaScript identifier; forexample "x" or "theForm".

    functionBody is a string specifying the JavaScript code to be compiled as the functionbody.Function objects are evaluated each time they are used. This is less efficient thandeclaring a function and calling it within your code, because declared functions arecompiled.In addition to defining functions as described here, you can also use the functionstatement. See the Client-Side JavaScript Reference for more information.The following code assigns a function to the variable setBGColor. This function setsthe current document's background color.var setBGColor = new Function("document.bgColor='antiquewhite'")To call the Function object, you can specify the variable name as if it were a function.The following code executes the function specified by the setBGColor variable:var colorChoice="antiquewhite"if (colorChoice=="antiquewhite") {setBGColor()}You can assign the function to an event handler in either of the following ways:1. document.form1.colorButton.onclick=setBGColor2.

    Creating the variable setBGColor shown above is similar to declaring the followingfunction:

    function setBGColor() {document.bgColor='antiquewhite'}You can nest a function within a function. The nested (inner) function is private to itscontaining (outer) function:

    The inner function can be accessed only from statements in the outer function.

    The inner function can use the arguments and variables of the outer function.The outer function cannot use the arguments and variables of the innerfunction.

    Math ObjectThe predefined Math object has properties and methods for mathematical constantsand functions. For example, the Math object's PI property has the value of pi(3.141...), which you would use in an application asMath.PI

    http://research.nihonsoft.org/devedge-srce/library/manuals/2000/javascript/1.3/reference/http://research.nihonsoft.org/devedge-srce/library/manuals/2000/javascript/1.3/reference/
  • 8/2/2019 Javascript Notes(2)

    30/54

    Similarly, standard mathematical functions are methods of Math. These includetrigonometric, logarithmic, exponential, and other functions. For example, if you wantto use the trigonometric function sine, you would writeMath.sin(1.56)Note that all trigonometric methods of Math take arguments in radians.The following table summarizes the Math object's methods.Table 7.1 Methods of Math

    Method Description

    Abs Absolute value

    sin, cos, tan Standard trigonometric functions; argumentin radians

    acos, asin,atan

    Inverse trigonometric functions; return valuesin radians

    exp, log Exponential and natural logarithm, base e

    Ceil Returns least integer greater than or equal toargument

    Floor Returns greatest integer less than or equal toargument

    min, max Returns greater or lesser (respectively) of twoarguments

    Pow Exponential; first argument is base, second isexponent

    Round Rounds argument to nearest integer

    Sqrt Square root

    Unlike many other objects, you never create a Math object of your own. You alwaysuse the predefined Math object.It is often convenient to use the with statement when a section of code uses severalmath constants and methods, so you don't have to type "Math" repeatedly. Forexample,with (Math) {

    a = PI * r*ry = r*sin(theta)x = r*cos(theta)

    }

    Number Object

    The Number object has properties for numerical constants, such as maximum value,not-a-number, and infinity. You cannot change the values of these properties and youuse them as follows:biggestNum = Number.MAX_VALUEsmallestNum = Number.MIN_VALUEinfiniteNum = Number.POSITIVE_INFINITYnegInfiniteNum = Number.NEGATIVE_INFINITYnotANum = Number.NaNYou always refer to a property of the predefined Number object as shown above, andnot as a property of a Number object you create yourself.

  • 8/2/2019 Javascript Notes(2)

    31/54

    The following table summarizes the Number object's properties.Table 7.2 Properties of Number

    Method Description

    MAX_VALUE The largest representable number

    MIN_VALUE The smallest representable number

    NaN Special "not a number" value

    NEGATIVE_INFINITY Special infinite value; returned onoverflow

    POSITIVE_INFINITY Special negative infinite value; returnedon overflow

    RegExp Object

    The RegExp object lets you work with regular expressions. It is described in Chapter4, "Regular Expressions."

    String Object

    The String object is a wrapper around the string primitive data type. Do not confuse astring literal with the String object. For example, the following code creates the stringliteral s1 and also the String object s2:s1 = "foo" //creates a string literal values2 = new String("foo") //creates a String objectYou can call any of the methods of the String object on a string literal value--JavaScript automatically converts the string literal to a temporary String object, calls

    the method, then discards the temporary String object. You can also use theString.length property with a string literal.You should use string literals unless you specifically need to use a String object,because String objects can have counterintuitive behavior. For example:s1 = "2 + 2" //creates a string literal values2 = new String("2 + 2")//creates a String objecteval(s1) //returns the number 4eval(s2) //returns the string "2 + 2"A String object has one property, length, that indicates the number of characters inthe string. For example, the following code assigns x the value 13, because "Hello,World!" has 13 characters:

    myString = "Hello, World!"x = mystring.lengthA String object has two types of methods: those that return a variation on the stringitself, such as substring and toUpperCase, and those that return an HTML-formattedversion of the string, such as bold and link.For example, using the previous example, both mystring.toUpperCase() and "hello,world!".toUpperCase() return the string "HELLO, WORLD!".The substring method takes two arguments and returns a subset of the stringbetween the two arguments. Using the previous example, mystring.substring(4, 9)returns the string "o, Wo." See the substring method of the String object in theClient-Side JavaScript Reference for more information.The String object also has a number of methods for automatic HTML formatting, suchas bold to create boldface text and link to create a hyperlink. For example, you couldcreate a hyperlink to a hypothetical URL with the link method as follows:mystring.link("http://www.helloworld.com")

    http://research.nihonsoft.org/javascript/ClientGuideJS13/regexp.html#1010922http://research.nihonsoft.org/javascript/ClientGuideJS13/regexp.html#1010922http://research.nihonsoft.org/devedge-srce/library/manuals/2000/javascript/1.3/reference/http://research.nihonsoft.org/javascript/ClientGuideJS13/regexp.html#1010922http://research.nihonsoft.org/javascript/ClientGuideJS13/regexp.html#1010922http://research.nihonsoft.org/devedge-srce/library/manuals/2000/javascript/1.3/reference/
  • 8/2/2019 Javascript Notes(2)

    32/54

    The following table summarizes the methods of String objects.Table 7.3 Methods of String

    Method Description

    anchor Creates HTML named anchor

    big, blink, bold,

    fixed, italics, small,strike, sub, sup

    Creates HTML formatted string

    charAt, charCodeAt Returns the character or character code at the specified positionin string

    indexOf,lastIndexOf

    Returns the position of specified substring in the string or lastposition of specified substring, respectively

    Link Creates HTML hyperlink

    concat Combines the text of two strings and returns a new string

    fromCharCode Constructs a string from the specified sequence of ISO-Latin-1codeset values

    Split Splits a String object into an array of strings by separating thestring into substrings

    Slice Extracts a section of an string and returns a new string.

    substring, substr Returns the specified subset of the string, either by specifying thestart and end indexes or the start index and a length

    match, replace,search

    Used to work with regular expressions

    toLowerCase,toUpperCase

    Returns the string in all lowercase or all uppercase, respectively

    6.3 JavaScript HTML DOM Objects

    In addition to the built-in JavaScript objects, you can also access and manipulate all

    of the HTML DOM objects with JavaScript.Navigator Object Hierarchy

    When you load a document in Navigator, it creates a number of JavaScript objectswith property values based on the HTML in the document and other pertinentinformation. These objects exist in a hierarchy that reflects the structure of the HTMLpage itself. The following figure illustrates this object hierarchy.

  • 8/2/2019 Javascript Notes(2)

    33/54

    In this hierarchy, an object's "descendants" are properties of the object. For example,a form named form1 is an object as well as a property of document, and is referredto as document.form1.

    Every page has the following objects:

    navigator: has properties for the name and version of Navigator being used,for the MIME types supported by the client, and for the plug-ins installed on theclient.

    window: the top-level object; has properties that apply to the entire window.Each "child window" in a frames document also has a window object.

    document: contains properties based on the content of the document, such astitle, background color, links, and forms.

    location: has properties based on the current URL.

    history: contains properties representing URLs the client has previouslyrequested.

    The Key Navigator Objects

    window and Frame Objects

    The window object is the "parent" object for all other objects in Navigator. You cancreate multiple windows in a JavaScript application. A Frame object is defined by theFRAME tag in a FRAMESET document. Frame objects have the same properties and

    methods as window objects and differ only in the way they are displayed.

    The window object has numerous useful methods, including the following:

  • 8/2/2019 Javascript Notes(2)

    34/54

    open and close: Opens and closes a browser window; you can specify the sizeof the window, its content, and whether it has a button bar, location field, andother "chrome" attributes.

    alert: Displays an Alert dialog box with a message.

    confirm: Displays a Confirm dialog box with OK and Cancel buttons.

    prompt: Displays a Prompt dialog box with a text field for entering a value.

    blur and focus: Removes focus from, or gives focus to a window.

    scrollTo: Scrolls a window to a specified coordinate.

    setInterval: Evaluates an expression or calls a function each time thespecified period elapses.

    setTimeout: Evaluates an expression or calls a function once after thespecified period elapses.

    Window also has several properties you can set, such as: Location: You can set location to redirect the client to another URL. Forexample, the following statement redirects the client to the Netscapehome page, as if the user had clicked a hyperlink or otherwise loaded theURL: location = http://home.netscape.com

    status: You can use the status property to set the message in the statusbar at the bottom of the client window

    Opening and Closing Windows

    A window is created automatically when you launch Navigator; you can open another

    window by choosing New then Navigator Window from the File menu. You can close awindow by choosing either Close or Exit from the File menu. You can also open andclose windows programmatically with JavaScript.

    Opening a Window

    You can create a window with the open method. The following statement creates awindow called msgWindow that displays the contents of the file sesame.html:msgWindow=window.open("sesame.html")The following statement creates a window called homeWindow that displays theNetscape home page:homeWindow=window.open("http://home.netscape.com")

    Windows can have two names. The following statement creates a window with twonames. The first name, msgWindow, is a variable that refers to the window object.This object has information on the window's properties, methods, and containership.When you create the window, you can also supply a second name, in this casedisplayWindow, to refer to that window as the target of a form submit or hypertextlink.msgWindow=window.open("sesame.html","displayWindow")A window name is not required when you create a window. But the window musthave a name if you want to refer to it from another window.When you open a window, you can specify attributes such as the window's heightand width and whether the window contains a toolbar, location field, or scrollbars.

    The following statement creates a window without a toolbar but with scrollbars:msgWindow=window.open

    ("sesame.html","displayWindow","toolbar=no,scrollbars=yes")

    Closing a Window

  • 8/2/2019 Javascript Notes(2)

    35/54

    You can close a window with the close method. You cannot close a frame withoutclosing the entire parent window.Each of the following statements closes the current window:window.close()self.close()close()Do not use the third form, close(), in an event handler. Because of how JavaScript

    figures out what object a method call refers to, inside an event handler it will get thewrong object.The following statement closes a window called msgWindow:msgWindow.close()

    Referring to Properties, Methods, and Event Handlers

    You can refer to the properties, methods, and event handlers of the current windowor another window (if the other window is named) using any of the followingtechniques:

    self or window: selfand window are synonyms for the current window, and youcan use them optionally to refer to the current window. For example, you canclose the current window by calling eitherwindow.close() orself.close().

    top or parent: top and parent are also synonyms that you can use in place ofthe window name. top can be used for any window; it refers to the topmostNavigator window. parent can be used for a frame; it refers to the framesetwindow that contains that frame. For example, for the frame frame1, thestatement parent.frame2.document.bgColor="teal" changes the backgroundcolor of the frame named frame2 to teal, where frame2 is a sibling frame in thecurrent frameset.

    The name of a window variable: The window variable is the variable specifiedwhen a window is opened. For example, msgWindow.close() closes a windowcalled msgWindow.

    Omit the window name: Because the existence of the current window is assumed,you do not have to refer to the name of the window when you call its methodsand assign its properties. For example, close() closes the current window.However, when you open or close a window within an event handler, you mustspecify window.open() or window.close() instead of simply using open() orclose(). Because of the scoping of static objects in JavaScript, a call to close()without specifying an object name is equivalent to document.close().

    document Object

    Each page has one document object.Because its write and writeln methods generate HTML, the document object is one ofthe most useful Navigator objects.

    The document object has a number of properties that reflect the colors of thebackground, text, and links in the page: bgColor, fgColor, linkColor, alinkColor, andvlinkColor. Other useful document properties include lastModified, the date thedocument was last modified, referrer, the previous URL the client visited, and URL,

    the URL of the document. The cookie property enables you to get and set cookievalues

    The document object is the ancestor for all the Anchor, Applet, Area, Form, Image,Layer, Link, and Plug-in objects in the page.

  • 8/2/2019 Javascript Notes(2)

    36/54

    Document Properties: an Example

    The properties of the document object are largely content-dependent. That is, theyare created based on the HTML in the document. For example, document has aproperty for each form and each anchor in the document.Suppose you create a page named simple.html that contains the following HTML:

    A Simple Documentfunction update(form) {

    alert("Form being updated")}Enter a value:

    Check if you want: Option #1

    Given the preceding HTML example, the basic objects might have properties likethose shown in the following table.

    Example object property values

    Property Value

    document.title "A Simple Document"

    document.fgColor

    #000000

    document.bgColor

    #ffffff

    location.href "http://www.royalairways.com/samples/simple.html"

    history.length 7

    Form Object

    Each form in a document creates a Form object. Because a document can containmore than one form, Form objects are stored in an array called forms. The first form(topmost in the page) is forms[0], the second forms[1], and so on. In addition toreferring to each form by name, you can refer to the first form in a document asdocument.forms[0]

  • 8/2/2019 Javascript Notes(2)

    37/54

    Likewise, the elements in a form, such as text fields, radio buttons, and so on, arestored in an elements array. You could refer to the first element (regardless of whatit is) in the first form asdocument.forms[0].elements[0]Each form element has a form property that is a reference to the element's parentform. This property is especially useful in event handlers, where you might need torefer to another element on the current form.

    In the following example, the form myForm contains a Text object and a button.When the user clicks the button, the value of the Text object is set to the form'sname. The button's onClick event handler uses this.form to refer to the parent form,myForm.

    Form name:

    location Object

    The location object has properties based on the current URL. For example, thehostname property is the server and domain name of the server hosting thedocument.The location object has two methods:

    reload forces a reload of the window's current document.

    replace loads the specified URL over the current history entry.

    history ObjectThe history object contains a list of strings representing the URLs the client hasvisited. You can access the current, next, and previous history entries by using thehistory object's current, next, and previous properties.

    You can access the other history values using the history array. This array containsan entry for each history entry in source order; each array entry is a string containinga URL.You can also redirect the client to any history entry by using the go method. Forexample, the following code loads the URL that is two entries back in the client's

    history list.history.go(-2)The following code reloads the current page:history.go(0)The history list is displayed in the Navigator Go menu.

    navigator Object

    The navigator object contains information about the version of Navigator in use. Forexample, the appName property specifies the name of the browser, and theappVersion property specifies version information for the Navigator.The navigator object has three methods:

    javaEnabled specifies whether Java is enabled

    preference lets you use a signed script to get or set various user preferences

    taintEnabled specifies whether data tainting is enabled (JavaScript 1.1 only)

  • 8/2/2019 Javascript Notes(2)

    38/54

    6.4 User-Defined Objects

    Most of the time you will be referencing objects that are built-in to the DOM.However, you may want to create your own objects for storing data within aJavaScript program.There are different ways to create a new object:

    1. Create a direct instance of an objectThe following code creates an instance of an object and adds four properties to it:

    personObj=new Object()personObj.firstname="John"personObj.lastname="Doe"personObj.age=50personObj.eyecolor="blue"

    Adding a method to the personObj is also simple. The following code adds a methodcalled eat() to the personObj:

    personObj.eat=eat

    2. Create a template of an objectThe template defines the structure of an object:

    function person(firstname,lastname,age,eyecolor){this.firstname=firstnamethis.lastname=lastnamethis.age=agethis.eyecolor=eyecolor}

    Notice that the template is just a function. Inside the function you need to assignthings to this.propertyName. The reason for all the "this" stuff in is that you're goingto have more than one person at a time (which person you're dealing with must beclear). That's what "this" is: the instance of the object at hand.Once you have the template, you can create new instances of the object, like this:

    myFather=new person("John","Doe",50,"blue")myMother=new person("Sally","Rally",48,"green")

    You can also add some methods to the person object. This is also done inside thetemplate:

    function person(firstname,lastname,age,eyecolor)

    {this.firstname=firstnamethis.lastname=lastnamethis.age=agethis.eyecolor=eyecolorthis.newlastname=newlastname}

    Note that methods are just functions attached to objects. Then we will have to writethe newlastname() function:

    function newlastname(new_lastname){this.lastname=new_lastname}

  • 8/2/2019 Javascript Notes(2)

    39/54

    The newlastname() function defines the person's new last name and assigns that tothe person. JavaScript knows which person you're talking about by using "this.". So,now you can write: myMother.newlastname("Doe").

    6.5 Object Manipulation Statements

    JavaScript uses the for...in and with statements to manipulate objects.

    for...in StatementThe for...in statement iterates a specified variable over all the properties of an object.For each distinct property, JavaScript executes the specified statements. A for...instatement looks as follows:for (variable in object) { statements }Example. The following function takes as its argument an object and the object'sname. It then iterates over all the object's properties and returns a string that liststhe property names and their values.function dump_props(obj, obj_name) {

    var result = ""for (var i in obj) {result += obj_name + "." + i + " = " + obj[i] + "
    "

    }result += ""return result

    }For an object car with properties make and model, result would be:car.make = Fordcar.model = Mustang

    with Statement

    The with statement establishes the default object for a set of statements. JavaScriptlooks up any unqualified names within the set of statements to determine if thenames are properties of the default object. If an unqualified name matches aproperty, then the property is used in the statement; otherwise, a local or globalvariable is used.A with statement looks as follows:with (object){ statements}Example. The following with statement specifies that the Math object is the default

    object. The statements following the with statement refer to the PI property and thecos and sin methods, without specifying an object. JavaScript assumes the Mathobject for these references.var a, x, yvar r=10with (Math) {

    a = PI * r * rx = r * cos(PI)y = r * sin(PI/2)

    }

  • 8/2/2019 Javascript Notes(2)

    40/54

    7. SCRIPTING EVENT HANDLERS

    7.1Events

    Events are actions that can be detected by JavaScript.

    By using JavaScript, we have the ability to create dynamic web pages. Events areactions that can be detected by JavaScript.

    Every element on a web page has certain events which can trigger JavaScriptfunctions. For example, we can use the onClick event of a button element to indicatethat a function will run when a user clicks on the button. We define the events in theHTML tags.Examples of events:

    A mouse click

    A web page or an image loading

    Mousing over a hot spot on the web page

    Selecting an input box in an HTML form

    Submitting an HTML form

    A keystroke

    The following table lists the events recognized by JavaScript:Note: Events are normally used in combination with functions, and the function willnot be executed before the event occurs!

    onload and onUnload

    The onload and onUnload events are triggered when the user enters or leaves thepage.The onload event is often used to check the visitor's browser type and browserversion, and load the proper version of the web page based on the information.Both the onload and onUnload events are also often used to deal with cookies thatshould be set when a user enters or leaves a page. For example, you could have apopup asking for the user's name upon his first arrival to your page. The name isthen stored in a cookie. Next time the visitor arrives at your page, you could haveanother popup saying something like: "Welcome John Doe!".

    onFocus, onBlur and onChange

    The onFocus, onBlur and onChange events are often used in combination withvalidation of form fields.Below is an example of how to use the onChange event. The checkEmail() functionwill be called whenever the user changes the content of the field:

    ;

    onSubmit

    The onSubmit event is used to validate ALL form fields before submitting it.

    Below is an example of how to use the onSubmit event. The checkForm() function willbe called when the user clicks the submit button in the form. If the field values arenot accepted, the submit should be cancelled. The function checkForm() returnseither true or false. If it returns true the form will be submitted, otherwise the submitwill be cancelled:

  • 8/2/2019 Javascript Notes(2)

    41/54

    onMouseOver and onMouseOut

    onMouseOver and onMouseOut are often used to create "animated" buttons.Below is an example of an onMouseOver event. An alert box appears when an

    onMouseOver event is detected:

    7.2 Event HandlersYou can define event handlers, such as onChange and onClick, to make your scriptreact to events.Each event is recognized by certain objects (HTML tags), summarized in the followingtable:

    Event Applies to Occurs whenEvent

    handler

    abort imagesUser aborts the loading of animage (for example by clicking alink or clicking the Stop button)

    onAbort

    blurwindows, frames, and allform elements

    User removes input focus fromwindow, frame, or form element

    onBlur

    click

    buttons, radio buttons,checkboxes, submitbuttons, reset buttons,links

    User clicks form element or link onClick

    changetext fields, textareas,select lists

    User changes value of element onChange

    error images, windowsThe loading of a document orimage causes an error

    onError

    focuswindows, frames, and allform elements

    User gives input focus towindow, frame, or form element

    onFocus

    load document bodyUser loads the page in theNavigator

    onLoad

    mouseout

    areas, linksUser moves mouse pointer outof an area (client-side imagemap) or link

    onMouseout

    mouseover

    links User moves mouse pointer overa link

    onMouse-Over

    reset forms User resets a form (clicks a onReset

  • 8/2/2019 Javascript Notes(2)

    42/54

    Reset button)

    select text fields, textareasUser selects form element'sinput field

    onSelect

    submit submit button User submits a form onSubmit

    unload document body User exits the page onUnload

    Example: using an event handler

    In the following example, you can enter an expression (for example, 2 + 2) in the firsttext field, and then click the button. The second text field then displays the value ofthe expression (for example, 4).

    Enter an expression:
    Result:The display in Navigator will look like this:

    Enter an expression:Result:

    Calling event handlers explicitly

    In JavaScript for Navigator 3.0, you can reset an event handler specified by HTML, asshown in the following example.

    function fun1() {

    ...

    }function fun2() {

    ...}

  • 8/2/2019 Javascript Notes(2)

    43/54

    document.myForm.myButton.onclick=fun2

    - Note that event handlers are function references, so you must assign fun2,not fun2() (the latter calls fun2 and has whatever type and value fun2returns).

    - Also, since the event handler HTML attributes are literal function bodies, youcannot use in the HTML source to make fun1 theonClick handler for an input; you must call fun1 instead, as in the example.

    - Finally, because JavaScript is case-sensitive, you must spell event handlernames in lowercase in JavaScript.

    8. JAVA SCRIPT ADVANCED TOPICS

    8.1 JavaScript Form Validation

    8.1.1 Introduction

    One of the most important uses of JavaScript is to validate form input to server-basedprograms such as LiveWire applications or CGI programs. This is useful because

    - It reduces load on the server. "Bad data" are already filtered out when input ispassed to the server-based program.

    - It reduces delays in case of user error. Validation otherwise has to beperformed on the server, so data must travel from client to server, be

    processed, and then returned to client for valid input.- It simplifies the server-based program.

    Generally, you'll want to validate input in (at least) two places:

    - As the user enters it, with an onChange event handler on each form elementthat you want validated.

    - When the user submits the form, with an onClick event handler on the buttonthat submits the form.

    JavaScript can be used to validate input data in HTML forms before sending off thecontent to a server.Form data that typically are checked by a JavaScript could be:

    has the user left required fields empty?

    has the user entered a valid e-mail address?

    has the user entered a valid date?

    has the user entered text in a numeric field?

    8.1.2 Required Fields

    The function below checks if a required field has been left empty. If the required fieldis blank, an alert box alerts a message and the function returns false. If a value isentered, the function returns true (means that data is OK):

    function validate_required(field,alerttxt)

  • 8/2/2019 Javascript Notes(2)

    44/54

    {with (field){if (value==null||value==""){alert(alerttxt);return false}

    else {return true}}

    }The entire script, with the HTML form could look something like this:

    function validate_required(field,alerttxt){with (field){if (value==null||value=="")

    {alert(alerttxt);return false}else {return true}}}function validate_form(thisform){with (thisform){if (validate_required(email,"Email must be filled out!")==false){email.focus();return false}

    }

    }Email:

    8.1.3 E-mail Validation

    The function below checks if the content has the general syntax of an email.This means that the input data must contain at least an @ sign and a dot (.). Also,the @ must not be the first character of the email address, and the last dot must atleast be one character after the @ sign:

    function validate_email(field,alerttxt)

    {with (field){apos=value.indexOf("@")dotpos=value.lastIndexOf(".")

  • 8/2/2019 Javascript Notes(2)

    45/54

    if (apos

  • 8/2/2019 Javascript Notes(2)

    46/54

    else if (parseInt(item.value) < min)alert("Please enter a " + item.name + " greater than " + min)

    else if (parseInt(item.value) > max)alert("Please enter a " + item.name + " less than " + max)

    elsereturnVal = true

    return returnVal

    }

    function validateAndSubmit(theform) {if (qty_check(theform.quantity, 0, 999)) {

    alert("Order has been Submitted")return trueelse {

    alert("Sorry, Order Cannot Be Submitted!")return false

    }}

    isaPosNum is a simple function that returns true if its argument is a positivenumber, and false otherwise.qty_checktakes three arguments: an object corresponding to the form elementbeing validated (item) and the minimum and maximum allowable values for the item(min and max). It checks that the value ofitem is a number between min and maxand displays an alert if it is not.validateAndSubmit takes a Form object as its argument; it uses qty_checktocheck the value of the form element and submits the form if the input value is valid.

    Otherwise, it displays an alert and does not submit the form.

    Using the validation functions

    In this example, the BODY of the document uses qty_checkas an onChange eventhandler for a text field and validateAndSubmit as the onClick event handler for abutton.

    How many widgets today?


    This form submits the values to a page in a LiveWire application called lwapp.html. Italso could be used to submit the form to a CGI program.

    8.2 Using JavaScript URLs

    You should be familiar with the standard types of URLS: http, ftp, file, and so on. WithNavigator you can also use URLs of type "javascript:" to execute JavaScriptstatements instead of loading a document. You simply use a string beginning with"javascript:" as the value for the HREF attribute of anchor tags. For example, you candefine a hyperlink as follows:

  • 8/2/2019 Javascript Notes(2)

    47/54

    Reload Nowto reload the current page when the user clicks it. In general, you can put anystatements or function calls after the "javascript:" URL prefix.You can use JavaScript URLs in many ways to add functionality to your applications.For example, you could increment a counterp1 in a parent frame whenever a userclicks a link, using the following function:function countJumps() {

    parent.p1++window.location=page1}To call the function, use a JavaScript URL in a standard HTML hyperlink:Page 1This example assumespage1 is a string representing a URL.If the value of the expression following a "javascript:" URL prefix evaluates toundefined, no new document is loaded. If the expression evaluates to a defined type,the value is converted to a string that specifies the source of the document to load.

    8.3 Using client-side image mapsA client-side image map is defined with the MAP tag. You can define areas within theimage that are hyperlinks to distinct URLs; the areas can be rectangles, circles, orpolygons.Instead of standard URLs, you can also use JavaScript URLs in client-side imagemaps, for example,

    8.5 Using server-side image maps

    Client-side image maps provide functionality to perform most tasks, but standard(sometimes called server-side) image maps provide even more flexibility. You specifya standard image map with the ISMAP attribute of an IMG tag that is a hyperlink. Forexample,

    The "about:logo" image is built in to Navigator and displays the Netscape

    logo.When you click an image with the ISMAP attribute, Navigator requests a URL of theformURL?x,ywhere URL is the document specified by the value of the HREF attribute, andxandyare the horizontal and vertical coordinates of the mouse pointer (in pixels from thetop-left of the image) when you clicked.Traditionally, image-map requests are sent to servers, and a CGI program performs adatabase lookup function. With Navigator JavaScript, however, you can perform thelookup on the client. You can use the search property of the location object to parsethexandycoordinates and perform an action accordingly. For example, supposeyou have a file named img.html with the following content:Click on the image

  • 8/2/2019 Javascript Notes(2)

    48/54

    str = location.searchif (str == "")

    document.write("

    No coordinates specified.")else {

    commaloc = str.indexOf(",") // the location of the comma

    document.write("

    The x value is " + str.substring(1, commaloc))document.write("

    The y value is " + str.substring(commaloc+1, str.length))}When you click a part of the image, Navigator reloads the page (because the HREFattribute specifies the same document), adding thexandycoordinates of themouse-click to the URL. The statements in the else clause then display thexandycoordinates. In practice, you could redirect to another page (by setting location) orperform some other action based on the values ofxandy.

    8.6 Using the status barYou can use two window properties, status and defaultStatus, to display messages inthe Navigator status bar at the bottom of the window. Navigator normally uses thestatus bar to display such messages as "Contacting Host..." and "Document: Done."The defaultStatus message appears when nothing else is in the status bar. Thestatus property displays a transient message in the status bar, such as when the usermoves the mouse pointer over a link.You can set these properties to display custom messages. For example, to display acustom message after the document has finished loading, simply set defaultStatus.For example,defaultStatus = "Some rise, some fall, some climb...to get to Terrapin"

    8.7 Creating hints with onMouseOver and onMouseOut

    By default, when you move the mouse pointer over a hyperlink, the status bardisplays the destination URL of the link. You can set status in the onMouseOut andonMouseOver event handlers of a hyperlink or image area to display hints in thestatus bar instead. The event handler must return true to set status. For example,Contents

    This example displays the hint "Click to display contents" in the status bar when youmove the mouse pointer over the link.

    8.8 Using cookies

    For a complete description of cookies, see Appendix D, "Netscapecookies.".

    Netscape cookies are a mechanism for storing persistent data on the client in a filecalled cookies.txt. Because HyperText Transport Protocol (HTTP) is a statelessprotocol, cookies provide a way to maintain information between client requests. This

    section discusses basic uses of cookies and illustrates with a simple example.Each cookie is a small item of information with an optional expiration date and isadded to the cookie file in the following format:name=value;expires=expDate;

    http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/cookies.htm#1002170http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/cookies.htm#1002170http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/cookies.htm#1002170http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/cookies.htm#1002170
  • 8/2/2019 Javascript Notes(2)

    49/54

    For more information on escape and unescape, see the topics in thereference section.

    name is the name of the datum being stored, and value is its value. Ifname andvalue contain any semicolon, comma, or blank (space) characters, you must use theescape function to encode them and the unescape function to decode them.expDate is the expiration date, in GMT date format:Wdy, DD-Mon-YY HH:MM:SS GMT

    Although it's slightly different from this format, the date string returned by the Datemethod toGMTString can be used to set cookie expiration dates.The expiration date is an optional parameter indicating how long to maintain thecookie. IfexpDate is not specified, the cookie expires when the user exits the currentNavigator session. Navigator maintains and retrieves a cookie only if its expirationdate has not yet passed.

    Limitations

    Cookies have these limitations

    Three hundred total cookies in the cookie file.

    4 Kbytes per cookie, for the sum of both the cookie's name and value.

    Twenty cookies per ser