Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Script Session1 INTRODUCTION. Session Objectives Describe JavaScript Differentiate between Client-Side and Server- Side Applications Differentiate.

Similar presentations


Presentation on theme: "Java Script Session1 INTRODUCTION. Session Objectives Describe JavaScript Differentiate between Client-Side and Server- Side Applications Differentiate."— 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 VersionBrowser Support Javascript 1.0Navigator 2.0 JavaScript 1.1Navigator 3.0 JavaScript 1.2Navigator JavaScript 1.3Navigator

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. Have Fun

8 Java Script in a Browser (2) alert(“Welcome to the world of JavaScript”);

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 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: JavaScript statements

22 Using the SCRIPT tag(3) JavaScript statements must be terminated with a semi-colon (;). document.write(“Welcome to the world of JavaScript”); Enjoy learning

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. 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 (1) If the browser does not support JavaScript, you can make use of the tag. The browser will display HTML enclosed within a tag in plain text. Browsers that support JavaScript ignore the code within this tag.

27 Using (2) The following example shows a tag. document.write(“Having fun”);

28 Using (3) The browser does not support JavaScript Click Here

29 Using (4) If your browser supports JavaScript, check the browser configuration to see if it is enabled.

30 Using (5) Using NOSCRIPT

31 Displaying Information(1) Using write and writeln object.write(string) Using Methods document.write (“Are you having fun?”)

32 Displaying Information(2) object.writeln(string) function doloop() { var String1 = ‘



33 Displaying Information(3) for (var size = 5; size <= 100; size+=5) document.writeln(String1 + size + ‘%”>’); document.close(); }

34 Using Alert(1) object.alert([message]) alert (“Click OK to reboot the computer”);

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]) confirm (“Do you want to continue?”);

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 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 Every data used in program should be declared first to be of a particular type 10, - 67,14.45, Jack, michal and joe TRUE, FALSE Names Boolean values Numbers

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 BaseRepresentationExample Decimal10Sequence of digits ( 0 – 9)35, -63 Octal8Sequence of digits ( 0 – 7) with a leading Hexa16Sequence 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 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 \ ’ \ ” \ \ \ r \ f \ n \ b \ t Single Quote Double Quote Back Slash Carriage Return Form Feed New Line Back Space Tab  Escape sequences should be used only with 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 ? VALUE = ?  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

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 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 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 OperatorUsageInference +=A+= BA = A + B -=A-=BA = A – B *=A*=BA = A * B /=A /= BA = 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 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 Logical Comparison Arithmetic AND, OR & NOT = = == != + - * / % Used in any Arithmetic calculation Used to compare two elements on its value Complex Operations based on combination of comparison / condition

68 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. 1-Negation 2 */%*/% Multiplication Division Modulus Addition Subtraction Arithmetic Operators

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

70 Logical Operators OperatorSymbol AND&& OR|| NOT!

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

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

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 OperatorOperationActionResult <>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 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 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. If ( ) Set of statements to be executed if the condition is true else Set of statements to be executed if the condition is false

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 else If (condition 3 ) Statements to be executed if the condition is true endif Condition 1 is true Condition 1 is false Condition 2 is true Condition 2 is false Condition 3 is true

83 Loops 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…… Start Initialise counter variable …… Yes No is counter variable = expected no. statements End

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

85 Nested FOR Loops 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 ………….. for (i=1; i<10; i++) { Cube = 1 Read Number for(j=1; j<3; j++) { Cube=Cube* Number } Print Number, Cube } ………….

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 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 While Construct 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 Yes Condition = ? statements to be executed until the condition is met Start ……. ……. End

92 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. No Yes Condition = ? statements to be executed until the condition is met Start ……. ……. End Do While construct

93 Continue statement 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 Yes Condition = ? Other loop statements Start ……. End Continue Statements to be executed before the condition

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…]. Read Num1 Num2 OPR + - * / Branching based upon opr value Ans = Num1 + Num2 Ans = Num1 - Num2 Ans = Num1 * Num2 Ans = Num1 / Num2 Default Not a valid opr

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

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 Working with Arrays Session 5

104 Session Objectives Identify the need for 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 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 1. Start 2. Declare num1, num2, num3, num4, num5 and sum as integers 3. Accept num1 4. Accept num2 5. Accept num3 6. Accept num4 7. Accept num5 8. Sum = num1 + num2 + num3 + num4 + num5 9. Display sum 10. 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 : JAVASCRIPT An Array of Characters

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. JAVASCRIPT Array of Characters Array of Numbers Prglang[9] digits[9]

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

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. num[0] :- index starts at Num(0)Num(1)Num(2)Num(3)Num(4) Array index

112 Using Arrays 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  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. Example : To find the sum of 5 nos. using array Advantages

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 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 Num(4)

116 Multi-Dimensional Array Two- Dimensional Array is declared in terms of rows and columns Used to store tabular data Marks [Rowpos][Colpos] PhysicsMathsScience Julia Ben Tom Demi To store marks in 3 subjects for 4 students.

117 Multi-dimensional Array [Contd…] To access an element of a multi- dimensional array var X = Marks[0][1] Value 60 is assigned to variable name X PhysicsMathsScience Julia Ben Tom Dem i Marks[3][3]  rows are student names  columns are subjects

118 Dense Arrays When an array is initialized during declaration itself, it is known as “Dense Array”. Days = new Array(“Mon”,”Tue”,”Wed”,”Thu”,”Fri”,”Sat”,”Sun”) MonTueWedThuFriSatSun 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 MonTueWedThuFriSatSun

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

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

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

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

124 Nested Arrays Arrays can be stored as other array’s element Arr3Arr1[0]Arr1[1]Arr1[2]Arr1[3]Arr1[4]Arr2 Arr Arr The length of Arr1 is 5 and the sum of elements is 150 The length of Arr2 is 5 and the sum of elements is 65 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); JunkHelloWorld Truefalse document.write( Junk[0]+Junk[1]); Concatenates and returns “HelloWorld”  document.write( Junk[2]+Junk[3]); Sums up the values and returns  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 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. Summary

128 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. Summary

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 Func 2 Func1 Func 3 1.Start 2.Func1() 3.Func2() 4.Func3() 4. End Function names Function definition Statements within Function Function Calling statements

133 Invoking a Function 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 1 Start 2 if (grade != 3) PF =.06 * basic else PF = 0 end if 3 return Program Function PF_CAL() Function PF-Calc() Is invoked

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

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 Ans can be accessed from the block where it is defined only. Sum Function function Sum(num1, num2) { var ans = num1 + num2 document.write (“The sum is ” + ans) } Function to add two numbers Sum (1,2)

138 Global Variables Local and Global variables function Sample() { Sum = 1 } Sample() document.write ("The value of the variable global Sum is" + Sum) Sum can be accessed from anywhere in the program

139 Function Libraries 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. MATH Avg() – to calculate average Sqrt() – to calculate square root Date and Time Fetch the system date and time  Extract the month from a date Calculate the days between two dates

140 Functions With Varying Arguments Sum Function function Sum () { var len = Sum.arguments.length var ans = 0 for (i=0; i

141 Function - Returning Values function Sum is invoked to return Value of ans (3) to variable total Sum Function function Sum(num1, num2) { var ans = num1 + num2 return ans } Function to add two numbers var total = Sum (1,2) document.write (“The sum is” + 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 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. Summary

144 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 Mouse Move Key Press event code for Mouse move event code for Key Press event execute Event handlers

148 Triggering Events 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 :  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 mouseOver is an event which is generated every time the mouse is placed over a hyper link Eg ‘++num; alert(“Number : ”+num)’

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

152 Event Handling Attribute EventEvent handling attribute clickonClick dbClickonDbClick mouseUponMouseUp mouseDownonMouseDown mouseOveronMouseOver keyDownonKeyDown Mouse events Keyboard Events

153 The above events gets generated when the user interacts with the hypertext Link Events HTML Element HTML Tag JavaScript Event Description Link clickLeft mouse button is clicked on a link dbClickLeft mouse button is double clicked on a link mouseOverMouse cursor is placed over the link mouseDownLeft mouse button is pressed mouseUp Left mouse button is released keyDownKey is pressed

154 Body Events HTML element HTML tag JavaScript event Description Document 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 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 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 blur focus change select Password Field blur, focus

158 other events (Contd.) Button click mouseDown mouseUp blur focus Submit click blur focus

159 other events (Contd.) Reset click blur focus Radio Button click blur focus

160 other events (Contd.) Checkbox click blur focus Selection blur focus change

161 other events (Contd.) 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 Events in JavaScript can be broadly classified as follows: Events associated with tag Events are also associated with other HTML elements such as buttons, text field, password field, text area, selection, submit and reset buttons. Summary

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 interactive web pages processing capabilities to HTML forms objects to manipulate web pages simpler than CGI scripts hybrid HTML and a Programming language JavaScript – Features

168 Browser Objects Browser 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

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)  Example document.write( “ Some Display Text ” ) JavaScript assumes the current window object and executes window.document.write(“Some Display Text”)

171 Document Object  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 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 PropertiesMethods buttonnameclick() typeblur() valuefocus()

175 Form Elements (Properties & Methods)[Contd…] Element Object PropertiesMethods textnameselect() typeblur() valuefocus() Default Value Handling Form Events First Name : Last Name :

176 Form Elements (Properties & Methods)[Contd…] Element Object PropertiesMethods checkboxcheckedclick() nameblur() typefocus() value default Value

177 Form Elements (Properties & Methods)[Contd…] Element ObjectPropertiesMethods checkboxnameblur() typefocus() length selectedIndex options

178 Form Elements (Properties & Methods)[Contd…] Hobbies Reading Books Listening to Music Trekking Painting

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 Basic form processing Your Name Your Password

180 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() Summary

181 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 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() Summary

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 The Date Object 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 my_date System Date & System Time

186 The Date Object Contd…..) 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. my_date Year Month Day Hours Minutes Seconds milliseconds

187 Date Object (Functions) 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) Let us consider the functions : With the Eg : 01-Jan-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 (Y YYY)

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) setHours( ) setMinutes ( ) setSeconds( ) sets the hours, minutes and seconds for the Date object.

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 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. The Image object img1 = new Image() img2 = new Image() img1.src = “but1.gif” img2.src = “but2.gif”

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]) urlURL of the file to be opened. namename of the window. options Characteristics of the window in which the url is opened. ( This is optional.) variablevariable name to which the window object is associated.

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

199 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. OptionValue Description toolbarYes / noTool bar of the window MenubarYes / noMenu bar of the window statusYes / noStatus bar of the window resizableYes / noresized window or not widthIntegerWindow width heightIntegerWindow 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)+" ") The statement returns the substring “first string. This is second string” from myString, which starts at index 8. document.write(myString.substring(5,13)+" ") 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')+" ") 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')+" ") 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 8 th position in the given string. document.write(myString.charCodeAt(1)+" ") 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. Session Objectives Describe JavaScript Differentiate between Client-Side and Server- Side Applications Differentiate."

Similar presentations


Ads by Google