JavaScript

71
JavaScript

description

JavaScript. JavaScript Basics. It is a Scripting Language invented by Netscape in 1995. It is a client side scripting language. - PowerPoint PPT Presentation

Transcript of JavaScript

Page 1: JavaScript

JavaScript

Page 2: JavaScript

JavaScript Basics It is a Scripting Language invented by Netscape in

1995. It is a client side scripting language.

Client-side scripting generally refers to the class of computer programs on the web that are executed client-side, by the user's web browser, instead of server-side (on the web server). This type of computer programming is an important part of the Dynamic HTML (DHTML) concept, enabling web pages to be scripted; that is, to have different and changing content depending on user input, environmental conditions (such as the time of day), or other variables

2

Page 3: JavaScript

3

Understanding Javascript

Javascript is used in million of web pages to

Improve design Validate forms Detect browsers Create cookies, etc.

Javascript is designed to add interactivity to HTML pages.

Page 4: JavaScript

Advantages of Javascript An Interpreted language Embedded within HTML Minimal Syntax Quick Development Designed for Simple, Small programs Performance Procedural capabilities Handling User events Easy Debugging and Testing Platform Independent

4

Page 5: JavaScript

5

JavaScript Basics

Prerequisites for learning javascript. Knowledge of basic HTML. You need a web browser. You need a editor. No need of special h/w or s/w or a web server.

Page 6: JavaScript

6

Understanding Javascript

Javascript is used in million of web pages to

Improve design Validate forms Detect browsers Create cookies, etc.

Javascript is designed to add interactivity to HTML pages.

Page 7: JavaScript

7

Understanding Javascript

Javascript is a scripting language developed by Netscape.

We can use nodepad, dreamweaver, golive .etc. for developing javascripts.

Page 8: JavaScript

8

HTML and Javascript

The easiest way to test a javascript program is by putting it inside an HTML page and loading it in a javascript enabled browser.

You can integrate javascript code into the HTML file in three ways

Integrating under <head> tag Integrating under <body> tag Importing the external javascript.

Page 9: JavaScript

9

HTML and Javascript

Integrating script under the <head> tag Javascript in the head section will execute

when called i.e javascript in the HTML file will execute immediately while the web page loads into the web browser before anyone uses it.

Page 10: JavaScript

10

HTML and Javascript

Integrating script under the <head> tag Syntax :- <html>

<head> <script type=“text/javascript” > ----------------- </script> </head> <body> </body> <html>

Page 11: JavaScript

11

HTML and Javascript

Integrating script under the <body> tag When you place the javascript code under

the <body> tag, this generates the content of the web page. Javascript code executes when the web page loads and so in the body section.

Page 12: JavaScript

12

HTML and Javascript

Integrating script under the <body> tag Syntax :- <html>

<head></head>

<body><script type=“text/javascript” >

----------------- </script> </body> <html>

Page 13: JavaScript

13

HTML and Javascript

Importing the External javascript You can import an external javascript file when

you want to run the same javascript file on several HTML files without having to write the same javascript code on every HTML file.

Save the external javascript file with an extension .js

The external javascript file don’t have a <script> tag.

Page 14: JavaScript

14

HTML and Javascript

Importing the external javascript Syntax :- <html>

<head><script src=“first.js” >

----------------- </script>

</head> <body>

</body> <html>

Page 15: JavaScript

15

First javascript program

The javascript code uses <script> </script> to start and end code.

The javascript code bounded with the script tags is not HTML to be displayed but rather script code to be processed.

Javascript is not the only scripting laguage, so you need to tell the browser which scripting language you are using so it knows how to process that language, so you specify <script type =“text/javascript”>

Page 16: JavaScript

16

First javascript program

Including type attribute is a good practice but browsers like firefox, IE, etc. use javascript as their default script language, so if we don’t specify type attribute it assumes that the scripting language is javascript.

However use of type attribute is specified as mandatory by W3C.

Page 17: JavaScript

17

First javascript program

<html><head> <title> first javascript </title>

</head>

<body><script type=“text/javascript” >

document.write(“First javascript stmt.”); </script>

</body> <html>

Page 18: JavaScript

18

Elements of javascript

Javascript statement Every statement must end with a enter

key or a semicolon. Example :-

<script type=“text/javascript” >document.write(“First javascript

stmt.”);

</script>

Page 19: JavaScript

19

Elements of javascript

Javascript statement blocks Several javascript statement grouped

together in a statement block. Its purpose is to execute sequence of

statements together. Statement block begins and ends with

a curly brackets.

Page 20: JavaScript

20

Elements of javascript

Example :-<script type=“text/javascript” >

{

document.write(“First javascript stmt.”);

document.write(“Second javascript stmt.”);

}

</script>

Page 21: JavaScript

21

Elements of javascript

Javascript comments It supports both single line and multi

line comments. // - Single line comments /*---------*/ - Multi line comments

Page 22: JavaScript

22

Elements of javascript

Example :-<script type=“text/javascript” > // javascript

code{

/* This code will write two statement in the single line. */

document.write(“First javascript stmt.”); document.write(“Second javascript stmt.”);

} </script>

Page 23: JavaScript

23

Variables

Basic syntax of variable declaration Syntax:- var variablename;

Naming conventions Variable name can start with a alphabet or underscore.

( Rest characters can be number, alphabets, dollar symbol, underscore )

Do not user any special character other than dollar sign ($), underscore (_)

Variable names are case-sensitive. Cannot contain blank spaces. Cannot contain any reserved word.

Page 24: JavaScript

24

Variables

Once you declare a variable you can initialise the variable by assigning value to it. Syntax:- variablename=value;

You can also declare and initialize the variable at the same time. Syntax:- var variablename=value;

Page 25: JavaScript

25

Variables

<html><head> <title> javascript variables </title> </head><body>

<script type=“text/javascript”> var bookname=“web tech and applications”;

var bookprice=390; document.write(“bookname is: ”,bookname);

document.write(“bookprice is: ”,bookprice);</script>

</body></html>

Page 26: JavaScript

26

Datatypes

Javascript supports three primitive types of values and supports complex types such as arrays and objects. Number :consists of integer and floating

point numbers. Interger literals can be represented in decimal,

hexadecimal and octal form. Floating literal consists of either a number

containg a decimal point or an integer followed by an exponent.

Page 27: JavaScript

27

Datatypes

Boolean :consists of logical values true and false. Javascript automatically converts

logical values true and false to 1 and 0 when they are used in numeric expressions.

Page 28: JavaScript

28

Datatypes

String :consists of string values enclosed in single or double quotes.

Examples:

var first_name=“Bhoomi”;

var last_name=“Trivedi”;

var phone=4123778;

var bookprice=450.40;

Page 29: JavaScript

29

Operators Arithmetic operators

Operator Action

+ Adds two numbers together

- Subtracts one number from another or changes a number to its negative

* Multiplies two numbers together

/ Divides one number by another

% Produces the remainder after dividing one number by another

Page 30: JavaScript

30

Operators Addition

JavaScript can add together two or more numeric variables and/or numeric constants by combining them in an arithmetic expression with the arithmetic operator for addition ( + ).

The result derived from evaluating an expression can be assigned to a variable for temporary memory storage.

The following statements declare variables A and B and assign them numeric values; variable Sum is declared for storing the result of evaluating the arithmetic expression that adds these two variables.

Example :- var A = 20;var B = 10;var Sum = A + B;var Sum1 = 1 + 2;var Sum2 = A + 2 + B + 1;var Sum3 = Sum1 + Sum2;

Page 31: JavaScript

31

Operators Other Arithmetic Operators

Operator Action

++ X++The equivalent of X = X + 1; add 1 to X, replacing the value of X

-- X--The equivalent of X = X - 1; subtract 1 from X, replacing the value of X

+= X += YThe equivalent of X = X + Y; add Y to X, replacing the value of X

-= X -= YThe equivalent of X = X - Y; subtract Y from X, replacing the value of X

*= X *= YThe equivalent of X = X * Y; multiply Y by X, replacing the value of X

/= X /= YThe equivalent of X = X / Y; divide X by Y, replacing the value of X

Page 32: JavaScript

32

Operators Relational Operators

ConditionalOperator

Comparison

== Equal operator.value1 == value2Tests whether value1 is the same as value2.

!= Not Equal operator.value1 != value2Tests whether value1 is different from value2.

< Less Than operator.value1 < value2Tests whether value1 is less than value2.

> Greater Than operator.value1 > value2Tests whether value1 is greater than value2.

<= Less Than or Equal To operator.value1 <= value2Tests whether value1 is less than or equal to value2.

>= Greater Than or Equal To operator.value1 >= value2Tests whether value1 is greater than or equal to value2.

Page 33: JavaScript

33

Operators Logical Operators

LogicalOperator

Comparison

&& And operator.condition1 && condition2The condition1 and condition2 tests both must be true for the expression to be evaluated as true.

|| Or operator.condition1 || condition2Either the condition1 or condition2 test must be true for the expression to be evaluated as true.

! Not operator.! conditionThe expression result is set to its opposite; a true condition is set to false and a false condition is set to true.

Page 34: JavaScript

34

If condition Syntax:-

if (conditional expression)

{ do this... }

Page 35: JavaScript

35

If – else condition Syntax:-

if (conditional expression)

{ do this... }

else

{ do this... }

Page 36: JavaScript

36

Nested if condition Syntax:-

if (conditional expression) { if (conditional expression) { do this... } else { do this... } } else { if (conditional expression) { do this... } else { do this... } }

Page 37: JavaScript

37

If..else if condition Syntax:-

if (conditional expression1) { do this... } else if (conditional expression2) { do this... } else if (conditional expression3) { do this... } ... [else {do this...}]

Page 38: JavaScript

38

The Switch Statement Syntax:-

switch (expression)

{

case "value1": do this...

break

case "value2": do this...

break

...

[ default: do this... ]

}

Page 39: JavaScript

39

Iterations For statement:-

for (exp1;exp2;exp3)

{

do this...

}

exp1:initial expression

exp2:conditional expression

exp3:incremental expression

Page 40: JavaScript

40

Iterations while statement:-

while (conditional expression)

{

do this...

}

Page 41: JavaScript

41

Iterations do …. while statement

do

{

do this...

}while (conditional expression)

Page 42: JavaScript

42

Array Array is a javascript object that is capable of

storing a sequence of values. Array declaration syntax :

arrayname = new Array(); arrayname = new Array(arraylength);

In the first syntax an of size zero is created. In the second syntax size is explicitly specified,

hence this array will hold a pre-determined set of values.

Page 43: JavaScript

43

Array Example :- bookname = new Array(); Note :- Even if array is initially created of a fixed

length it may still be extended by referencing elements that are outside the current size of the array.

Example :- cust_order = new Array();

cust_order[50] = “Mobile”;

cust_order[100] = “Laptop”;

Page 44: JavaScript

44

Array Dense Array

It is an array that has been created with each of its elements being assigned a specific value.

They are declared and initialized at the same time.

Syntax:- arrayname = new Array(value0,value1,……..

…,valuen); Example :-

Page 45: JavaScript

45

Array Array is a javascript object so it has several

methods associated with it. join() – it returns all elements of the array

joined together as a single string. By default “,” is used as a separator or you can specify the character to separate the array elements.

reverse() – it reverses the order of the elements in the array.

Page 46: JavaScript

46

Array Array is a javascript object so it has also properties

associated with it. length - it determines the total number of

elements. Example :- length = myarray.length;

Javascript values for array could me of any type Example :- myarr = new Array(“one”,”two”,1,2, true, new Array(3,4) );

Page 47: JavaScript

47

Special Operators Strict Equal (= = =)

Example “5” == 5 – true but “5” === 5 false It do not perform type conversion before testing for

equality. Ternary operators (? :)

Example :- condition ? Exp1 : Exp2 Delete operator

It is used to delete a property of an object or an element at an array index.

Example :- delete arrayname[5]

Page 48: JavaScript

48

Special Operators New operator

It is used to create an instance of object type. Example :- myarr = new Array();

Void operator It does not return a value It is specially used to return a URL with no value.

Page 49: JavaScript

49

Functions Functions are blocks of JS code that perform a

specific task and often return a value. Functions can be

Built in functions User defined functions

Built in functions Examples :

eval() parseInt() parseFloat()

Page 50: JavaScript

50

Functions eval

It is used to convert a string expression to a numeric value. Example :- var g_total = eval (“10 * 10 + 5”);

parseInt It is used to convert a string value to an integer. It returns the first integer contained in a string or “0” if the

string does not begin with an integer. Example :-

var str2no = parseInt(“123xyz”); //123

var str2no =parseInt(“xyz”); //NaN

Page 51: JavaScript

51

Functions parseFloat

It returns the first floating point number contained in a string or “0” if the string does not begin woth a valid floating point number.

Example :-

var str2no = parseFloat(“1.2xyz”); //1.2

Page 52: JavaScript

52

Functions User Defined functions

When defining user defined functions appropriate syntax needs to be followed for Declaring functions Invoking / calling functions Passing values Returning and accepting the return values

Page 53: JavaScript

53

Functions Function Declaration

Functions are declared and created using the function keyword.

A function can comprise of the following things, function name List of parameters Block of javascript code that defines what the function

does. Syntax :-

function function_name( P1, P2,………..,Pn)

{// Block of JS code

}

Page 54: JavaScript

54

Functions Place of declaration

Functions can be declared any where within an HTML file.

Preferably functions are created within the <head> tags.

This ensures that all functions will be parsed before they are invoked or called.

Page 55: JavaScript

55

Functions If the function is called before it is declared and

parsed, it will lead to an error condition as the function has not been evaluated and the browser does not know that it exists.

Parsed:- it refers to the process by which the JS interpreter evaluates each line of script code and converts it into a pseudo – compiled byte code before attempting to execute it.

At this time syntax errors and other programming mistakes that would prevent the script from running are trapped and reported.

Page 56: JavaScript

56

Functions Function call

A variable or a static value can be passed to a function.

Example:-printName(“Bhoomi”);

var firstname=“Bhoomi”;

printName(firstname);

Page 57: JavaScript

57

Functions Variable Scope

Any variable declared within the function is local to the function. Any variable declared outside the function is available to all the

statements within the JS code. Return Values

Use return statement to return a value or expression that evaluates to a single value.function cube(n){

var ans = n * n * n;return ans;

}

Page 58: JavaScript

58

Functions Recursive Functions

A function calls itself. Example :-

function factorial( n){

if ( n >1 )return n * factorial( n-

1);else

return n;}

Page 59: JavaScript

59

Dialog Boxes Dialog Boxes

JS provides the ability to pickup user input, display text to user by using dialog boxes.

These dialog boxes appear as separate windows and their content depends on the information provided by the user.

These content is independent of the text in the HTML page containing the JS code and does not affect the content of the page in any way.

There are three types of dialog boxes provided by JS, Alert dialog box Prompt dialog box Confirm dialog box

Page 60: JavaScript

60

Dialog Boxes Alert dialog box

It is used to display small amount of “textual output” to a browser window.

The alert DB displays the string passed to the alert() as well as an OK button.

It is used to display a “cautionary message” or “some information” for eg Display message when incorrect information is keyed in a

form. Display an invalid result as an output of a calculation. A warning that a service is not available on a given date/time.

Page 61: JavaScript

61

Dialog Boxes Syntax :- alert (“message”); Example :-<html>

<body><script type=“text/javascript”> alert(“This is a alert dialog box”);

document.write(“Hello”);</script>

</ body ></html>

Page 62: JavaScript

62

Page 63: JavaScript

63

Dialog Boxes Prompt Dialog Box Alert DB simply displays information in the

browser and does not allow any interaction. It halts program execution until some action

takes place. (i.e. click OK button) But it cannot be used to take input from user

and display output based on it. For this we use prompt DB.

Page 64: JavaScript

64

Dialog Boxes Prompt Dialog Box Prompt() display the following things

A predefined message. A textbox ( with a optional value) A OK and CANCEL button.

It also causes program execution to halt until action takes place. (i.e OK or CANCEL ) Clicking OK causes the text typed inside the textbox to

be passed to the program environment. Clicking CANCEL causes a Null value to be passed to

the environment.

Page 65: JavaScript

65

Dialog Boxes Prompt Dialog Box Syntax :- prompt( “msg”,”<default value>”); Example :-

<html><body>

<script type=“text/javascript”> var name;

name=prompt(“Enter you Name: ”,” “ “);document.write(“<br/>Name entered is : ”,name);

</script></ body >

</html>

Page 66: JavaScript

66

Page 67: JavaScript

67

Dialog Boxes Confirm Dialog Box Confirm() display the following things

A predefined message. A OK and CANCEL button.

It also causes program execution to halt until action takes place. (i.e OK or CANCEL ) Clicking OK causes true to be passed to the program,

which called Confirm DB. Clicking CANCEL causes false to be passed to the

program which called Confirm DB.

Page 68: JavaScript

68

Dialog Boxes Confirm Dialog Box Syntax :- confirm( “message”); Example :-

<html><body>

<script type=“text/javascript”> var ans;

ans=confirm(“Are you sure want to exit ? “);if ( ans == true )

document.write(“ you pressed OK”);else

document.write(“ you pressed CANCEL”);

</script></ body >

</html>

Page 69: JavaScript

69

Page 70: JavaScript

70

Page 71: JavaScript

71

Events Events

Event Handler Event

onclick The mouse button is clicked and released with the cursor positioned over a page element.

ondblclick The mouse button is double-clicked with the cursor positioned over a page element.

onmousedown The mouse button is pressed down with the cursor positioned over a page element.

onmousemove The mouse cursor is moved across the screen.

onmouseout The mouse cursor is moved off a page element.

onmouseover The mouse cursor is moved on top of a page element.

onmouseup The mouse button is released with the cursor positioned over a page element.