Вы находитесь на странице: 1из 36

NETWORK COMPUTING (RT605)

Module 2
Dynamic HTML Pages Client side scripting - Java Script variables, Arithmetic operations message boxes, Arrays, control statements, functions, event handling, document object model. Dynamic updating of pages with JAVA Script. Embedding ActiveX controls - using the structured graphics ActiveX Control.

Introduction XHTML XHTML stands for EXtensible HyperText Markup Language XHTML is almost identical to HTML 4.01 XHTML is a stricter and cleaner version of HTML XHTML is a W3C Recommendation XHTML is a combination of HTML and XML (EXtensible Markup Language). XHTML elements must be properly nested XHTML elements must always be closed XHTML elements must be in lowercase XHTML documents must have one root element XHTML version used is XHTML 1.1 Filename extension used is .xhtml, .xht, .html

DHTML Dynamic HTML DHTML is NOT a language DHTML is a TERM describing the art of making dynamic and interactive web pages DHTML is a collection of technologies used together to create interactive and animated web sites by using a combination of a static markup language (such as HTML), a client-side scripting language (such as JavaScript), a presentation definition language (such as CSS), and the Document Object Model. DHTML combines HTML, JavaScript, the HTML DOM, and CSS. DHTML allows scripting languages to change variables in a web page's definition language, which in turn affects the look and function of the web page after loading or during the viewing process.
Module 2

Network Computing (SRP)

DHTML allows authors to add effects to their pages such as animated text and images. DHTML allows the use a form to capture user input, and then process and respond to that data. DHTML allows including rollover buttons or drop-down menus in the web page. DHTML enable scripts in documents to control the content, content position, and content appearance in response to user actions.

Eg: <html> <head> <title>The Dynamic Paragraph: DHTML Style</title> </head> <body> <h1 align=center>The Dynamic Paragraph</h1> <hr /> <p id=para1>This is a dynamic paragraph. </p> <form action=#> <input type=button value=Right onclick=para1.align='right'; /> <input type=button value=Left onclick=para1.align='left'; /> <input type=button value=Center onclick=para1.align='center'; /> </form> </body> </html> This simple example that moves the paragraph around the page by changing the align attribute of the paragraph tag through its corresponding align property.

Client Side Scripting DHTML supports client-side scripting of HTML documents and objects embedded within HTML documents. Client-side scripting generally refers to the class of computer programs on the web that are executed client-side, by the user's web browser. Scripts can be supplied in separate files or embedded directly within HTML documents in a manner independent of the scripting language. Scripts allow HTML forms to process input as it is entered: to ensure that values conform to specified patterns, to check consistency between fields and to compute derived fields. Scripts can also be used to simplify authoring of active documents. The behaviour of objects inserted into HTML documents can be tailored with scripts that respond to events generated by such objects. This enables authors to create compelling and powerful web content. HTML documents can include multiple script elements, which can be placed in the document HEAD or BODY.
Network Computing (SRP) Module 2

JAVASCRIPT Introduction JavaScript is the most popular scripting language on the internet. JavaScript was originally developed by Brendan Eich for Netscape Communications. The initial name was Mocha, which was later renamed to LiveScript. It was renamed JavaScript in a joint announcement with Sun Microsystems in September 1995, when it was deployed in the Netscape browser version 2.0B3. JavaScript is used in millions of Web pages to add functionality, validate forms, detect browsers, and much more. JavaScript is an implementation of the ECMA Script language standard and is typically used to enable programmatic access to computational objects within a host environment. It can be characterized as a prototype-based object-oriented scripting language that is dynamic, weakly typed and has first-class functions. It is also considered a functional programming language like Scheme and OCaml because it has closures and supports higher-order functions. JavaScript is primarily used in the form of client-side JavaScript, implemented as part of a web browser in order to provide enhanced user interfaces and dynamic websites. JavaScript uses syntax influenced by that of C syntax, also JavaScript copies many Java programming language names and naming conventions, but the two languages are otherwise unrelated and have very different semantics. JavaScript is supported by all major browsers such as Internet Explorer, Firefox and Chrome. It is commonly used in tasks ranging from the validation of form data to the creation of complex user interfaces. It can be used to manipulate the very markup in the documents in which it is contained. It adds interactivity to HTML pages.

Designed by Developed by Filename extension Internet media type Type of format Paradigm Influenced by Influenced Version License

Brendan Eich Netscape Communications Corporation, Mozilla Foundation .js text/java script, application/java script Scripting language Multi-paradigm: prototype-based, functional, imperative, scripting C, Java, Self, Scheme, Perl, Python, JScript 1.8.2 Free

Advantages of JavaScript 1. Interpreted Language


Network Computing (SRP) Module 2

JavaScript is a lightweight interpreted language, which requires no compilation steps. This provides an easy development process. The syntax is completely interpreted by the browser just as it interprets HTML tags. 2. Embedded within HTML JavaScript does not require any special or separate editor for programs to be written, edited or compiled. It can be written in any text editor like Notepad, along with appropriate HTML tags, and saved as filename.html. HTML files with embedded JavaScript commands can then be read and interpreted by any browser that is JavaScript enabled. 3. Platform Independent JavaScript is a programming language that is completely independent of the hardware on which it works. It is a language that is understood by any JavaScript enabled browser. JavaScript applications work on any machine in the network. JavaScript typically relies on a run-time environment in a web browser) to provide objects and methods by which scripts can interact with the outside world. 4. Structured JavaScript supports all the structured programming syntax in C (e.g., if statements, while loops, switch statements, etc.). JavaScript also supports regular expressions in a manner similar to Perl, which provide a concise and powerful syntax for text manipulation. 5. Dynamic JavaScript is a dynamic and loosely typed language. As in most scripting languages, types are associated with values, not with variables. For example, a variable x could be bound to a number, and then later rebound to a string. It supports run-time evaluation. 6. Functional JavaScript provides first class functions. As such, they have properties and methods. They can be assigned to variables, passed as arguments. JavaScript allows 'inner' or 'nested' functions (functions defined within another function). 7. Object Based JavaScript is an object oriented scripting language. JavaScript is almost entirely object-based. JavaScript objects are associative arrays, augmented with prototypes. JavaScript uses prototypes instead of classes for inheritance. Properties and their values can be added, changed, or deleted at run-time. Most properties of an object can be enumerated using a for...in loop. 8. Minimal Syntax JavaScript applications can be built using just a few commands and simple rules of syntax. 9. Quick Development JavaScript does not require time-consuming compilations. It can be developed in a short period of time using minimal code. 10. Designed for simple small programs It is well suited to implement simple small programs. Such programs can be easily written and executed at an acceptable speed. They can be easily integrated into a web page.
Network Computing (SRP) Module 2

11. Performance JavaScript can be written such that the HTML files are fairly compact and quite small. This minimizes the storage requirements on the web server and downloads time for the client. 12. User Events JavaScript supports Object / Event based programming. JavaScript recognizes when a form event occurs. This event can have suitable JavaScript code attached, which will execute when the event occurs or user action takes place.

JavaScript can be useful in: 1. Making our Web page to respond or react directly to user interaction with form elements (input fields, text areas, buttons, radio buttons, checkboxes, selection lists) and hypertext links. 2. Distributing small collections of database-like information and providing a friendly interface to that data. 3. Controlling multiple-frame navigation, plug-ins, or Java applets based on user choices in the HTML document. 4. Pre processing data on the client before submission to a server. 5. Changing content and styles in modern browsers dynamically and instantly in response to user interaction.

Writing JavaScript in HTML JavaScript syntax is embedded into an HTML file. A browser reads HTML files and interprets HTML tags. The primary way to include scripts written in any language in a Web page is through the use of the <script> tag. JavaScript code can be associated with an HTML document in the following ways: 1. Within a <script> tag. 2. As a linked .js file indicated by the src attribute of a <script> tag. <script src=url type= text/javascript > 3. Within an event handler attribute such as onclick.

The <script> tag <script> </script>

Network Computing (SRP)

Module 2

The HTML <script> tag is used to insert a JavaScript into an HTML page. Inside the <script> tag we use the type attribute to define the scripting language. So, the <script type=text/javascript> and </script> tells where the JavaScript starts and ends. A script-aware browser assumes that all text within the <script> tag is to be interpreted as some form of scripting language; by default this is generally JavaScript. It is possible for the browser to support other scripting languages such as VBScript. Within the element should be scripting statements in the particular language used. Any script code is executed by the browser and the results are then output to the document. The <script> tag can occur in either the head or the body elements numerous times. Syntax: <script type=text/javascript > . . . JavaScript code snippet . . . </script> OR <script language=JavaScript> . . . JavaScript code snippet . . . </script> OR <script type= text/javascript src=url >

Eg:

<html> <head> <title>First JavaScript Example</title> <script type=text/javascript> document.write (Hello user! Welcome to JavaScript.); // JavaScript comment </script> </head> <body> <h1>First JavaScript Example</h1> </body> </html>

The document.write command is a standard JavaScript command for writing output to a page. By entering the document.write command between the <script> and </script> tags, the browser will recognize it as a JavaScript command and execute the code line.
Network Computing (SRP) Module 2

Eg:

<script src=/scripts/myscript.js type=text/javascript> </script>

We can place the script code in a separate file with a .js extension and use the src attribute to specify the URL of the script to include. The url contains the relative path and the filename.js. This is also called a linked script. Script in the <head>

The <head> </head> tags make an ideal location to place the <script> element. This is due to the sequential nature of Web documents. The browser interprets the contents of the <head> first. The JavaScript programs may be processed or executed before the <body> section. Very often scripts within the <head> of a document are used to define variables or functions that may be used later on in the document. JavaScript Statements The JavaScript lines of code written within the <script> tags are known as JavaScript statements. They are instructions to the interpreter to carry out specific actions. Curly braces ({ }) are used to group a list of statements together forming a statement block. These statements use a semi colon (;) as the statement terminator. The JavaScript statements are used to define or initialize a variable, assign a value, modify a value, invoke an objects method, invoke a function or make a decision. Eg: document.write (Hello user! Welcome to JavaScript.); JavaScript Comments Comments can be added to explain the JavaScript, or to make the code more readable. Single line comments start with //. Multi line comments start with /* and end with */. Eg: document.write(Hello user! Welcome to JavaScript.); Special Characters In JavaScript we can add special characters to a text string by using the backslash ( \ ) sign. The backslash in a string is an escape character. It indicates that the following character is a special character. This character is combined with the backslash to form an escape sequence. Escape Sequence \' \" \\ \n \r \t \b Variables JavaScript variables are used to store values that can be used in other parts of a program. They can be considered as containers in computer memory that hold information. Each variable has a name, type and value. 7 Outputs single quote double quote backslash new line carriage return tab backspace // write it to HTML page.

Network Computing (SRP)

Module 2

The name is called the identifier via which it can be referenced later. A variable can have a short name, like x, or a more descriptive name, like carname. Variable names are case sensitive (x and X are two different variables). Variable names must begin with a letter or the underscore character. The type refers to the data type of the value it holds. The value is the data stored in the variable.

Declaring / Creating Variables The var keyword is used to declare JavaScript variables. Declaring a variable tells JavaScript that a variable of a given name exists so that the interpreter can understand references to that variable name throughout the program. The variables are commonly declared in the head section of an HTML document. It allows the use of the variable later in the document. We can also assign values to the variables when we declare them. Syntax: var <variable_name>; var <variable_name> = value; Eg: var x; var x = 5 ; var carname = BENZ ; Assigning values to undeclared variables causes JavaScript to automatically declare that variable. Eg: x = 10; has the same effect as var x = 10;

Data Types and Literals JavaScript does not allow the data type of the variable to be declared when it is created. The same variable may be used to hold different types of data at different times in a program. Literals are fixed values which literally provide a value in a program. In JavaScript variables are loosely cast. The type of the variable is implicitly defined based on the literal values that are assigned to it. JavaScript supports 4 primitive types of values: 1. Number : Consists of integers, floating point numbers and NaN (Not a Number) value. 2. Boolean : Consists of the logical value true and false. Values 1 and 0 are not considered as Boolean values in JavaScript. 3. String : Consists of string values that are enclosed in single or double quotes. If it begins with double quotes then it should end with double quotes and vice versa. Eg: Cars Bikes 4. Null : Consists of a single value null, which identifies a null, empty or non-existent reference. Operators An operator is used to transform one or more values into a single resultant value. The values to which the operator is applied are referred to as operands. A combination of an operator and its operands is referred to as an expression. Expressions are evaluated to determine the value of the expression.
Network Computing (SRP) Module 2

An operator requiring a single operand is called a Unary operator and that requires two operands is called a Binary operator. An operator having three operands is called a Ternary operator and so on. JavaScript supports the following operators: 1. Arithmetic Operators 2. Assignment Operators 3. Logical Operators 4. Comparison Operators 5. String Operator 6. Conditional Operator 7. Special Operators

Arithmetic Operators Arithmetic operators are used to perform arithmetic between variables and/or values. Operator Description Addition Subtraction Multiplication Division Modulus (division remainder) Increment Decrement Example (y=5) x=y+2 x=y-2 x=y*2 x=y/2 x=y%2 x=++y x=y++ x=--y x=y-x=7 x=3 x=10 x=2.5 x=1 x=6 x=5 x=4 x=5 Result y=5 y=5 y=5 y=5 y=5 y=6 y=6 y=4 y=4

+ * / % ++ --

Assignment Operators Assignment operators are used to assign values or update values of JavaScript variables. Some assignment operators are combined with other operators to perform a computation and then update the variable with the new value. Operator Description Assignment: Sets the variable on the left of the = operator to the value on its right. Addition: Increments the variable on the left of the operator by the value on its right. Subtraction: Decrements the variable on the left of the operator by the value on its right. Multiplication: Multiplies the variable on
Module 2

Eg: (x=10, y=5) x=y x+=y x-=y x*=y

Same as

Result x=5

= += -= *=

x=x+y x=x-y x=x*y

x=15 x=5 x=50 9

Network Computing (SRP)

/= %=

the left of the operator by the value on its right. Division: Divides the variable on the left of the operator by the value on its right. Modulus: Takes the modulus of the variable on the left of the operator using the value on its right.

x/=y x%=y

x=x/y x=x%y

x=2 x=0

Logical Operators Logical operators are used to determine the logic between variables or values. They are used to perform Boolean operations. Operator Description Logical AND Logical OR Logical NOT Example (x=6, y=3) (x < 10 && y > 1) is true (x= =4 || y= =5) is false !(x= =y) is true

&& || !

Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. Operator Description is equal to is strictly equal to (value and type) is not equal is strictly not equal to (value and type) is less than is greater than is less than or equal to is greater than or equal to Example (x=5) x==8 is false x===5 is true x===5 is false x!=8 is true x!==5 is false x<8 is true x>8 is false x<=8 is true x>=8 is false

== === != !== < > <= >=

String Operator The string operator is used to perform operations on string. JavaScript supports the string concatenation ( + ) operator. The + operator can be used to join two string variables or text values together. Eg: txt1=Good ; txt2=Morning; txt3=txt1+txt2;
Network Computing (SRP) Module 2

10

After the execution of the statements above: txt3=Good Morning

Conditional Operator JavaScript supports the conditional expression operator. It is a ternary operator. It takes 3 operands; a condition to be evaluated and 2 alternative values to be returned based on the truth and falsity of the condition. Syntax: variablename = ( condition ) ? value 1: value 2 (If the condition is true, value 1 is the result of the expression, otherwise value 2 is the result of the expression) Eg: greeting = (visitor==PRES)? Dear President : Dear ; (If the variable visitor has the value of PRES, then the variable greeting will be assigned the value Dear President else it will be assigned Dear.)

Special Operators JavaScript supports a number of special operators. new operator: The new operator is used to create an instance of an object type. Eg: myArray = new Array(); delete operator: The delete operator is used to delete a property of an object or an element at an array index. Eg: delete myArray[5]; void operator: The void operator does not return a value. It is typically used to return a URL with no value.

Arrays An array is an ordered set of values grouped together under a single identifier. It is a data structure consisting of related data or a collection of data items. Array object is used to store multiple values in a single variable. It may contain primitive types like numbers, strings, Booleans, undefined values, and null values, and even other composite types. The members of an array are called elements. The values are stored in indexed locations within the array. JavaScript arrays are dynamic entities in that they can change size after they are created. The individual elements of the array are accessed by using the name of the array followed by the index value of the array element enclosed in square [] brackets. 11

Network Computing (SRP)

Module 2

The index value is also known as position number or subscript. It must be an integer or an integer expression. The length of an array is the number of elements that an array contains. The array element index starts with 0. The last array element index number is one less than the length of the array. An array must be declared before it is used.

Declaring and Allocating Arrays Arrays occupy space in memory. The operator new is used for dynamically allocating memory for the array. This process is called creating an instance or instantiating the object. JavaScript automatically resizes the array when new array elements are initialized. Syntax: var arrayName = new Array(); var arrayName = new Array(ArrayLength); Eg: var myCars = new Array(); var myCars = new Array(5);

To assign or modify values we can reference the array using the array name and the index value. myCars[0] = BMW; myCars[1] = Benz; myCars[2] = Volvo; To access an array, we can reference the array using the array name and the index value. document.write(myCars[0]; Dense Arrays Array created with each of its elements being assigned a specific value and a specific position. These arrays are declared and initialized at the same time. Listing the values of the array elements in the array declaration creates dense arrays. Eg: var arrayName = new Array(value0, value1, value2, . . . value n); ( Length of the array is n+1 ) Literal Arrays Array created with each of its elements being assigned literal values. Eg: var myCars = [Saab, Volvo, BMW]; var myCars = [BMW,5,true,Benz];

Network Computing (SRP)

Module 2

12

Properties Properties are the values associated with an object. We can read and set these properties to display or modify its values. It can be referenced by using the array name ( arrayname.propertyname). Length Property : It retrieves the index of the next available position at the end of the array. It sets or returns the number of elements in an array. Eg: myCars[100]=Tata; myCars.length; myCars.length will return a value 101. Methods Methods are the actions that can be performed on objects. JavaScript provides some in built methods to modify the values of the array object. concat() Combines 2 or more arrays and returns the copy of joined array. myBus.concat(myCars); join() Joins all the elements of the array into a single string. myCars.join(:); reverse() Reverses the order of the elements in the array. myCars.reverse(); sort() Sorts the elements of the array. String sort is applied by default. myCars.sort();

Message Boxes / Dialog Boxes / Pop up Boxes JavaScript uses dialog boxes to display small amount of data to the user or pick up user input. These appear as separate windows and their content depends on the information provided by the user. The content is independent of the text in the HTML page. It does not affect the contents in the HTML page. The browser has to allow running of scripts for the dialog boxes to work properly. JavaScript provides 3 types of dialog boxes: 1. Alert Box 2. Prompt Box 3. Confirm Box
Network Computing (SRP) Module 2

13

1. Alert Box Alert Box is used to direct small amounts of textual output to a browsers window. The JavaScript alert( ) method takes a string as an argument and displays an alert dialog box in the browser window, when invoked by appropriate JavaScript. It can be very useful in form validation process to warn the user or give additional information. Syntax: Eg: alert(<Message>); alert(Welcome);

The alert dialog box displays the string passed to the alert() method, as well as an OK button. The processing of the program will not continue until the user action is received i.e. either the OK button is clicked or the user closes the dialog box.

2. Prompt Box JavaScript provides a prompt dialog box which displays a specified message. In addition, it provides a single entry field which accepts user input. The prompt( ) method is used to display prompt boxes. It instantiates the prompt dialog box, displays a predefined message, displays a text box to accept user input, displays the OK and Cancel buttons. The prompt dialog box causes the program to halt until user action takes place. Syntax: Eg: prompt(<Message>,<Default value>); var col = prompt(Enter a color:,blue);

Clicking on OK button causes the text (default or user typed ) inside the textbox to be passed to the program environment. Clicking on the Cancel button causes a NULL value to be passed to the program environment.
Module 2

Network Computing (SRP)

14

3. Confirm Box The confirm dialog box serves as a technique for confirming user action. A confirm box is often used if we want the user to verify or accept something. The confirm( ) method is used to instantiate a confirm box. It accepts a string as argument, which is displayed in the confirm box. It also displays an OK button and a Cancel button. The confirm dialog box causes the program to halt until user action takes place. If the user clicks OK, the box returns true. If the user clicks Cancel, the box returns false. Syntax: Eg: confirm(<Message>); confirm(Are you sure?); if(confirm(Are you sure?)) { document.write(Yes); } else { document.write(No); }

Control Statements / Structures JavaScript supports a common set of basic programming constructs. These are used to dictate the program control. Program control refers to specifying the order in which statements are to be executed in a program. It allows the programmer to transfer control based on certain conditions. The statements may not be executed in a sequential order. It allows the selective execution of code in a program. 1. if Statement The if selection statement is used to make a decision based on a condition and transfer the program control accordingly. if is a single selection structure because it selects or ignores a single action or single group of actions. A decision can be made on any expression that evaluates to a value of JavaScripts Boolean type, i.e true or false. Program execution depends on the value returned by
Network Computing (SRP) Module 2

15

the condition or expression. If the value returned is true, the statement or block of statements inside the if block executes. If the value returned is false, the program skips that portion and control is transferred to the next immediate section. Syntax: if(expression) { statement or block of statements; } Eg: if(x > y) { alert(x is greater than y); }

2. if . . . else Statement The if . . . else statement is a double selection structure because it selects between 2 different actions or groups. The decision is based on the value returned by the expression. If the value returned is true, the statement or block of statements inside the if block executes. If the value returned is false, the statement or block of statements inside the else block executes. The program control is then transferred to the next immediate section. Syntax: if(expression) { statement or block of statements; } else { statement or block of statements; } Eg: if(x > y) { alert(x is greater than y); } else { alert(y is greater than x);
Network Computing (SRP) Module 2

16

3. if . . .else if . . . else Statement The if...else if....else statement is used to select one of many blocks of code to be executed. The if statement is executed based on the value of the expression. If the value returned is true, the statement or block of statements inside the if block executes. If the value returned is false, the control moves to the next if statement. The expression is evaluated and the above step is repeated. If all the expressions evaluate to false, the statement or block of statements inside the final else block executes. Syntax: if(expression) { statement or block of statements; } else if(expression) { statement or block of statements; } else { statement or block of statements; }

Eg:

if(x > y) { alert(x is greater than y); } else if (y > x) { alert(y is greater than x); } else { alert(x is equal to y);

Network Computing (SRP)

Module 2

17

4. switch Statement The switch is a multiple selection structure because it selects among multiple actions or groups. It is used to select one of many blocks of code to be executed. The variable or expression is tested separately for each of the values it may assume. Different actions are taken for each value. The switch statement consists of a series of case labels and an optional default case. When the flow of control reaches the switch statement, the script evaluates the controlling expression in the parentheses. The value of this expression is compared with the value in each of the case labels, starting with the first case label. If the comparison evaluates to true, the statement or block of statements in that case is executed. The break statement is used as the last statement in each case to exit the switch statement immediately. It is not required for the last case. The default case allows us to specify a set of statements to execute if no other case is matched. It is usually written as the last case in the switch statement. Syntax: switch(expression) { case condition 1: statement; break; case condition 2: statement; break; ...... case condition n: statement; break; default: } statement;

Eg:

var x=3; switch (x) { case 1: alert(x is 1); break; case 2: alert(x is 2); break; case 3: alert(x is 3); break;

Network Computing (SRP)

Module 2

18

case 4: alert(x is 4); break; default: alert(x is not 1, 2, 3 or 4); } 5. for loop Loops execute a block of code a specified number of times, or while a specified condition is true. The for loop is used to cycle through a sequence of statements or block of code for a number of times. It iterates a specific number of times as specified. The for statement takes 3 expressions: an initialization, a condition and an iteration statement / expression. Each of these are separated by a semi colon (;). The initialization, loop-continuation condition and increment portions of a for statement can contain constants or arithmetic expressions. The loop exits when the specified condition is satisfied. The control flow is transferred to the next section of the program. Syntax: for (initialization; test condition; iteration statement) { loop statements or block; } Eg: for (var i = 0; i < 3; i++) { document.write (Loop: + i + <br />); }

6. while loop While loops execute a block of code a specified number of times, or while a specified condition is true. The while loop is used to cycle through a sequence of statements or block of code until a specified condition is true. If the condition or expression evaluates to true, the loop continues. If the condition is false, the loop terminates and execution continues from the first statement after the loop body. Syntax: while(condition) { loop statements or block; } Eg: var count = 0; while(count < 4) { document.write (Count= + count + <br />);
Network Computing (SRP) Module 2

19

count ++; }

7. do . . . while loop The do - while is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once (unless a break is encountered first). The loop continuation condition is tested after the body of the loop is executed. Syntax: do { loop statements or block; } while (condition); Eg: var count = 0; do { document.write (Count= + count + <br />); count ++; } while (count < 4);

8. break Statement The break statement can be used to more precisely control the execution of a loop. The break statement is used to exit a loop early, breaking out of the enclosing curly braces. The program continues from the next statement after the loop or control structure. Syntax: break; Eg: Code var x = 1; while(x < 10) { x = x + 1;
Network Computing (SRP) Module 2

Output

x=2 x=3

20

if(x == 4) { break; } document.write(x = + x + <br>); }

9. continue Statement The continue statement can be used to control the execution of a loop. The continue statement tells the interpreter to immediately start the next iteration of the loop. When its encountered, program flow will move to the loop check expression immediately. In while loop, the loop continuation test is evaluated immediately after this statement. In for loop the increment expression executes, then the condition is checked. Syntax: continue; Eg: Code var x = 1; while(x < 10) { x = x + 1; if(x == 4) { continue; } document.write(x = + x + <br>); } x=2 x=3 x=5 x=6 x=7 x=8 x=9 x = 10 Output

10. Labeled break A label can be used with the break statement to direct flow control more precisely. A label is simply an identifier followed by a colon that is applied to a statement or block of code. The labeled break statement is used to break out of a nested control structure. This statement, when executed in for / while / other loops, causes immediate exit from that statement and any number of enclosing
Network Computing (SRP) Module 2

21

repetition statements. The program execution resumes with the first statement after the specified labeled statement (statement preceded by a label). Eg: Code document.write(Labeled Break+<br>); outerloop: for (var i = 0; i < 3; i++) { document.write(Outerloop: + i + <br />); for (var j = 0; j < 5; j++) { if (j == 3) break outerloop; document.write(Innerloop: + j +<br />); } } document.write(All loops done+<br />); Output Labeled Break Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 All loops done

11. Labeled continue A label can be used with the continue statement to direct flow control more precisely. A label is simply an identifier followed by a colon that is applied to a statement or block of code. The labeled continue statement will cause flow control to resume at the loop indicated by the label. When the interpreter encounters a labeled continue, it skips the remaining statements in the structures body and returns to the iteration of the labeled loop. Eg: Code document.write(Labeled Continue+<br>); outerloop: for (var i = 0; i < 3; i++) { Output Labeled Continue Outerloop: 0 Innerloop: 0 Innerloop: 1 22

Network Computing (SRP)

Module 2

document.write(Outerloop: + i + <br />); for (var j = 0; j < 5; j++) { if (j == 3) continue outerloop; document.write(Innerloop: + j + <br />); } } document.write(All loops done+<br />);

Innerloop: 2 Outerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Outerloop: 2 Innerloop: 0 Innerloop: 1 Innerloop: 2 All loops done

12. for . . . in Statement The for...in statement loops through the elements of an array or through the properties of an object. The code in the body of the for...in loop is executed once for each element/property. The variable argument can be a named variable, an array element, or a property of an object. The execution stops when it reaches the end of the array or list of properties. Syntax: for (variablename in object) { statement or block to execute; }

Eg:

var x; var myCars = [Saab, Volvo, BMW]; for (x in myCars) { document.write(myCars[x] + <br />); }

13. with Statement JavaScripts with statement allows programmers to use a shorthand notation when referencing objects. Normally to write to an HTML document, we would use the write() method of the Document object. The with statement indicates an object that will be used implicitly inside the statement body. Eg: with (document)
Module 2

Network Computing (SRP)

23

{ write(Hello from JavaScript); write(<br />); write(You can write what you like here); }

Functions JavaScript functions are blocks of JavaScript code that perform a specific task and often return a value. JavaScript functions can be used to create script fragments that can be used over and over again. A function may take 0 or more parameters. A function will be executed by an event or by a call to the function. JavaScript supports all the features necessary to write modular code using functions and even supports some advanced features, such as variable parameter lists. It helps to develop and maintain large programs from simple pieces or modules. 1. Built-in Functions 2. User Defined Functions 1. Built-in Functions JavaScript provides several built-in functions that can be used to perform many common tasks such as explicit type conversions. Commonly used functions are: eval() The eval() function can be used to convert a string expression to a numeric value. Eg: var total = eval(10 * 10 + 5); parseInt() The parseInt() function is used to convert a string value to an integer. It returns the first integer contained in the string. It returns NaN (Not a Number) if the string does not contain any number. Eg: var num = parseInt(123xyz); var num= parseInt(xyz); parseFloat() The parseFloat() function is used to convert a string value to a floating point number. It returns the first floating point number contained in the string. It returns NaN (Not a Number) if the string does not contain any number. Eg: var num = parseFloat(1.2xy3z); var num= parseFloat(xyz); // The value 1.2 will be assigned to num. // The value NaN will be assigned to num. // The value 123 will be assigned to num. // The value NaN will be assigned to num. // The value 105 will be assigned to total

User Defined Function


Network Computing (SRP) Module 2

24

Functions offer the ability to group JavaScript code that performs a specific task into a single unit or module. It can be used repeatedly whenever required in the program. We define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. A function may take 0 or more parameters. Parameters are a standard technique via which control data can be passed to function. Control data passed to a function offers a means to control what a function returns. A user defined function has to be declared and coded before it can be used. The function can be invoked by calling it using the function name. Function can accept information in the form of arguments and return results. Declaring Functions Functions are declared and created using the function keyword. It contains: A name for the function. A list of parameters (arguments) that will accept values passed to the function when called. A block of JavaScript code that defines what the function does. Syntax: function function_name ( parameter 1, parameter 2, . . .) { // Block of JavaScript Code } The function name is case sensitive and should be a valid identifier. It cannot be a reserved keyword of JavaScript. It should start with a letter and can contain underscores (_). White spaces are not allowed. The list of parameters passed to the function appears in parentheses and the members of the list are separated by commas (,). Eg: function printName (user) { document.write(Your name is); document.write(user); document.write(<br>); } Functions can be defined both in the <head> and in the <body> section of a document. , to assure that a function is read/loaded by the browser before it is called, it could be wise to put functions in the <head> section. This ensures that all functions will be parsed before they are invoked or called. If the function is called before it is declared and parsed, it will lead to an error. The browser will not be able to understand that the function exists. Passing Parameters (Arguments) Values can be passed to a function as parameters or arguments. They are passed to the function by listing them in the parentheses following the function name. Multiple values can be passed, separated by commas provided that the function has been declared accordingly. A function may take 0 or more parameters. Parameters are a standard technique via which control data can be
Network Computing (SRP) Module 2

25

passed to function. Control data passed to a function offers a means to control what a function returns. The parameters are processed inside the function and the values are returned. The number of values passed is fixed when the function is declared. In the above example, the function printName has a single parameter which is user. Within the function, reference to user will then refer to the value passed to the function. Function Call (Invoke) The function is called or invoked by using the function name, list of parameters in parentheses followed by a semicolon (;). Both variables and literals can be passed as values when calling a function. Parameters exist only for the life of the function. Changing the value of the parameter within the function does not change the value of the variable passed to the function. Eg: printName(user); printName(Guest); A function call may be located inside the head section or the body section of the HTML document. Variable Scope The parameters of a function are local to the function. They come into existence when the function is called and cease to exist when the function ends. A variable declared within the function would have a scope limited to the function. It cannot be referred to or manipulated outside the function. If a variable is declared outside the body of the function, it is available to all statements inside and outside the function. If a local variable declared within a function has the same name as an existing global variable, then within the function code, that variable name will refer to the local variable and not the global variable. It ignores the global variable for the time being.

Return Values User defined functions can return values. The value is returned using the return statement. The return statement can be used to return a variable, a single value or a valid expression that evaluates to a single value. Eg 1: function volume (num) { var cube = num * num * num ; return cube; } Eg 2: function volume (num) { return num * num * num ;
Network Computing (SRP) Module 2

26

Recursive Functions Recursion functions are functions that call themselves. The function is called or invoked from a statement within the body of the same function. It is commonly used when the function itself needs to be repeatedly executed. Eg: function factorial (num) { if(num > 1) { return num * factorial(num-1); } else { return num; } }

Document Object Model ( DOM ) The HTML page is rendered or painted in a browser. The browser assembles all the elements (objects) contained in the HTML page and then renders these objects in the browser window. Once the page is rendered, the browser can no longer recognize individual HTML elements or objects. JavaScript is an object based language. The JavaScript enabled browser recognizes and uses the Document Object Model (DOM). Using the DOM, the browsers can identify the collection of web page objects / elements present in the HTML based web page. It enables the browsers to recognize individual objects in an HTML page even after the page has been rendered. The developer can create interactive web pages by accessing the properties and controlling the functionality of these objects. It allows a user to access the document via a common set of objects, properties, methods and events, to alter the contents of the web page dynamically using scripts. This means that developers can write a piece of JavaScript code that dynamically updates the page in any type of browser. The DOM achieves this independence by representing the contents of the page as a generic tree structure. The topmost object in the DOM is the browsers Window. The next level in the DOM is the Navigator (the browser) itself. The next level in the DOM is the Document displayed in the browsers window. If the displayed document has an HTML Form coded in it, then the next level is the Form itself.
Module 2

Network Computing (SRP)

27

The DOM hierarchy continues downward to encompass individual elements on a form, such as Text boxes, Labels, Radio buttons, Check boxes, and so on. JavaScripts object hierarchy is mapped to the DOM, which in turn is mapped to the web page elements in the browser window. So, JavaScript is capable of uniquely identifying each element in the web page. JavaScripts DOM is referred to as an instance hierarchy. The HTML object is registered in the DOM only after they are assembled in memory prior to rendering the page. If a document does not contain any Anchors, the Anchors object will exist but will be empty.

A Simple Document HTML Source Object Model

<html> <head></head> <body></body> </html>

Network Computing (SRP)

Module 2

28

<html> <head></head> <body> <p></p> </body> </html>

<html> <head></head> <body> <p>This is the one and only paragraph.</p> </body> </html>

Window object: At the very top of the hierarchy is the window. This object represents the content area of the browser window where HTML documents appear. In a multiple frame environment, each frame is also a window. Because all document action takes place inside the window, the window is the outermost element of the object hierarchy. Its physical borders contain the document. Navigator object: This is primarily used to read the brand and version of browser that holds the current document. This object is read-only, protecting the browser from inappropriate access by the scripts. Screen object: Another read-only object lets scripts learn about the physical environment in which the browser is running. This object is used to access information about the size and color depth of the clients computer screen in which the browser is running. History object: While the browser maintains internal details about the browsers recent history (such as the list available under the Back button), scripts have no access to the details. It is used to maintain a history of the URLs accessed within a window. At most this object assists a script in simulating a click of the Back or Forward button. Location object: This object is the primary avenue to loading a different page into the current window or frame. It can be used to create a URL object, access parts of a URL or modify an existing URL. URL information about the window is available under very controlled circumstances so that scripts cannot track access to other Web sites.
Network Computing (SRP) Module 2

29

Document object: Each HTML document that gets loaded into a window becomes a document object. The document object contains the content that we are likely to script. Except for the html, head, and body element objects that are found in every HTML document, the precise makeup and structure of the element object hierarchy of the document depends on the content we put into the document.

Event Handling JavaScript has an extensive event handling mechanism. Events occur as the result of a user action or, potentially, an external event, such as a page loading. JavaScript provides a way to bind a script to the occurrence of a particular event, through an event handler attribute. This is the name of the event, prefixed by the word on: for example, onclick. Event can be anything such as user action, click, mouse over, page load or page unload and so on. First the web page element or object is identified. Secondly, choose an appropriate event associated with the object. Finally, have a standard method of connecting an objects event and JavaScript code snippets. JavaScript event handlers mapped to an objects events do this. JavaScript has several named event handlers that are mapped to an HTML objects events. JavaScript event handlers are of 2 types: Interactive and Non Interactive An interactive event handler depends on user interaction with an HTML page, such as a mouse click. Non interactive event handler does not require user interaction to be invoked. For example, the page load event occurs without any user action. Named JavaScript Event Handlers Event Handler onAbort onBlur onChange onClick onDblClick onFocus onKeyDown onKeyPress onLoad onUnload onMouseOver onMouseDown onMouseUp Event The loading of an image is aborted as a result of user action Document, Form Element loses current input focus Text field, Text area, file upload field or selection is changed Link, Image Map or Document is clicked by user Link, Image Map or Document is double clicked by user Document, Form Element receives the current input focus User presses a key User presses and releases a key Image, Document is loaded Image, Document is closed or exited Mouse is moved over User presses a mouse button User releases a mouse button

Network Computing (SRP)

Module 2

30

onError onResize onSubmit onReset

Error occurs during loading of an image, window or frame User resizes window or frame User presses the forms submit button User presses the forms reset button

Dynamic updating of pages with JavaScript HTML can be used to create a Graphical User Interface (GUI) in a web page. HTML is capable of accessing and using a number of objects such as textboxes. A textbox is used to accept user input. The textbox is an object which belongs to the DOM. JavaScript facilitates access to such objects and it can process the contents of the form. Properties of HTML objects determine the behaviour of that object. It determines the state of an object. An objects property can be referenced as : ObjectName.PropertyName Methods of HTML objects are used to set or get a value of an objects property. For dynamic updating of pages, an objects properties need to be set dynamically. The methods associated with the objects provide this facility. An objects method can be referenced as : ObjectName.MethodName Using JavaScript it is possible to use an objects built-in methods and manipulate the objects properties at run time. Once JavaScript code accepts client side input or reads a clients browser parameters, web pages can be structured on demand. HTML Objects When a web page is loaded, the browser automatically creates a number of JavaScript objects that map to the DOM. It provides JavaScript access to the HTML objects that are contained in the web page. The JavaScript code snippets embedded as part of the web page makes use of these objects to interact with the HTML objects in the web page. The HTML document may contain various HTML objects such as: Images Image Maps Hyperlinks Frames Anchors Applets Multimedia Objects Form Elements

The HTML page is rendered or painted in a browser. The browser assembles all the elements (objects) contained in the HTML page and then renders these objects in the browser window. Once the page is rendered, the browser can no longer recognize individual HTML elements or objects.
Network Computing (SRP) Module 2

31

To create an interactive web page, each element of the web page would have to be held in memory. The HTML objects are stored in memory. Once the context area in memory of an HTML object is known, JavaScript can set specific object Properties using the Methods of the object. Thus functionality of an HTML object can be controlled while the HTML page is running in the browser. Accessing Web Page Element HTML tags are used to instantiate or create objects in web page. Each HTML object instantiated in a web page has properties and methods. The element can be accessed in several ways such as document.getElementById() or document.formname.elementname. Each HTML object has an event or several events bound to the object. The HTML object can recognize a specific event when it occurs. When an HTML object recognizes an event, it is passed to JavaScript. JavaScript provides a number of named JavaScript Event Handlers. The names of these event handlers are bound to the HTML objects event name. Eg: < input name=text1 type=text value= onChange=<JavaScript function> > A change event is recognized by a textbox when its contents change. JavaScript provides an event handler called onChange that is internally bound to the Change event of the text box. The onChange event handler of JavaScript is bound to a JavaScript code snippet or JavaScript function. As soon as the change event occurs, the JavaScript event handler is invoked and the appropriate code is executed. It results in the page being dynamic and interactive. Simple Form Validation <html> <head> <title>Simple Form Validation</title> <script type=text/javascript> <!-function validate() { if (document.myform.username.value == ) { alert(Username is required); return false; } return true; } //--> </script>
Network Computing (SRP) Module 2

32

</head> <body> <form name=myform id=myform method=get action=simple.jsp onsubmit=return validate(); > Username: <input type=text name=username id=username size=30 /> <input type=submit value=submit /> </form> </body> </html>

ActiveX Controls ActiveX is a Microsoft component object technology enabling Windows programs to load and use other programs or objects at runtime. It is a framework for designing reusable software components. ActiveX controls are basically subprograms launched by the browser that can interact with page content. They are also called as add-ons. It is intended to distribute these controls via the Internet to add new functionality to browsers such as Internet Explorer. ActiveX controls serve to create distributed applications working over the internet. They can be considered as executable codes. They are included or embedded in another program. Security is a big concern for ActiveX controls. Because these small pieces of code could potentially have full access to a user's system, they could cause serious damage. So the latest browsers and operating systems block them by default. Embedding ActiveX Controls An ActiveX control is embedded in the web page using an <object> tag. The <object> tag is used to include objects such as images, audio, videos, Java applets, ActiveX, PDF, and Flash. The object support in browsers depends on the object type. The classid is the most important attribute for an <object> tag. The value of classid identifies the object to include. Each ActiveX control has a class identifier of the form CLSID: classidentifier, where the value for class-identifier is a complex string such as D27CDB6E-AE6D-11CF96B8-444553540000. The <param> tags specify the parameters or information to be passed to the control. It has a name attribute and value attribute. Syntax: <object classid=clsid:class-identifier codebase=url height=pixels or percentage width=pixels or percentage id=unique identifier >
Network Computing (SRP) Module 2

33

Parameters and alternative text rendering </object>

Attribute classid codebase name id height width type border

Value Class_ID URL name id pixels pixels MIME_type pixels

Description Defines a class ID value for the object Defines where to find the code for the object Defines the name for an object Specifies a unique id for an object Defines the height of the object Defines the width of the object Defines the MIME type of data specified in the data attribute Defines a border around the object

Eg: This example defines an embedded Flash file for use with an ActiveX control. <body> <object classid=clsid:D27CDB6E-AE6D-11CF-96B8-444553540000 name=demoMovie codebase=http://download.macromedia.com/flash/swflash.cab# version=6,0,40,0 id=demoMovie width=300 height=200 > <param name=movie value=http://www.javascriptref.com/flash.swf /> <param name=play value=true /> <param name=loop value=false /> <param name=quality value=high /> </object> </body>

Eg:

<embed src=http://www.javascriptref.com /flash.swf width=300 height=250 play=true loop=false quality=high >

Network Computing (SRP)

Module 2

34

<noembed> Error: No Object or Embed Support </noembed> </embed>

Structured Graphics The Structured Graphics control is primarily for visual presentations. It is a Web interface for the widely used Direct Animation subset of Microsoft's DirectX software, used in many high-end video games and graphical applications. It contains a set of graphics primitives. These are widely used for creating graphics in web pages. The Structured Graphics Control allows us to create simple shapes by using functions that can be called via scripting or through param tags inside object elements. The name attribute of the param tag method determines the order in which the function specified in the value attribute is called. The order of calls must be Line0001, Line0002, Line0003 and so on. The SetLineColor(R,G,B) method sets the color of lines and borders of shapes that are drawn. It takes an RGB triplet in decimal notation as its three parameters. The SetLineStyle method takes two parameters which set the line style and line width respectively. A value 1 for line style creates a solid line (the default). A value of 0 does not draw any lines or borders, and value of 2 creates a dashed line. The line width is specified in pixels. The SetFillColor(R,G,B) method sets the fill color of the shapes drawn. It takes an RGB triplet value. Simple shapes such as rectangles, circle, oval, arc, polygon etc can be drawn. The Rect method draws a rectangle. The parameters are x, y co-ordinates, width and height of the rectangle. The origin of the co-ordinates system is set in the center of the screen window. Eg: <body> <object id=lines classid=clsid :369303C2-D7AC- 1ID0-89D5-00A0C90833E6 style=border-style: groove; width: 300 ; height: 200 > <param name=Line0001 value=SetLineColor(255,0,0) > <param name=Line0002 value=SetLineStyle(2,1) > <param name=Line0003 value=Rect(200,100,60,40) > </object> </body>

Network Computing (SRP)

Module 2

35

**********************************************************************************

Network Computing (SRP)

Module 2

36