Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Script Session1 INTRODUCTION.

Similar presentations


Presentation on theme: "Java Script Session1 INTRODUCTION."— Presentation transcript:

1 Java Script Session1 INTRODUCTION

2 Session Objectives Describe JavaScript
Differentiate between Client-Side and Server- Side Applications Differentiate between JavaScript and Java Integrate JavaScript in HTML

3 What is JavaScript (1) A scripting language that can be used to create client-side scripts and server-side scripts JavaScript makes it easier to create interactive Web pages.

4 What is JavaScript (2) You can insert JavaScript statements directly into an HTML page. JavaScript statements can recognize and respond to user events - - mouse clicks, or system generated events - - page resizing, and so on.

5 Versions of JavaScript
Browser Support Javascript 1.0 Navigator 2.0 JavaScript 1.1 Navigator 3.0 JavaScript 1.2 Navigator JavaScript 1.3 Navigator

6 Client-Side and Server-Side Applications
JavaScript can be used to write both client- side and server-side applications. Client applications run in a browser, such as Netscape Navigator or Internet Explorer, and server applications run on a Web server, such as Microsoft’s Internet Information Server or Netscape Enterprise Server.

7 Java Script in a Browser (1)
When the client requests an HTML page that includes a client-side script, the server forwards the full content of the HTML document - - the JavaScript statements and the HTML content. <HTML> <HEAD> <TITLE>Have Fun</TITLE> <SCRIPT LANGUAGE=”JavaScript”>

8 Java Script in a Browser (2)
alert(“Welcome to the world of JavaScript”); </SCRIPT> </HEAD> </HTML>

9 Java Script in a Browser (3)
Using JavaScript

10 JavaScript on a Web Server (1)
Server-side statements can be used to: connect to databases share information across users of an application access the file system on the server

11 JavaScript on a Web Server (2)
The process of creating server-side applications is thus a two-stage process: The HTML pages containing both client-side and server-side JavaScript statements are created along with JavaScript files. All of these files are then compiled into a single executable.

12 JavaScript on a Web Server (3)
When the client browser requests the executable, the run-time engine executes the server-side JavaScript statements and returns the HTML page to the browser.

13 JavaScript and Java(1) Java-enabled browser is not automatically a JavaScript-enabled browser Java, developed by Sun Microsystems, is a full-fledged object-oriented programming language.

14 JavaScript and Java(2) It can be used to create standalone applications and applets. Applets are mini applications, which are downloaded and executed in the browser. JavaScript, developed by Netscape, is an object-based scripting language.

15 JavaScript and Java(3) While most Java syntax and basic control-flow constructs are supported by JavaScript, it does not have Java’s static typing and strong type checking. JavaScript cannot be used to create applets or standalone applications.

16 JavaScript and Java(4) Java programs consist exclusively of classes and their methods. JavaScript consists of a small range of data types representing numeric, Boolean, and string values. JavaScript provides dynamic inheritance.

17 JavaScript and Java(5) Functions in JavaScript need not have special declarations. Functions can be properties of objects, executing as loosely typed methods. Java code must be compiled before it is executed.

18 Embedding JavaScript You can insert JavaScript statements into an HTML document in the following ways: Embedding the statements directly in the document using the <SCRIPT> tag. Linking a JavaScript source file to the HTML document.

19 Embedding JavaScript (1)
Using JavaScript expressions within HTML tag attribute values. As event handlers within certain other HTML tags.

20 Using the SCRIPT tag(1) JavaScript code is typically embedded into an HTML document using the SCRIPT tag. You can embed several scripts into a single document, provided you enclose each script with a SCRIPT tag.

21 Using the SCRIPT tag(2) The format is:
<script language=”JavaScript”> JavaScript statements </script>

22 Using the SCRIPT tag(3) JavaScript statements must be terminated with a semi-colon (;). <html> <head> <script language = “JavaScript”> document.write(“Welcome to the world of JavaScript”); </script> </head> <body> <p> Enjoy learning <\body></html>

23 Using an External file(1)
You can also link an external text file containing JavaScript code to an HTML document. The SRC (source) attribute of the SCRIPT tag can be used to include the external file.

24 Using an External file(2)
You can specify absolute and relative pathnames to the SRC attribute. <scriptlanguage=”JavaScript” src=”filename.js”> The external file is a text file containing JavaScript code, and whose filename ends with the extension “.js”.

25 Using an External file(3)
The .js suffix must be mapped by the server to the MIME type application/x-javascript. The server then sends it back in the HTTP header. The suffix can be mapped to the MIME type by adding the following line to the mime.types file in the server’s config directory.

26 Using <Noscript>(1)
If the browser does not support JavaScript, you can make use of the <NOSCRIPT> tag. The browser will display HTML enclosed within a <NOSCRIPT> tag in plain text. Browsers that support JavaScript ignore the code within this tag.

27 Using <Noscript>(2)
The following example shows a <NOSCRIPT> tag. <HTML> <HEAD> <SCRIPT> document.write(“Having fun”); </SCRIPT> </HEAD>

28 Using <Noscript>(3)
<BODY> <NOSCRIPT> <P>The browser does not support JavaScript<BR> <A HREF=” ”>Click Here</A>

29 Using <Noscript>(4)
<P>If your browser supports JavaScript, check the browser configuration to see if it is enabled. </NOSCRIPT> </BODY> </HTML>

30 Using <Noscript>(5)

31 Displaying Information(1)
Using write and writeln object.write(string) <HTML> <HEAD> <TITLE>Using Methods</TITLE> <SCRIPT LANGUAGE = “JavaScript”> document.write (“Are you having fun?”) </SCRIPT> </HEAD> </HTML>

32 Displaying Information(2)
object.writeln(string) <HTML> <HEAD> <SCRIPT LANGUAGE = “JavaScript”> function doloop() { var String1 = ‘<hr align=”center” width=’; document.open();

33 Displaying Information(3)
for (var size = 5; size <= 100; size+=5) document.writeln(String1 + size + ‘%”>’); document.close(); } </SCRIPT></HEAD> <BODY> <FORM> <INPUT type=”button” value=”Test the loop” onclick = “doloop()” > </FORM></BODY> </HTML>

34 Using Alert(1) object.alert([message]) <HTML> <HEAD>
<SCRIPT LANGUAGE = “Javascript”> alert (“Click OK to reboot the computer”); </SCRIPT> </HEAD> </HTML>

35 Using Alert(2) Staying Alert

36 Using Confirm The confirm method is used to display a message with OK and Cancel buttons. object.confirm([message]) <HTML> <HEAD> <SCRIPT LANGUAGE = “Javascript”> confirm (“Do you want to continue?”); </SCRIPT> </HEAD> </HTML>

37 Using Prompts The prompt method is used to display a message box to accept user input. object.prompt([message[, inputDefault]]) where message - - is the string to be displayed. This is optional. Inputdefault - - is the string or integer that represents the default value of the input field.

38 Data types and Operators
Session 2 Data types and Operators

39 Session Objectives List different data types available in JavaScript
Numeric – Integers and Floating-point Numbers Alpha numeric – Strings Boolean – TRUE or FALSE Apply basic arithmetic and assignment operators Use data declaration and assignment statements Type casting in JavaScript

40 Data types Numbers Jack, michal and joe Boolean values Names
Every data used in program should be declared first to be of a particular type Numbers 10, - 67,14.45, Jack, michal and joe TRUE, FALSE Boolean values Names

41 Number Comprises of Numeric Data and can be classified as
Integers ( without decimals) Eg : 123, 5040, -121 Floating- point ( with decimals) Eg :

42 Integers Number system Base Representation Example Decimal 10
Sequence of digits ( 0 – 9) 35, -63 Octal 8 Sequence of digits ( 0 – 7) with a leading 0 Hexa 16 Sequence of digits ( 0 – 9, A - F) With a leading 0X 0XABC 0X123

43 Floating point Numbers
Represent fractional numbers and can be positive and negative integers with exponents Floating points numbers can be positive and negative Example : e-2 ( 1/ 100)

44 is 10 < 20 True ? False? Boolean Value
Results from comparison operation returns either a TRUE or FALSE. Eg : is 10 < 20 Returns the value True Is Night longer than Day? Returns the value False is 10 < 20 True ? False?

45 String In JavaScript strings are represented by data enclosed within ‘’ or “” and can contain Numbers ( 0 – 9 ) Alphabets ( a – z) and ( A – Z ) Special characters like -, #, $, * Blank spaces Eg : “ABC 12345” , ‘John Martin’

46 String with Quotes It can include ‘’ ( single quotes ) within double quotes and double quotes “ “ enclosed within single quotes “ John D’silva” and ‘string to display double quotes ( “” ) ’ Escape characters are used to represent double quotes with double quotes and single quotes within single quotes  “ Double Quotes \“\” ” ‘Single Quotes \‘\’ ’

47 List of Escape characters
Single Quote Double Quote Back Slash Carriage Return Form Feed New Line Back Space Tab \ ’ \ ” \ \ \ r \ f \ n \ b \ t Escape sequences should be used only with <PRE> </PRE> tag.

48 Variable Declaration Variables can be declared as follows
Declaring a single variable in JavaScript var sum ; Declaring more than one variable in JavaScript, using a single declaration statement var sum, average,result ; Where sum, average and result are variables.

49 Variable Initialization
Variables can be initalized in two ways ; During Declaration . Var sum = 0 0 is assigned to variable sum Var name = ‘Smith’ Name ‘Smith’ is assigned to variable name After Declaration var sum Sum = 0

50 Displaying Variable Contents
How much money do I have ? In JavaScript document.write ( ) is used for displaying the contents of a variable Eg : var balance balance = $22 document.write(“Current Balance is = ” Output balance) Current Balance is = $22 VALUE = ?

51 JavaScript Statements
Every JavaScript program is made up of several instructions. Each instruction is called a statement. Statements are present as a block enclosed with { and } brackets.

52 Types of Statements Assignment statements Data declaration statements
Conditional statements Loop statements

53 Assignment Statement Used for assigning values to variables.
Expression on the right side of the = sign is evaluated and assigned to the variable on the left Example : A = B * 10 sum = sum + total

54 Operator & Operand Average=(a+ b) / 2 Amt = Rate * qty -
Operator : acts upon values in an arithmetic expression to produce result. Operand : Values on which Operators act Types of Operator : Binary Operators Unary Operators Assignment Operator - Average=(a+ b) / 2 Amt = Rate * qty

55 % Operators List of Binary operators
Used with values to form mathematical expression. Types of operators Binary unary Binary operators takes two operands List of Binary operators + ( add ) - ( minus ) * ( asterisk) / ( Division) %

56 Assignment Operator = is known as the assignment operator
It is a Binary operator Used in expression to assign values to variables. Assigns the value of the right hand side operand / expression to the operand on its left Eg : Num1 = 2 Str1 = “JavaScript” Result = true

57 Compound Assignment Operators
Assignment operator can be used along with other Binary Arithmetic operators Operator Usage Inference += A+= B A = A + B -= A-=B A = A – B *= A*=B A = A * B /= A /= B A = A / B

58 Unary Operator Takes one operand only ++ and -- are unary operators
Eg : A = 10 A ++ is similar to A = A + 1 as it increases the value of A by 1. A - - is similar to A = A – 1 as it decreases the value of A by 1.

59 Unary Operator [Contd…]
Increment Operator can be used in two ways A = 10 Pre-increment ++a and -- a are used to change the value of a before it is used in expression Post-increment A++ and A - - are is used to change the value of A after it is used with the current value of A. The same is applied to decrement operator

60 Negation & Modulus operator
Negation (-) is used to represent negative values Eg : -10, Modulus ( % ) operator returns the remainder of a division operation to the variable. Eg : Num = 10 Ans = Num % 3 Value 1 is assigned to the variable Ans

61 Type casting Automatic conversion of one type of data to another type ( when used in an expression) is called type casting. Eg : Ans = “ cost of fruits = “+ 10 “cost of fruits = 10” gets stored in variable Ans Num = 10 + “12.5” Evaluated to 22.5 and gets stored in variable Num.

62 Summary JavaScript supports the following data types
Number – This consists of numbers including integer and floating-point String – This consists of text specified within single or double quotes. Null – This consists of “null” value. Boolean – This consists of Boolean values TRUE and FALSE “String”, is one or more characters or digits or a combination of both enclosed within single or double quotes.

63 Summary The operator = is the assignment operator. It performs a simple operation of assigning a value to a variable. Arithmetic operators operate on numerical values and return numerical values only. For example +, -, * and / Ability of a programming language to automatically convert values from one type to another when they are used in expressions is known as type casting.

64 Operators And Control Statements
Session 3 Operators And Control Statements

65 Session Objectives Explain operator precedence
Apply logical and comparison operators Change operator precedence using parenthesis Use bitwise, string, ternary and comma operators Apply conditional statements – if, if-else and nested if Identify the need for loops and apply them

66 Operators Operators are symbols used to process data
Different types of process in which operators are used : Arithmetic Comparison Logical Text concatenation

67 Types of Operators Arithmetic + - * / %
* / % Used in any Arithmetic calculation Comparison < > = <= >= == != Used to compare two elements on its value Logical AND, OR & NOT Complex Operations based on combination of comparison / condition

68 Multiplication Division Modulus
Precedence level Consider the eg. Ans = * 3 Pay = basic – tax + allowance An expression may have more than one operator, precedence decides the order in which the operators are chosen for execution When two operators are of same precedence occur in an equation then it is solved from left to right. Arithmetic Operators 1 - Negation 2 * / % Multiplication Division Modulus 3 Addition Subtraction

69 Greater than and Equal to
Comparison Operators < Less than <= Less than and Equal to > Greater than >= Greater than and Equal to == Equal to != Not equal to

70 Logical Operators Operator Symbol AND && OR || NOT !

71 Logical Operator Precedence Table
1 NOT 2 AND 3 OR To evaluate : false OR true AND [true AND true] With equal precedence of Logical Operators in an expression, it gets resolved from right to left

72 Precedence Among Operators
Any expression containing combination of all operators, the precedence in which it gets processed is as follows : Precedence Type of Operator 1 Arithmetic 2 Comparison 3 Logical

73 Changing Precedence Parenthesis ( ) has the highest level of precedence. The precedence of operators can be modified using parenthesis ( ). Operator of lower precedence with parenthesis assume highest precedence and gets executed first. In case of nested Parenthesis ( ( ( ) ) ) the inner most parenthesis gets evaluated first. An expression consisting of many set of parenthesis gets processed from left to right.

74 String Operator ‘ + ‘ Operator is used to concatenate strings. Eg :
STR 1 = ‘ Java’ STR2 = ‘Script ’ STR3 = STR1 + STR2 JavaScript gets assigned to variable name STR3

75 Bitwise Operators Bitwise operator processes data after converting number to its binary equivalent. (Bit wise representation). Used to perform both Logical operations Shift operations With bitwise data

76 Bitwise - Logical Operators
AND ( NUM1 & NUM2) Return 1 if both the operands are 1s. OR ( NUM1 | NUM2 ) Returns 1 if bits of either of the operand are 1s. NOT ( ~ NUM1) Reverses the bits of its operand ( from 0 to 1 and 1 to 0). XOR ( NUM1 ^ NUM2) Returns 1 if either of the bits in an operand is 1 but not both.

77 Bitwise - Shift Operators
Operation Action Result << Left shift 15 << 2 Shift the Bits by two positions towards left >> Right Shift 15 >> 3 Shift the Bits by three positions towards right >>> Zero filled Right shift 25 >>> 2 Shift the Bits by two positions towards right and fills it with zero.

78 Ternary Operator Evaluated based upon certain condition
It has a set of three operands. The first operand is the condition to be evaluated Ans = ( Num1 > Num2 ) ? 10 : 20 The second operand is the value returned if the condition is true Ans is assigned the value 10. The third operand is the value returned if the condition is false Ans is assigned the value 20. If Num1 > Num2 variable name Ans gets 10 else 20 stored in it.

79 x = ( a++ , c) * ( b++ , d) (x = c * d )
Comma (,) Operator The comma operator (,) evaluates two operands and returns the value of the second operand. Eg :   a = 2 b = 3 c = 4 d = 5 x = ( a++ , c) * ( b++ , d) (x = c * d ) Value 20 is assigned to variable name x.

80 Typeof Operator Returns the string representing the type of the operand used with it. Eg : Num1 = typeof( “JavaScript “) Num1 is assigned string Num2 = typeof(123) Num1 is assigned Number

81 Conditional Statement
If ( <condition> ) Set of statements to be executed if the condition is true else be executed if the condition is false Used in decision making. Set of statements have to be executed based upon certain condition. Conditional statement is used to change the flow of program execution.

82 Nested Condition Statements
If (condition 1 ) If (condition 2 ) Statements to be executed if the condition is true else statements to be executed if the condition is false end if If (condition 3 ) endif Condition 1 is true Condition 2 is true Condition 2 is false Condition 1 is false Condition 3 is true

83 Loops Start Initialise counter variable……
Yes No is counter variable = expected no. statements End Set of statements have to be executed repeatedly for specific number of times. Used with certain condition to control the number of iterations Advantages of Loops Used to minimise code size …statements to be executed until the condition is met Increment / decrement counter variable……

84 FOR Loop Initialise the counter variable.
check the value of the counter variable against max limit to operate the loop. If the condition is true then the loop is terminated. Otherwise Counter variable gets updated after executing the set of statements. Repeat the above operation till condition is not true. Eg : Find the sum of numbers from 1 to 100.

85 Nested FOR Loops To calculate and print the cube of ten numbers …………..
for (i=1; i<10; i++) { Cube = 1 Read Number   for(j=1; j<3; j++) Cube=Cube* Number } Print Number, Cube …………. for loop present within other for loop is called as Nested for loop. Execution of Inner most Loop gets completed first Loops cannot overlap with another loops. Eg : To calculate and print the cube of ten numbers

86 Summary Operator precedence is the order in which operators get evaluated. If two operators of the same precedence occur in an expression, then it gets evaluated from left to right. Operators used for comparing two operands on the basis of a certain condition are called as Comparison Operators. Logical operators take Boolean values (true or false) as operands and return a Boolean value.

87 Summary The precedence of operators can be modified using parentheses
Ternary operator takes three operands, condition to be evaluated two values to be returned depending upon the condition evaluating to true or false. The comma operator (,) evaluates two operands and returns the value of the second operand. The typeof operator returns a string indicating the type of the operand.

88 Summary The if statement allows decisions based on a condition
The if statement can contain another if - else statement is called the nesting of if statements. A loop is basically the execution of a set of statements repeatedly. Loops present within another Loop is called as Nested loop. In nested loops, execution of Inner most Loop gets completed first

89 Programming Constructs
Session 4 Programming Constructs

90 Session objectives Use while and do – while construct
Use switch-case construct Apply break and continue statements Use conversion functions

91 statements to be executed until the condition is met
While Construct Start ……. To execute a set of statements repeatedly till it satisfies certain condition. Condition is evaluated every time before the statement is executed. Operation of the while loop is terminated when the condition is not met. No Condition = ? Yes statements to be executed until the condition is met ……. End

92 statements to be executed until the condition is met
Do While construct Start ……. To execute a set of statements repeatedly till it satisfies certain condition. Condition is evaluated after the statements are executed for the first time. Operation of the while loop is terminated once the condition is not met. statements to be executed until the condition is met No Condition = ? Yes ……. End

93 Statements to be executed before the condition
Start ……. Continue statement Statements to be executed before the condition used to skip portion of the loop and continue with next iteration. On execution control is transferred to the looping statement to continue with the looping process continue statement can be used anywhere in the loop. Used within a if statement No Condition = ? Yes Continue Other loop statements ……. End

94 Switch - Case Statement
The switch-case statement is construct to choose from multiple paths of branches Switch statement is used with an variable Multiple case statements are present in the construct Statements inside the case construct gets executed for which the value matches with variable used with Switch statement.

95 Switch - Case Statement (Contd…_)
Case statements should be constructed in such a way that only one case construct gets executed. default case gets executed only when there are no matching values used with case. One default case should be present in every problem using switch-case construct

96 switch - case statement [Cont…]
+ Ans = Num1 + Num2 . Read Num1 Num2 OPR - Ans = Num1 - Num2 * Ans = Num1 * Num2 / Ans = Num1 / Num2 Branching based upon opr value Not a valid opr Default

97 switch - case statement [Cont…]
switch ( value ) { case ( value 1 ) : Statement(s) }  case ( value n ) : default :

98 Conversion functions eval() –
This function converts a string to a numerical value.   eg sum = eval(“1234”) value 1234 gets assigned to the variable name sum. eg num = parseInt(“xyz123”) An error is encountered when the eval() is used with the string containing non numerical values.

99 Conversion functions [Contd…]
parseInt() – This function extracts integers from the string if the string starts with numbers. num = parseInt(“123String”) value 123 being assigned to the variable num num = parseInt(“xyz123”) value 0 is assigned to num

100 Conversion functions [Cont…]
parseFloat() it extracts and returns the floating-point number from the given string. Number = parseFloat(“1. 23e2xyz”) function returns to Number Number = parseFloat(“xyz”) returns 0 to Number

101 Summary The while statement is another looping structure in JavaScript language and is used to execute a set of statements while a certain condition is true. The do - while statement is similar to that of the “while” loop. The only difference is that the looping condition is checked at the end of the loop, instead of at the beginning. The break statement is used to exit from a loop and transfers the control to the statement after the loop. The continue statement is similar to that of the break statement but it does not terminate the loop.

102 Summary The eval() function converts a string to a numerical value.
The parseInt() function converts a string in to an integer. The parseFloat()extracts the first floating-point number from the given string.

103 Session 5 Working with Arrays

104 Session Objectives Identify the need for Construct arrays
Single dimensional array Double dimensional array Construct arrays Use Dense arrays Work with different type of array elements Use array manipulation commands

105 Using Variables be declared If a program has large amount
Each of these variables has to be declared If a program has large amount of data is to be stored, it is difficult to think of a variable name for each of these. One variable can store one value at a time. Hence for storing 100 values 100 different variables are required. Use of more number of variables lead to longer execution time for a program Start Declare num1, num2, num3, num4, num5 and sum as integers Accept num1 Accept num2 Accept num3 Accept num4 Accept num5 Sum = num1 + num2 + num3 + num4 + num5 Display sum End

106 What is an Array? An Array is a group of elements of the same data type which share a common name. Example for a Single Dimension Array : An Array of Characters J A V S C R I P T

107 Characteristics of Arrays
All the elements share a common name. Each element has the same data type. The entire array is stored contiguously in memory. Array of Characters Array of Numbers Prglang[9] digits[9] J A V S C R I P T 1 2 3 4 5 6 7 8 9

108 Declaring an Array Array num[5] Syntax used for declaring an array
No. of elements Name of array

109 Declaring an Array [Contd…]
In JavaScript : for creating an fixed length array Method 1 ArrayName = new Array(arrayLength) Fixed length array gets created in memory with the specified length.

110 Declaring an Array [Contd…]
In JavaScript : for creating variable length Array Method 2 ArrayName = new Array() A variable length Array gets created in memory block. Array length is equal to the number of elements stored in the array Variable arrays help conserve memory space

111 Array Index Array element is accessed with the help of index number.
4 5 6 7 8 Array index Num(0) Num(1) Num(2) Num(3) Num(4) Array element is accessed with the help of index number. num[0] :- index starts at 0

112 Using Arrays Start Example : To find the sum of 5 nos. using array
Advantages Array declaration for 5 elements Reduces Code size and minimise on use of variables Every array position can store different values. Faster execution of the program. Start Array num[5] Declare sum, count as integer sum = 0 count = 0 While count < 5 Accept num[count] Add num[count] to sum count = count + 1 Display sum End

113 Assigning Values To Array Elements
Assigning strings to an array For example: Employee[0] = “James” Employee[1] = “Paul” Where Employee is name of the array.

114 Assigning Values To Array Elements[Contd…]
Assigning Integers to an array int_Arr[0] = 10 int_Arr[1] = 11 Assigning characters to an array ch_ar[0] = ‘l’ ch_ar[1] = ‘o’

115 Retrieving Values From an Array
Num(4) The contents of an array can be retrieved in following way Variable Name = Array name [Index] Ex A = Num[2] which assigns value 14 to Variable name A 12 13 14 15 16

116 Multi-Dimensional Array
To store marks in 3 subjects for 4 students. Two- Dimensional Array is declared in terms of rows and columns Used to store tabular data Marks [Rowpos][Colpos] Physics Maths Science Julia 45 60 90 Ben 20 67 92 Tom 35 56 Demi 78 50 80

117 Multi-dimensional Array [Contd…]
Marks[3][3] To access an element of a multi-dimensional array var X = Marks[0][1] Value 60 is assigned to variable name X Physics Maths Science Julia 45 60 90 Ben 20 67 92 Tom 35 56 Demi 78 50 80 rows are student names columns are subjects

118 Dense Arrays Days(0) ………Days(6) When an array is initialized during
declaration itself, it is known as “Dense Array”. Days = new Array(“Mon”,”Tue”,”Wed”,”Thu”,”Fri”,”Sat”,”Sun”) Mon Tue Wed Thu Fri Sat Sun Days(0) ………Days(6)

119 Finding the Length of Array
Array_Name.length is used to determine the length of an array (number of elements that can be stored) weekdays = Days.length Value 7 is assigned to the variable name weekdays Mon Tue Wed Thu Fri Sat Sun

120 Manipulation of Arrays
Array function : toString() : Converts an array to string. Ex document.write(num.toString()) num = 4 5 6 7 8 “45678”

121 Manipulation of Arrays[Contd…]
Array function : join(separator): Separator string separates the array elements Ex document.write(num.join("-")) num = 4 5 6 7 8

122 Manipulation of Arrays[Contd…]
Array function : sort() : Sorts the contents of array in ASCII format Ex document.write(num.sort()) num = 6 5 4 2 8 2 4 5 6 8

123 Manipulation of Arrays[Contd…]
Array function : reverse() : reverses the contents of array. Ex document.write(num.reverse()) Num = 4 5 6 7 8 8 7 6 5 4

124 Nested Arrays Arrays can be stored as other array’s element Arr1 10 20 30 40 50 The length of Arr1 is 5 and the sum of elements is 150 Arr2 11 12 13 14 15 The length of Arr2 is 5 and the sum of elements is 65 Arr3 Arr1[0] Arr1[1] Arr1[2] Arr1[3] Arr1[4] Arr2 The length of Arr1 is 6 and the sum of elements is 215

125 ARRAY WITH DIFFERENT DATA ELEMENTS
junk = new Array (“Hello”, ‘World’, 12, 123.4, true, false); Junk Hello World 12 123.4 True false document.write( Junk[0]+Junk[1]); Concatenates and returns “HelloWorld” document.write( Junk[2]+Junk[3]); Sums up the values and returns 135.4 document.write( Junk[4]+Junk[5]); Evaluates and returns 1 [True (1) + False(0)]

126 Summary A collection of objects all of the same type is known as an array. Each object in an array is called an array element.   The array index indicates the position of the array element, which is to be accessed.   Array_Name [Index]  In JavaScript arrays can be declared in the following manner.  arrayName = new Array (arrayLength) arrayName = new Array ( )

127 Summary Array elements can be initialised in the following manner
 Array_Name [ Index ] = Value Array_Name is the name of the array Index is the position of the array element for which the value has to be assigned Dense Arrays are ones, which are initialised during the declaration stage itself.

128 Summary The following are the functions that can be used with arrays
 toString() This functions converts an array to a string.. join(separator) This function is same as the toString() function.. sort() This function sorts the contents of an array based upon the ASCII value reverse() This function reverses the contents of an array.

129 Session 6 Functions

130 Session Objectives Need for functions Advantages of Functions
Functions with fixed and variable parameters Use of the return statement Difference between user-defined and predefined functions The need for function libraries The “Function” object

131 Functions Larger programs are broken down into smaller modules for the ease of understanding. Each module can act as a separate program by itself Smaller modules performing task on it own are functions.

132 Function Definition Function Calling statements Function names Func1
1.Start 2. Func1() Func2() Func3() 4. End Function Calling statements Function names Func1 Func 2 Func 3 Function definition Statements within Function

133 Invoking a Function Program Function PF_CAL() Function PF-Calc()
Start ……… ……. do Accept emp_no, emp_name HRA_CAL() allow = HRA + std_Allow PF_CAL() deduct = std_ded + PF net_sal = (basic + allow) - deduct display emp_no, emp_name …….. End Program Function PF-Calc() Is invoked Function PF_CAL() 1 Start 2 if (grade != 3) PF = .06 * basic else PF = 0 end if 3 return

134 Functions Arguments User defined function ADD(x,y) to add two numbers
Functions arguments are values passed to functions to perform certain task User defined function ADD(x,y) to add two numbers X & Y are arguments Add (x is an integer, y is an integer) Start Declare sum as an integer sum = x + y Display sum return

135 Standard Functions Standard functions pre-defined by
software itself to perform specific task Example document.write()

136 User-defined Functions
User-defined functions written by user to perform specific task Example To add two numbers

137 Local Variables <TITLE> Sum Function </TITLE>
<SCRIPT LANGUAGE = "JavaScript"> function Sum(num1, num2) { var ans = num1 + num2 document.write (“The sum is ” + ans) } </SCRIPT> </HEAD> <BODY> <H1 ALIGN = "CENTER"> Function to add two numbers</H1> Sum (1,2) Ans can be accessed from the block where it is defined only.

138 Global Variables anywhere in the program Sum can be accessed from
</HEAD> <BODY> <H1 ALIGN = "CENTER"> Local and Global variables </H1> <SCRIPT LANGUAGE = "JavaScript"> function Sample() { Sum = 1 } Sample() document.write ("The value of the variable global Sum is" + Sum) </SCRIPT> </BODY> </HTML> Sum can be accessed from anywhere in the program

139 Function Libraries Date and Time MATH
A collection of functions is known as a function library. The advantage using a function library is that it need not be reproduced in programs. Date and Time   Fetch the system date and time Extract the month from a date Calculate the days between two dates MATH Avg() – to calculate average Sqrt() – to calculate square root

140 Functions With Varying Arguments
<TITLE> Sum Function </TITLE> <SCRIPT LANGUAGE = "JavaScript"> function Sum () { var len = Sum.arguments.length var ans = 0 for (i=0; i<len; i++) ans += Sum.arguments[i] } document.write( “The sum is” + ans) document.write(“<BR>”); </SCRIPT> </HEAD> <BODY> <SCRIPT> Sum (10, 20) Sum (10,20,30) </HTML> JavaScript allows functions with varying arguments only when used with argument array

141 Function - Returning Values
<TITLE> Sum Function </TITLE> <SCRIPT LANGUAGE = "JavaScript"> function Sum(num1, num2) { var ans = num1 + num2 return ans } </SCRIPT> </HEAD> <BODY> <H1 ALIGN = "CENTER"> Function to add two numbers</H1> var total = Sum (1,2) document.write (“The sum is” + total) function Sum is invoked to return Value of ans (3) to variable total

142 Function Object To create functions dynamically
Fn = new Function(“a1”, “a2”, ….. “an”, ”Body”) Example sum= new Function(“a1”,”a2”, “var ans=0; ans=a1+a2; return ans;”) Sum1 = Sum(1,2) shall invoke the above function and return the value 3 to variable name sum

143 Summary specific task. Functions may or may not return a value.
Functions are set of statements, which perform a specific task. Functions may or may not return a value. Every function has a name and an argument list, which is optional. Values passed to the functions are known as parameters / arguments. The control is transferred back to the calling program after the execution of the last statement in the called function. The return statement can be used for transferring the control and value back to the calling program.

144 Summary Variables declared inside a function using the var keyword are known as local variables and their scope is limited to the function. variables without using the var keyword, then it can be accessed from any part of the program. Such variables are known as global variables. User defined functions are written by the programmers according to their requirements.  Standard functions provided by the programming language.  A collection of functions is known as a function library.. The Function object allows you to dynamically create and invoke functions

145 Session 7 Event Handling

146 Session Objectives Define an event Define an event handler
Types of event handlers Events associated with various HTML elements Basic mouse events

147 Events & Event handlers
An event represents the user’s interaction with the program execute code for Mouse move event Event handlers Mouse Move execute code for Key Press event Key Press event

148 Triggering Events Screen saver - event triggered by the system.
Events can be triggered by an activity between 1. Program 2. System 3. User Eg System generates an event when an action is performed by the user such as selecting a particular menu option clicking on some button etc Screen saver - event triggered by the system.

149 Example in JavaScript Event handler : Event Handler can be
Code segment attached with an event It gets executed when the event is triggered. Event Handler can be System defined User Defined

150 Example in JavaScript Eg ‘++num; alert(“Number : ”+num)’ mouseOver is an event which is generated every time the mouse is placed over a hyper link

151 Event Handler attributes and Events
Attributes are used for identifying events Eg onMouseOver is defined by JavaScript to identify occurrence a mouseOver event Event mouseOver Event Handler Attribute onMouseOver

152 Event Handling Attribute
 click onClick dbClick onDbClick mouseUp onMouseUp mouseDown onMouseDown mouseOver onMouseOver keyDown onKeyDown Mouse events Keyboard Events

153 Link Events The above events gets generated when
HTML Element  HTML Tag   JavaScript Event  Description Link <A> </A>  click Left mouse button is clicked on a link dbClick Left mouse button is double clicked on a link  mouseOver Mouse cursor is placed over the link mouseDown Left mouse button is pressed mouseUp  Left mouse button is released keyDown Key is pressed The above events gets generated when the user interacts with the hypertext

154 Body Events HTML element HTML tag JavaScript event Description
Body Events HTML element HTML tag JavaScript event Description Document Body <BODY> </BODY> click When mouse is clicked in the document body dbClick  When mouse is double clicked in the document body blur When window loses focus mouseDown When mouse button is pressed mouseUp When mouse button is released keyDown When key is pressed

155 Body Events – (Contd.) keyUp When key is released keyPress
keyUp When key is released keyPress When key is pressed and released move When window is moved resize When window is resized load When loading of window is complete unload When window is closed focus When window receives input focus

156 Image Events HTML element HTML tag JavaScript event Description Image
HTML element HTML tag JavaScript event Description Image <IMG> abort When image loading is cancelled error When there is an error while loading an image load When an images is loaded and displayed keyDown When key is pressed keyUp When key is released keyPress When key is pressed and released

157 other events HTML element HTML tag JavaScript event Text field
other events HTML element HTML tag JavaScript event Text field <INPUT TYPE = “TEXT”> blur focus change select Password Field <INPUT TYPE = “PASSWORD”> blur, focus

158 other events (Contd.) Button <INPUT TYPE = “BUTTON”> click
Button <INPUT TYPE = “BUTTON”> click mouseDown mouseUp blur focus Submit <INPUT TYPE = “SUBMIT”>

159 other events (Contd.) Reset <INPUT TYPE = “RESET”> click blur
Reset <INPUT TYPE = “RESET”> click blur focus Radio Button <INPUT TYPE = “RADIO”>

160 other events (Contd.) Checkbox <INPUT TYPE = “CHECKBOX”> click
Checkbox <INPUT TYPE = “CHECKBOX”> click blur focus Selection <SELECT> </SELECT> change

161 other events (Contd.) TextArea <TEXTAREA></TEXTAREA> blur
TextArea <TEXTAREA></TEXTAREA> blur focus change keyDown keyPress keyUp select

162 Summary Events occur as a result of the user
interaction with any application. The code that is executed when an event occurs is known as an event handler. An Event can be either triggered by a user or by another event.

163 Summary Events in JavaScript can be broadly classified as follows:
Events associated with <A> tag Events associated with <IMG> tag Events associated with <BODY> tag Events are also associated with other HTML elements such as buttons, text field, password field, text area, selection, submit and reset buttons.

164 Session 8 Object and Forms

165 Session Objectives Identify the need for JavaScript
Explain the term Object Use properties and methods of an Object List in built JavaScript objects such as browser, window, document and forms Use form elements using the form object

166 Session Objectives (cont.)
List the properties and methods of the form object Use the forms array of the document object Use the elements array of the form object

167 JavaScript – Features JavaScript simpler processing than capabilities
CGI scripts processing capabilities to HTML forms objects to manipulate web pages hybrid HTML and a Programming language interactive web pages

168 Browser Objects Description Browser Object window object
Description window object To access the browser window. It is the top most object in the browser objects hierarchy document object To access the document displayed in the browser. It is used to access the contents displayed by head and body sections form object forms array To access an HTML form. The forms array is used to access all the form objects in the HTML document elements To access all the form elements in the HTML document Browser Object

169 Window Object Top level object in the hierarchy of browser objects
Automatically defined by the browser Need not specify the name of the window object while invoking methods such as alert(), prompt()

170 Window Object (Example)
document.write(“Some Display Text”) JavaScript assumes the current window object and executes window.document.write(“Some Display Text”)

171 Document Object The forms array provides access
It has a property called forms, which is an array The forms array provides access to all the forms embedded in a web page Eg to access the third form : document.forms[2] window.document.forms[2]

172 Form Object To interact with HTML forms and process document.form_name
its contents document.form_name document.forms[index] To access document.myform2 document.forms[1]

173 Accessing Form Elements
Using the HTML name document.form_name.element_name document.myform1.text1.value Using elements array document.myform1.elements[3].value

174 Form Elements (Properties & Methods)
Element Object Properties Methods button name click() type blur() value focus() <P ALIGN="CENTER"><INPUT TYPE="BUTTON" VALUE="Submit Form" ONCLICK="return processForm()"><INPUT TYPE="RESET" VALUE="Reset Form"></P>

175 Form Elements (Properties & Methods)[Contd…]
Element Object Properties Methods text name select() type blur() value focus() Default Value <H2 ALIGN="CENTER">Handling Form Events</H2><HR> <FORM NAME="form1"> <P>First Name :<INPUT TYPE="TEXT" NAME="fname" MAXSIZE="10" ONCHANGE="Validate_FirstName()"> Last Name :<INPUT TYPE="TEXT" NAME="lname" MAXSIZE="15" ONCHANGE="Validate_LastName()"></P>

176 Form Elements (Properties & Methods)[Contd…]
Element Object Properties Methods checkbox checked click() name blur() type focus() value default Value

177 Form Elements (Properties & Methods)[Contd…]
Element Object Properties Methods checkbox name blur() type focus() length selectedIndex options

178 Form Elements (Properties & Methods)[Contd…]
<H1 ALIGN = "CENTER"><U>Hobbies</U></H1> <INPUT TYPE = "CHECKBOX" NAME = "Hobbies" VALUE = "Reading" CHECKED> Reading Books <BR> <INPUT TYPE = "CHECKBOX" NAME = "Hobbies" VALUE = "Music" > Listening to Music <BR> <INPUT TYPE = "CHECKBOX" NAME = "Hobbies" VALUE = "Trekking" > Trekking <BR> <INPUT TYPE = "CHECKBOX" NAME = "Hobbies" VALUE = "Painting" > Painting <BR>

179 Accessing forms in a HTML Document
To access the value of an object text1 which is in a form myform1 document.myform1.text1.value To access the value of an object text1 which is in the second form of the document document.form[1].text1.value <SCRIPT LANGUAGE = "JavaScript"> <BODY> <H2 ALIGN = "CENTER"> Basic form processing </H2><HR> <FORM NAME = "myform1"> Your Name <BR> <INPUT TYPE="TEXT" NAME="text1" SIZE = "15"><BR> Your Password <BR> <INPUT TYPE="PASSWORD" NAME="pass1" SIZE= "8"><BR>

180 Summary JavaScript is an interpreted, object-based scripting language.
An object can be defined as an entity, which consists of data members known as Properties and member function known as Methods, which act upon the data members.  Properties of an object can be accessed in the following manner.   Object.Property If a property of an object is an object by itself then it can be accessed in the following manner.   Object.Property.Property  Methods of an object can be accessed in the following manner.   Object.Method()

181 Summary The window object is an in built JavaScript object used for accessing the browser window. It is the top most object in the browser objects hierarchy. The document object is an inbuilt JavaScript object used to access the document displayed in the browser. It is used to access the contents displayed by head and body sections. The form object allows your script to interact with HTML forms and process the contents contained in it. The forms array, which is a property of the document object, can be used for accessing every form in the HTML document

182 Summary Every form can contain one or more of the following elements such as radio button, push button, checkbox, submit button, reset button, options menu and text area. Each element is an object and has its own properties and methods. The properties common to most of the form elements are given below.   name type value  The methods common to most of the form elements are given below.   blur() focus()

183 Session 9 Advanced JavaScript

184 Session Objectives Apply the Date object Use the Event object
Apply the Image object to dynamically load images Use the window object timeouts and time intervals  Use the document object Apply in-built JavaScript objects history, navigator and string objects

185 my_date The Date Object System Date & Time
The Date object provides methods to work with date and time. my_date = new Date() Creates a date object containing the system date and time System Date & Time

186 The Date Object Contd…..)
my_date Year Month Day Hours Minutes Seconds milliseconds my_date = new Date(year, month, day, hours, minutes, seconds, milliseconds) Other than Year and month all other parameters are optional Note : If the optional parameters are included, then it must be specified in the pre defined order.

187 Date Object (Functions)
Let us consider the functions : With the Eg : 01-Jan-2006 getDate( )  getDay( ) getMonth( )  getYear( ) getFullYear( ) Returns the day (01) of the month Returns the day of the week (6) Returns the month of the year (0) (‘0’ for January, ‘1’ for February till ‘11’ for December). Returns the year (00) Returns the year in four digit format ( YYYY) (2006)

188 Date Object (Functions) (Contd)
setMonth( ) setYear( ) setFullYear( ) sets the month of the year sets the year sets the year in four digit format (YYYY)

189 Date Object (Functions) (Contd)
getTime( ) getHours( ) getMinutes( ) getSeconds( ) Returns the time in milliseconds since midnight January 1, 1970 Returns the hours, minutes and seconds from Date object

190 Date Object (Functions) (Contd)
sets the hours, minutes and seconds for the Date object. setHours( ) setMinutes ( ) setSeconds( )

191 The Event Object Events are related to tasks that gets carried out by Keyboard and Mouse interface. The properties available to an event object depend upon the type of event that occurred. Mouse Move event Key Press event

192 Event Object (Properties)
height width screenX screenY The height and the width of the window in pixels. Mouse cursor’s X position in pixels. Mouse cursor’s Y position in pixels.

193 Event Object (Properties) (Contd….)
type determines the type of the event keypress click dblclick keyCode   identifies the UNICODE key code associated with the key press.

194 Event Object (Properties) (Contd…)
Buttons : Used to identify the mouse button that was pressed when an event occurred. Various possible values of this property are:   0                    No button 1                    Left mouse button 2                    Right mouse button 3                    Middle mouse button altKey, ctrlKey, shiftKey set to true or false indicating whether alt, ctrl or Shift keys were pressed when the event occurred.

195 The Image Object <HTML> <HEAD>
<TITLE> The Image object </TITLE> <SCRIPT LANGUAGE = “JavaScript”> img1 = new Image() img2 = new Image() img1.src = “but1.gif” img2.src = “but2.gif” The image object is used to dynamically work with images in a HTML document The image object has the following properties. src identifies the source of an image.

196 The Image Object (Contd)
height identifies the height of an image. specified in pixels or as percentage of the window’s height.    width identifies the width of an image. specified in pixels or as percentage of the window’s width. Complete identifies whether an image has been completely loaded in the browser or not  border identifies the thickness of an image border in pixels.

197 Window Object Used to dynamically open and close windows
Uses the open() and close() methods to open and close the browser window. open() method is used as variable = open(url, name, [options]) url URL of the file to be opened. name name of the window. options Characteristics of the window in which the url is opened. ( This is optional.) variable variable name to which the window object is associated.

198 Window Object (Contd) my_var=open("samp.html","win1”)
The open() method returns the window object, which is opened for displaying the specified URL.

199 my_var=open("samp.html","win1”,[option] )
Window Object (Contd) my_var=open("samp.html","win1”,[option] ) Option are given with values as listed below. More than one option, can be used with separated by commas and enclosed within double quotes.   Option Value Description toolbar Yes / no Tool bar of the window Menubar Yes / no Menu bar of the window status Yes / no Status bar of the window resizable Yes / no resized window or not width Integer Window width height Integer Window height

200 Closing a Window The close() method is used to close an Open window:
variable.close() variable: The variable which contains the window object Example : The following statement closes a window associated with the window object “win”   win.close()

201 Timeouts timeouts are used to execute function once after a specified time period. It uses the following methods setTimeout() setTimeout() method executes only once after the specified time period has elapsed.

202 Time Interval Time interval are used to execute function repeatedly after a specified time period has elapsed. It uses the following methods setInterval() setInterval( ) method is used for repeated execution after the specified time period has elapsed.

203 Setinterval( ) This method is used as follows :
variable= setInterval(expression, milliseconds)   or variable = setInterval(function, milliseconds)  It is used to evaluate the expression / function and assign the interval reference to the variable.

204 Setinterval( ) (Contd)
ref = setInterval(‘alert(“4 Seconds Over”)’,4000) used to display an alert dialog box with the message “4 Seconds Over” for every 4 seconds. ref = setInterval(“MyFunc()”, 4000) used to invoke the function MyFunc() for every 4 seconds.

205 Clearinterval()   The clearInterval() method of the window is used to undo the effect caused by setinterval() method ref = setInterval(“MyFunc()”, 4000) is used to define and invoke a timeinterval clearInterval(ref) is used to clear timeinterval

206 Settimeout() This method is used as follows :
variable= setTimeout(expression, milliseconds)   or variable = setTimeout(function, milliseconds)  It is used to evaluate the expression / function and assign the interval reference to the variable.

207 Settimeout( ) (Contd) ref = setTimeout(‘alert(“4 Seconds Over”)’,4000)
used to display an alert dialog box with the message “4 Seconds Over” for every 4 seconds. ref = setTimeout(“MyFunc()”, 4000) used to invoke the function MyFunc() for every 4 seconds.

208 Document Object Properties (Contd)
To access forms and alter the color settings of the document elements bgColor background colour of the document.   fgColor text colour in the document.   linkColor colour of the unvisited links.   alinkColor colour of a link while it is being activated.   vlinkColor Colour of visited links.

209 The History Object The history object represents the list of documents that the current window or frame has displayed. back() Loads the previous URL in the history list forward() Loads the next URL in the history list length It gives the length of the history list go() Loads an URL specified from a current place

210 The Navigator Object The navigator object provides the following information about the browser version and type

211 Declaration of Strings
String can be declared in two ways Using Single or double quotes Str = “This Is Sample String” The other way is to declare and initialize the string   Str = new String (“This Is Sample String”)

212 The String Object toLowerCase() converts the string to lowercase.
 toUpperCase() converts the string to uppercase myString=new String("This is first string. This is second string")   document.write(myString.substring(7)+"<BR>")   The statement returns the substring “first string. This is second string” from myString, which starts at index 8. document.write(myString.substring(5,13)+"<BR>") The statement returns the substring “is first” from myString, which starts at index 5 and ends at index 12.

213 The String Object document.write(myString.split('first')+"<BR>")
This statement converts myString into the following two sub strings “This is” and “string. This is second string” because the separator string is “first”.  document.write(myString.indexOf('first')+"<BR>") The following statement returns the index value of the pattern “first” from myString.

214 The String Object document.write("myString.charAt(8)\t\t:")
This statement returns the the letter “f” starting at 8th position in the given string. document.write(myString.charCodeAt(1)+"<BR>") This statement returns the ASCII value 104 of the letter “T”, which is at index 1.

215 Summary The Date object provides methods to work with date and time.
The Image object can be used to provide dynamic effect to images displayed in web pages. The images array, which is a property of the document object, can be used for accessing all the images in the web page. The event object was introduced with JavaScript 1.2 and is used for providing information about an event during execution.

216 Summary The setInterval() method evaluates a function or an
expression repeatedly for the specified number of milliseconds and it returns an interval reference. The setTimeout() method evaluates an expression or invokes a function after a timeout period has elapsed The open() and close() methods of the window object can be used from within JavaScript to open and close browser windows.

217 Summary The document object is used for accessing the various
components embedded in a web page, which is displayed in the browser window. The history object represents the list of documents that the current window has displayed. The navigator object provides information about the browser such as version number, type and other browser specific information. String object has functions to manipulate strings.

218 THANKS


Download ppt "Java Script Session1 INTRODUCTION."

Similar presentations


Ads by Google