Java Script o o A highlevel programming language

  • Slides: 159
Download presentation
Java. Script

Java. Script

o o A high-level programming language that is interpreted by another program at runtime

o o A high-level programming language that is interpreted by another program at runtime rather than compiled by the computer's processor as other programming languages (such as C and C++) are. Scripting languages, which can be embedded within HTML, commonly are used to add functionality to a Web page, such as different menu styles or graphic displays or to serve dynamic advertisements. These types of languages are client-side scripting languages, affecting the data that the end user sees in a browser window. Other scripting languages are server-side scripting languages that manipulate the data, usually in a database, on the server. Scripting languages came about largely because of the development of the Internet as a communications tool. Java. Script, ASP, JSP, PHP, Perl, Tcl and Python are examples of scripting languages. 2

Java. Script Basics o o It is a Scripting Language invented by Netscape in

Java. Script Basics o o It is a Scripting Language invented by Netscape in 1995. It is a client side scripting language. n o 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 Sometimes Java. Script is referred to as ECMAscript, ECMA is European Computer Manufacturers Association, it is a private organization that develops standards in information and communication systems. 3

Understanding Javascript n Javascript is used in million of web pages to n n

Understanding Javascript n Javascript is used in million of web pages to n n n Improve design Validate forms Detect browsers Create cookies, etc. Javascript is designed to add interactivity to HTML pages. 4

Java. Script Basics o Prerequisites for learning javascript. n n Knowledge of basic HTML.

Java. Script Basics o Prerequisites for learning javascript. n n 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. 5

Understanding Javascript n n Javascript is a scripting language developed by Netscape. We can

Understanding Javascript n n Javascript is a scripting language developed by Netscape. We can use nodepad, dreamweaver, golive etc. for developing javascripts. 6

HTML and Javascript o o The easiest way to test a javascript program is

HTML and Javascript o o 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 o o o Integrating under <head> tag Integrating under <body> tag Importing the external javascript. 7

HTML and Javascript o Integrating script under the <head> tag n Javascript in the

HTML and Javascript o Integrating script under the <head> tag n 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. 8

HTML and Javascript o o Integrating script under the <head> tag Syntax : -

HTML and Javascript o o Integrating script under the <head> tag Syntax : - <html> <head> <script type=“text/javascript” > -------- </script> </head> <body> </body> <html> 9

HTML and Javascript o Integrating script under the <body> tag n When you place

HTML and Javascript o Integrating script under the <body> tag n 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. 10

HTML and Javascript o o Integrating script under the <body> tag Syntax : -

HTML and Javascript o o Integrating script under the <body> tag Syntax : - <html> <head> </head> <body> </body> <html> <script type=“text/javascript” > --------</script> 11

HTML and Javascript o Importing the External javascript n n n You can import

HTML and Javascript o Importing the External javascript n n n 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. 12

HTML and Javascript o o Importing the external javascript Syntax : - <html> <head>

HTML and Javascript o o Importing the external javascript Syntax : - <html> <head> <script src=“first. js” > --------</script> </head> <body> </body> <html> 13

First javascript program o o o The javascript code uses <script> </script> to start

First javascript program o o o 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”> 14

First javascript program o o Including type attribute is a good practice but browsers

First javascript program o o 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 W 3 C. 15

First javascript program <html> <head> <title> first javascript </title> </head> <body> <script type=“text/javascript” >

First javascript program <html> <head> <title> first javascript </title> </head> <body> <script type=“text/javascript” > document. write(“First javascript stmt. ”); </script> </body> <html> 16

Elements of javascript o Javascript statement n n Every statement must end with a

Elements of javascript o Javascript statement n n Every statement must end with a enter key or a semicolon. Example : <script type=“text/javascript” > document. write(“First javascript stmt. ”); </script> 17

Elements of javascript o Javascript statement blocks n n n Several javascript statement grouped

Elements of javascript o Javascript statement blocks n n n 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. 18

Elements of javascript n Example : - <script type=“text/javascript” > { document. write(“First javascript

Elements of javascript n Example : - <script type=“text/javascript” > { document. write(“First javascript stmt. ”); document. write(“Second javascript stmt. ”); } </script> 19

Elements of javascript o Javascript comments n n n It supports both single line

Elements of javascript o Javascript comments n n n It supports both single line and multi line comments. // - Single line comments /*-----*/ - Multi line comments 20

Elements of javascript n Example : - <script type=“text/javascript” > // javascript code {

Elements of javascript n 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> 21

Variables o Basic syntax of variable declaration n o Syntax: - variablename; Naming conventions

Variables o Basic syntax of variable declaration n o Syntax: - variablename; Naming conventions n n n Variable name can start with a alphabet or underscore. ( Rest characters can be number, alphabets, dollar symbol, underscore ) Do not use any special character other than dollar sign ($), underscore (_) Variable names are case-sensitive. Cannot contain blank spaces. Cannot contain any reserved word. 22

 Java. Script Reserved Words abstract boolean break byte case catch char class const

Java. Script Reserved Words abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false finally float for function goto if implements import in instanceof interface long native new null package private protected public return short static super switch synchronized this throws transient true try typeof var void volatile while with 23

Variables o Once you declare a variable you can initialize the variable by assigning

Variables o Once you declare a variable you can initialize the variable by assigning value to it. n o Syntax: - variablename=value; You can also declare and initialize the variable at the same time. n Syntax: - variablename=value; 24

Variables <html> <head> <title> javascript variables </title> </head> <body> <script type=“text/javascript”> var bookname=“web tech

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> 25

Datatypes o Javascript supports three primitive types of values and supports complex types such

Datatypes o Javascript supports three primitive types of values and supports complex types such as arrays and objects. n Number : consists of integer and floating point numbers. o o Integer 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. 26

Datatypes o Boolean : consists of logical values true and false. n Javascript automatically

Datatypes o Boolean : consists of logical values true and false. n Javascript automatically converts logical values true and false to 1 and 0 when they are used in numeric expressions. 27

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

Datatypes String : consists of string values enclosed in single or double quotes. o Examples: var first_name=“Bhoomi”; var last_name=“Trivedi”; var phone=4123778; var bookprice=450. 40; o 28

Operators o Arithmetic operators Operator Action + Adds two numbers together - Subtracts one

Operators o 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 29

Operators o Addition n n Java. Script can add together two or more numeric

Operators o Addition n n Java. Script 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 Sum 1 = 1 + 2; var Sum 2 = A + 2 + B + 1; var Sum 3 = Sum 1 + Sum 2; 30

Operators o Other Arithmetic Operators Operator Action ++ X++ The equivalent of X =

Operators o 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 += Y The equivalent of X = X + Y; add Y to X, replacing the value of X -= Y The equivalent of X = X - Y; subtract Y from X, replacing the value of X *= Y The equivalent of X = X * Y; multiply Y by X, replacing the value of X /= Y The equivalent of X = X / Y; divide X by Y, replacing the value of X 31

Operators o Relational Operators Conditional Operator Comparison == Equal operator. value 1 == value

Operators o Relational Operators Conditional Operator Comparison == Equal operator. value 1 == value 2 Tests whether value 1 is the same as value 2. != Not Equal operator. value 1 != value 2 Tests whether value 1 is different from value 2. < Less Than operator. value 1 < value 2 Tests whether value 1 is less than value 2. > Greater Than operator. value 1 > value 2 Tests whether value 1 is greater than value 2. <= Less Than or Equal To operator. value 1 <= value 2 Tests whether value 1 is less than or equal to value 2. >= Greater Than or Equal To operator. value 1 >= value 2 Tests whether value 1 is greater than or equal to value 2. 32

Operators o Logical Operators Logical Operator Comparison && And operator. condition 1 && condition

Operators o Logical Operators Logical Operator Comparison && And operator. condition 1 && condition 2 The condition 1 and condition 2 tests both must be true for the expression to be evaluated as true. || Or operator. condition 1 || condition 2 Either the condition 1 or condition 2 test must be true for the expression to be evaluated as true. ! Not operator. ! condition The expression result is set to its opposite; a true condition is set to false and a false condition is set to true. 33

If condition o Syntax: if (conditional expression) { do this. . . } 34

If condition o Syntax: if (conditional expression) { do this. . . } 34

If – else condition Syntax: if (conditional expression) { do this. . . }

If – else condition Syntax: if (conditional expression) { do this. . . } else { do this. . . } o 35

Nested if condition Syntax: if (conditional expression) { do this. . . } else

Nested if condition Syntax: if (conditional expression) { do this. . . } else { do this. . . } else { if (conditional expression) { do this. . . } else { do this. . . } o 36

If. . else if condition o Syntax: - if (conditional expression 1) { do

If. . else if condition o Syntax: - if (conditional expression 1) { do this. . . } else if (conditional expression 2) { do this. . . } else if (conditional expression 3) { do this. . . } . . . [else {do this. . . }] 37

The Switch Statement Syntax: switch (expression) { case "value 1": do this. . .

The Switch Statement Syntax: switch (expression) { case "value 1": do this. . . break case "value 2": do this. . . break . . . [ default: do this. . . ] } o 38

Iterations For statement: for (exp 1; exp 2; exp 3) { do this. .

Iterations For statement: for (exp 1; exp 2; exp 3) { do this. . . } exp 1: initial expression exp 2: conditional expression exp 3: incremental expression o 39

Iterations while statement: while (conditional expression) { do this. . . } o 40

Iterations while statement: while (conditional expression) { do this. . . } o 40

Iterations do …. while statement do { do this. . . }while (conditional expression)

Iterations do …. while statement do { do this. . . }while (conditional expression) o 41

Array o o Array is a javascript object that is capable of storing a

Array o o Array is a javascript object that is capable of storing a sequence of values. Array declaration syntax : n n n o o var array-name = [item 1, item 2, . . . ]; arrayname = new Array(); // var arrayname = []; arrayname = new Array(arraylength); In the second syntax an array of size zero is created. In the third syntax size is explicitly specified, hence this array will hold a pre-determined set of values. 42

Array o Examples of array declaration n n o var cars = ["Saab", "Volvo",

Array o Examples of array declaration n n o var cars = ["Saab", "Volvo", "BMW"]; var cars = new Array("Saab", "Volvo", "BMW"); Access the Elements of an Array n n n var name = cars[0]; cars[0] = "Opel"; var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[10] = "Lemon"; // adds a new element (Lemon) to fruits 43

Array o o o Example : - bookname = new Array(); Note : -

Array o o o 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”; 44

Array o Dense Array n It is an array that has been created with

Array o Dense Array n It is an array that has been created with each of its elements being assigned a specific value. n They are declared and initialized at the same time. n Syntax: - arrayname = new Array(value 0, value 1, ……. . …, valuen); 45

Array o Array is a javascript object so it has several methods associated with

Array o Array is a javascript object so it has several methods associated with it. n 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. n reverse() – it reverses the order of the elements in the array. 46

Array o Array is a javascript object so it has also properties associated with

Array o Array is a javascript object so it has also properties associated with it. n length - it determines the total number of elements. n Example : - length = myarray. length; o Javascript values for array could be of any type n Example : - myarr = new Array(“one”, ”two”, 1, 2, true, new Array(3, 4) ); 47

Special Operators o Strict Equal (= = =) n n o Ternary operators (?

Special Operators o Strict Equal (= = =) n n o Ternary operators (? : ) n o Example “ 5” == 5 – true but “ 5” === 5 false It do not perform type conversion before testing for equality. Example : - condition ? Exp 1 : Exp 2 Delete operator n n It is used to delete a property of an object or an element at an array index. Example : - delete arrayname[5] 48

Special Operators o New operator n n o It is used to create an

Special Operators o New operator n n o It is used to create an instance of object type. Example : - myarr = new Array(); Void operator n n It does not return a value It is specially used to return a URL with no value. 49

Functions o o Functions are blocks of JS code that perform a specific task

Functions o o Functions are blocks of JS code that perform a specific task and often return a value. Functions can be n n o Built in functions User defined functions Built in functions n Examples : o o o eval() parse. Int() parse. Float() 50

Functions o eval n n o It is used to convert a string expression

Functions o eval n n o It is used to convert a string expression to a numeric value. Example : - var g_total = eval (“ 10 * 10 + 5”); parse. Int n n n 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 str 2 no = parse. Int(“ 123 xyz”); //123 51 var str 2 no =parse. Int(“xyz”); //Na. N

Functions o parse. Float n n It returns the first floating point number contained

Functions o parse. Float n n It returns the first floating point number contained in a string or “ 0” if the string does not begin with a valid floating point number. Example : var str 2 no = parse. Float(“ 1. 2 xyz”); //1. 2 52

Functions o User Defined functions n When defining user defined functions appropriate syntax needs

Functions o User Defined functions n When defining user defined functions appropriate syntax needs to be followed for o o Declaring functions Invoking / calling functions Passing values Returning and accepting the return values 53

Functions o Function Declaration n Functions are declared and created using the function keyword.

Functions o Function Declaration n Functions are declared and created using the function keyword. A function can comprise of the following things, o function name o List of parameters o Block of javascript code that defines what the function does. Syntax : function_name( P 1, P 2, ………. . , Pn) { // Block of JS code } 54

Functions o Place of declaration n Functions can be declared any where within an

Functions o Place of declaration n Functions can be declared any where within an HTML file. n Preferably functions are created within the <head> tags. n This ensures that all functions will be parsed before they are invoked or called. 55

Functions o o o If the function is called before it is declared and

Functions o o o 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. 56

Functions o Function call n n A variable or a static value can be

Functions o Function call n n A variable or a static value can be passed to a function. Example: print. Name(“Bhoomi”); var firstname=“Bhoomi”; print. Name(firstname); 57

Functions o Variable Scope n n o Any variable declared within the function is

Functions o Variable Scope n n o 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 n Use return statement to return a value or expression that evaluates to a single value. function cube(n) { var ans = n * n; return ans; } 58

Functions o Recursive Functions n A function calls itself. n Example : function factorial(n)

Functions o Recursive Functions n A function calls itself. n Example : function factorial(n) { if ( n >1 ) return n * factorial(n-1); else return n; } 59

Dialog Boxes o Dialog Boxes n JS provides the ability to pickup user input,

Dialog Boxes o Dialog Boxes n JS provides the ability to pickup user input, display text to user by using dialog boxes. n These dialog boxes appear as separate windows and their content depends on the information provided by the user. n 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. n There are three types of dialog boxes provided by JS, n n n Alert dialog box Prompt dialog box Confirm dialog box 60

Dialog Boxes o Alert dialog box n It is used to display small amount

Dialog Boxes o Alert dialog box n It is used to display small amount of “textual output” to a browser window. n The alert DB displays the string passed to the alert() as well as an OK button. n It is used to display a “cautionary message” or “some information” for eg. o o o 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. 61

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

Dialog Boxes o o Syntax : - alert (“message”); Example : - <html> <body> <script type=“text/javascript”> alert(“This is a alert dialog box”); document. write(“Hello”); </script> </ body > </html> 62

Alert Dialog Box : Example 63

Alert Dialog Box : Example 63

Dialog Boxes o Prompt Dialog Box n n Alert DB simply displays information in

Dialog Boxes o Prompt Dialog Box n n 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. 64

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

Dialog Boxes o Prompt Dialog Box n Prompt() display the following things o o o n 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 ) o o 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. 65

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

Dialog Boxes o Prompt Dialog Box n Syntax : - prompt( “msg”, ”<default value>”); n Example : - <html> <body> <script type=“text/javascript”> var name; name=prompt(“Enter you Name: ”, ” “ “); document. write(“<br/>Name entered is : ”, name); </script> </ body > </html> 66

Prompt Dialog Box : Example 67

Prompt Dialog Box : Example 67

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

Dialog Boxes o Confirm Dialog Box n Confirm() display the following things o o n A predefined message. A OK and CANCEL button. It also causes program execution to halt until action takes place. (i. e OK or CANCEL ) o o 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. 68

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

Dialog Boxes o Confirm Dialog Box n n 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> 69

Confirm Dialog Box : Example 70

Confirm Dialog Box : Example 70

Different types of Objects o W 3 C DOM objects n n o Built-in

Different types of Objects o W 3 C DOM objects n n o Built-in objects n n o In recent browsers several objects are made available to allow more control over a document. Eg : - navigator, window, document, form, etc. Several objects are part of JS language itself. These include the date, string and math objects. Custom objects n JS allows you to create your own objects that can contain related functionality.

Java. Script Object Hierarchy

Java. Script Object Hierarchy

W 3 C DOM objects o To access a documents property or method the

W 3 C DOM objects o To access a documents property or method the general syntax is as follows, n n o objectname. property objectname. method() Document object n Property : - alinkcolor, bgcolor, fgcolor, lastmodified, linkcolor, referrer, title, vlinkcolor. o n Example : - document. last. Modified Method : - write(str) , writeln(str)

W 3 C DOM objects o Form object n Property : - action, method,

W 3 C DOM objects o Form object n Property : - action, method, length, name, target o o n action- it points to the address of a program on the web server that will process the form data captured and being sent back. method – it is used to specify the method used to send data captured by various form elements back to the web server. Method : - reset(), submit()

75

75

HTML form elements o o o text – a text field ( <input type=“text”

HTML form elements o o o text – a text field ( <input type=“text” /> ) password – a password field in which keystrokes appear as an asterisk ( <input type=“password” /> ) button – it provides a button other than submit and reset. ( <input type=“button” /> ) checkbox – a checkbox. ( <input type=“checkbox” /> ) radio – a radio button. ( <input type=“radio” /> )

HTML form elements o o o reset – a reset button (<input type=“reset” />

HTML form elements o o o reset – a reset button (<input type=“reset” /> ) submit – a submit button ( <input type=“submit” /> ) select – a selection list. ( <select> <option> option 1 </option> <option> option 2 </option> </select> ) o o textarea – a multiline text entry field. ( <textarea rows=n cols=n > </textarea>) hidden – a field that may contain a value but is not displayed within a form. ( <input type=“hidden” /> )

Properties of form elements Property Name name value Form element name Description Text, password,

Properties of form elements Property Name name value Form element name Description Text, password, texta rea, button, radio, che ckbox, select, submit, reset, hidden Indicates the name of the object. Indicates the current value of the object.

Properties of form elements Property Name Form element name defaultvalue Text, password, textarea checked

Properties of form elements Property Name Form element name defaultvalue Text, password, textarea checked Radio button , checkbox Description Indicates the default value of the object. Indicates the current status of the object. (checked/unchecked) defaultchecked Radio button , Indicates the default checkbox status of the element.

Properties of form elements Property Name Form element Description name length Radio Indicates the

Properties of form elements Property Name Form element Description name length Radio Indicates the number of radio buttons in the group. index Radio button , Indicates the index of select currently selected radio button or option. text select Contains the value of the text.

Properties of form elements Property Name Form element Description name selectindex select Contains the

Properties of form elements Property Name Form element Description name selectindex select Contains the index number of the currently selected option. defaultselected select Indicates whether the option is selected by default in the option tag selected select Indicates the current status of the option.

Events on form elements Method Name Form element name on. Focus() Text, password, text

Events on form elements Method Name Form element name on. Focus() Text, password, text area on. Blur() Text, password, text area on. Select() Text, password, text area Description Fires when the form cursor enters into an object. Fires when the form cursor is moved away from an object. Fires when text is selected in an object.

Events on form elements Method Name Form element name on. Change() Text, password, text

Events on form elements Method Name Form element name on. Change() Text, password, text area on. Click() Button, radio, checkbox, submit, reset Description Fires when the text is changed in an object. Fires when an object is clicked on.

Events o Events Event Handler Event onclick The mouse button is clicked and released

Events o 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. 84

Example o Accept any mathematical expression evaluate and display the result. <html> <head> <script

Example o Accept any mathematical expression evaluate and display the result. <html> <head> <script type =“text/javascript”> function calculate(form){ form. result. value=eval(form. entry. value); } </script> </head> <body> <form> Enter a mathematical expression <input type=“text” name=“entry” /> <input type=“button” value=“Calculate” on. Click=calculate(this. form) /> <input type=“text” name=“result” /> </form> </body> </html>

Built-in objects o o o String object Date object Math object

Built-in objects o o o String object Date object Math object

String object o o o Every string in an javascript is an object. So

String object o o o Every string in an javascript is an object. So it also has property and methods. Property : length Property length Description Returns the number of characters in a string: Text. String. length "A text string". length Returns 13

Method bold() italics() strike() sub() sup() to. Lower. Case() Description Returns Changes the text

Method bold() italics() strike() sub() sup() to. Lower. Case() Description Returns Changes the text in a string to bold. Text. String. bold() "A text string". bold() A text string Changes the text in a string to italic. Text. String. italics() "A text string". italics() A text string Changes the text in a string to strike-through characters. Text. String. strike() "A text string". strike() A text string Changes the text in a string to subscript. "Subscript" + Text. String. sub() "Subscript" + "A text string". sub() Subscript. A text string Changes the text in a string to superscript. "Superscript" + Text. String. sup() "Superscript" + "A text string". sup() Superscript. A text string Changes the text in a string to lower-case. Text. String. to. Lower. Case() "A text string". to. Lower. Case() a text string

to. Upper. Case() fixed() fontcolor ("color") fontsize("n") link("href") Changes the text in a string

to. Upper. Case() fixed() fontcolor ("color") fontsize("n") link("href") Changes the text in a string to upper-case. Text. String. to. Upper. Case() "A text string". to. Upper. Case() Changes the text in a string to fixed (monospace) font. Text. String. fixed() "A text string". fixed() Changes the color of a string using color names or hexadecimal values. Text. String. fontcolor("blue") Text. String. fontcolor("#0000 FF") "A text string". fontcolor("blue") "A textstring". fontcolor("#0000 FF") A TEXT STRING A text string Changes the size of a string using font sizes 1 (smallest) - 7 (largest). Text. String. fontsize("4") "A text string". fontsize("4") A text string Formats a string as a link. Text. String. link("page. htm") "A text string". link("page. htm") A Text String

Method char. At(index) char. Code. At(index) index. Of("chars") last. Index. Of("chars") Description Returns the

Method char. At(index) char. Code. At(index) index. Of("chars") last. Index. Of("chars") Description Returns the character at position index in the string. Text. String. char. At(0) "A text string". char. At(0) Returns the Unicode or ASCII decimal value of the character at position index in the string. Text. String. char. Code. At(0) "A text string". char. Code. At(0) Returns the starting position of substring "chars" in the string. If "chars" does not appear in the string, then -1 is returned. Text. String. index. Of("text") "A text string". index. Of("text") Text. String. index. Of("taxt") Returns the starting position of substring "char" in the string, counting from end of string. If "chars" does not appear in the string, then -1 is returned. Text. String. last. Index. Of("text") "A text string". last. Index. Of("text") Text. String. last. Index. Of("taxt") Returns A 65 2 2 -1

substr(index[, length]) substring(index 1, index 2) to. String() to. Fixed(n) to. Precision(n) Returns a

substr(index[, length]) substring(index 1, index 2) to. String() to. Fixed(n) to. Precision(n) Returns a substring starting at position index and including length characters. If no length is given, the remaining characters in the string are returned. Text. String. substr(7, 6) "A text string". substr(7, 6) Returns a substring starting at position index 1 and ending at (but not including) position index 2. Text. String. substring(7, 13) "A text string". substring(7, 13) Converts a value to a string. var Number. Value = 10 var String. Value = Number. Value. to. String() Returns a string containing a number formatted to n decimal digits. var Number. Value = 10. 12345 var String. Value = Number. Value. to. Fixed(2) Returns a string containing a number formatted to n total digits. var Number. Value = 10. 12345 var String. Value = Number. Value. to. Precision(5) string 10 10. 123

Math object o It has following properties n n n n E - Euler's

Math object o It has following properties n n n n E - Euler's constant LN 2 - Natural log of the value 2 LN 10 - Natural log of the value 10 LOG 2 E - The base 2 log of euler's constant (e). LOG 10 E - The base 10 log of euler's constant (e). PI - 3. 1428 - The number of radians in a 360 degree circle (there is no other circle than a 360 degree circle) is 2 times PI. SQRT 2 - The square root of 2.

Math object o It has following methods Method Math. abs(expression) Math. max(expr 1, expr

Math object o It has following methods Method Math. abs(expression) Math. max(expr 1, expr 2) Math. min(expr 1, expr 2) Description Returns the absolute (non-negative) value of a number: Math. abs(-100) Returns 100 Returns the greater of two numbers: Math. max(10, 20) 20 Returns the lesser of two numbers: Math. min(10, 20) 10

Math object Math. round(expression) Math. ceil(expression) Math. floor(expression) Math. pow(x, y) Math. sqrt(expression) Math.

Math object Math. round(expression) Math. ceil(expression) Math. floor(expression) Math. pow(x, y) Math. sqrt(expression) Math. random() Returns a number rounded to nearest integer (. 5 rounds up): Math. round(1. 25) Math. round(1. 50) Math. round(1. 75) Returns the next highest integer value above a number: Math. ceil(3. 25) 1 2 2 4 Returns the next lowest integer value below a number: Math. floor(3. 25) 3 Returns the y power of x: Math. pow(2, 3) 8 Returns the square root of a number: Math. sqrt(144) 12 Returns a random number between zero and one: Math. random() 0. 039160

Date object Method get. Date() get. Day() get. Month() get. Year() get. Full. Year()

Date object Method get. Date() get. Day() get. Month() get. Year() get. Full. Year() Description Returns the day of the month. The. Date. get. Date() Returns 8 Returns the numeric day of the week (Sunday = 0). The. Date. get. Day() 2 Returns the numeric month of the year (January = 0). The. Date. get. Month() 6 Returns the current year. The. Date. get. Year() The. Date. get. Full. Year() 2014

Date object Method get. Time() get. Hours() get. Minutes() get. Seconds() get. Milliseconds() Description

Date object Method get. Time() get. Hours() get. Minutes() get. Seconds() get. Milliseconds() Description Returns the number of milliseconds since January 1, 1970. The. Date. get. Time() Returns 1280911017797 Returns the military hour of the day. The. Date. get. Hours() 14 Returns the minute of the hour. The. Date. get. Minutes() 6 Returns the seconds of the minute. The. Date. get. Seconds() 57 Returns the milliseconds of the second. The. Date. get. Milliseconds() 797

Date object Method to. Time. String() Description Converts the military time to a string.

Date object Method to. Time. String() Description Converts the military time to a string. The. Date. to. Time. String() to. Locale. Time. String() Converts the time to a string. The. Date. to. Locale. Time. String() to. Date. String() Converts the date to an abbreviated string. The. Date. to. Date. String() to. Locale. Date. String() Converts the date to a string. The. Date. to. Locale. Date. String() to. Locale. String() Converts the date and time to a string. The. Date. to. Locale. String() Returns 12: 54: 02 GMT+0530 (India Standard Time) 2: 06: 57 PM 9: 45: 48 AM Tue Jul 08 2014 Tuesday, July 08, 2014 9: 44: 00 AM

Form Elements Text. Box <input type=“text” name=“txtusr” /> Properties Methods Events name value default.

Form Elements Text. Box <input type=“text” name=“txtusr” /> Properties Methods Events name value default. Value focus() blur() select() on. Focus() on. Blur() on. Select() on. Change() Password <input type=“password” name=“p 1” /> Properties Methods Events name value default. Value focus() blur() select() on. Focus() on. Blur() on. Select() on. Change()

Form Elements Button <input type=“button” value=“Click” /> Submit <input type=“submit” value=“Submit” /> Reset <input

Form Elements Button <input type=“button” value=“Click” /> Submit <input type=“submit” value=“Submit” /> Reset <input type=“reset” value=“Reset” /> Properties Methods Events name value click() on. Click()

Form Elements Checkbox <input type=“checkbox” name=“chk” /> Properties Methods Events name value checked defaul.

Form Elements Checkbox <input type=“checkbox” name=“chk” /> Properties Methods Events name value checked defaul. Checked click() on. Click() Radio <input type=“radio” name=“Radio” /> Properties Methods Events name checked index length click() on. Click()

Form Elements Textarea <textarea cols=20 rows=30> </textarea> Properties Methods Events name value default. Value

Form Elements Textarea <textarea cols=20 rows=30> </textarea> Properties Methods Events name value default. Value rows cols focus() blur() select() on. Focus() on. Blur() on. Select() Select and option <select name=“city”> <option> Changa</select> Properties Methods Events name text value selected index selected. Index default. Selected focus() blur() change() on. Focus() on. Blur() on. Change()

Navigator object o o The Java. Script navigator object is the object representation of

Navigator object o o The Java. Script navigator object is the object representation of the client internet browser or web navigator program that is being used. This object is the top level object to all others Properties : - user. Agent, app. Version, cookie. Enabled Methods : - java. Enabled(), tiant. Enabled() Navigator Objects n n n Mime type Plugin Window

Window object o o The Java. Script Window Object is the highest level Java.

Window object o o The Java. Script Window Object is the highest level Java. Script object which corresponds to the web browser window. Internal Objects : - window, self, parent, top Window Properties Methods Events name length status default. Status alert() confirm() prompt() blur() close() focus() open() close() on. Blur on. Click on. Error on. Focus onmouseout onmouseover onmouseup

History object o o The Java. Script History Object is property of the window

History object o o The Java. Script History Object is property of the window object. Properties : - current , length, next, previous Methods : - back(), forward(), go() Example : - <FORM> <INPUT TYPE="button" VALUE="Go Back" on. Click="history. back()“ /> </FORM>

Frame object o The Java. Script Frame object is the representation of an HTML

Frame object o The Java. Script Frame object is the representation of an HTML FRAME which belongs to an HTML FRAMESET. The frameset defines the set of frame that make up the browser window. The Java. Script Frame object is a property of the window object. Document Properties frames name length parent self Methods blur() on. Blur focus() on. Focus set. Interval() clear. Interval() set. Timeout(exp, milliseconds) clear. Timeout(timeout) Events

Document object o The Java. Script Document object is the container for all HTML

Document object o The Java. Script Document object is the container for all HTML HEAD and BODY objects associated within the HTML tags of an HTML document. Document Properties alinkcolor bgcolor, fgcolor, lastmodified, linkcolor, referrer, title, vlinkcolor Methods write() open() close() contextual() Events on. Click ondblclick ondragstart onkeydown onkeypress , onkeyup onmousedown , onmousemove on. Mouse. Out , on. Mouse. Over

Image object o The Java. Script Image Object is a property of the document

Image object o The Java. Script Image Object is a property of the document object. Document Properties border, complete height, hspace lowsrc , name. prototype , src vspace Width Events on. Abort on. Error on. Load

Javascript Global o The Java. Script global properties and functions can be used with

Javascript Global o The Java. Script global properties and functions can be used with all the built-in Java. Script objects. Property Description Infinity A numeric value that represents positive/negative infinity Na. N "Not-a-Number" value undefined Indicates that a variable has not been assigned a value

Javascript Global Function Description decode. URI() Decodes a URI decode. URIComponent() Decodes a URI

Javascript Global Function Description decode. URI() Decodes a URI decode. URIComponent() Decodes a URI component encode. URI() Encodes a URI encode. URIComponent() Encodes a URI component escape() Encodes a string eval() Evaluates a string and executes it as if it was script code is. Finite() Determines whether a value is a finite, legal number is. Na. N() Determines whether a value is an illegal number Number() Converts an object's value to a number parse. Float() Parses a string and returns a floating point number parse. Int() Parses a string and returns an integer String() Converts an object's value to a string unescape() Decodes an encoded string

Reg. Exp Object o A regular expression is an object that describes a pattern

Reg. Exp Object o A regular expression is an object that describes a pattern of characters. Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text. Regular expressions can be created in two ways as follows, o Syntax : - o o n n var txt= new Reg. Exp(pattern, modifiers); var txt=/pattern/modifiers;

Reg. Exp Object o Modifiers are used to perform case-insensitive and global searches: n

Reg. Exp Object o Modifiers are used to perform case-insensitive and global searches: n Modifier Description i Perform case-insensitive matching g Perform a global match (find all matches rather than stopping after the first match) m Perform multiline matching

Reg. Exp Object o Brackets n Brackets are used to find a range of

Reg. Exp Object o Brackets n Brackets are used to find a range of characters: Expression Description [abc] Find any character between the brackets [^abc] Find any character not between the brackets [0 -9] Find any digit from 0 to 9 [A-Z] Find any character from uppercase A to uppercase Z [a-z] Find any character from lowercase a to lowercase z [A-z] Find any character from uppercase A to lowercase z [adgk] Find any character in the given set [^adgk] Find any character outside the given set (red|blue|green) Find any of the alternatives specified

Reg. Exp Object o Metacharacters : Metacharacters are characters with a special Description meaning:

Reg. Exp Object o Metacharacters : Metacharacters are characters with a special Description meaning: Metacharacter . Find a single character, except newline or line terminator w Find a word character (Matches any alphanumeric character including the underscore. Equivalent to [A-Za-z 0 -9_] ) W Find a non-word character. Equivalent to [^A-Za-z 0 -9_] d Find a digit. Equivalent to [0 -9] D Find a non-digit character s Find a whitespace character. Matches a single white space character, including space, tab, form feed, line feed. Equivalent to [ fnrtvu 00 a 0u 1680u 180 eu 2000u 2001u 2002u 2003u 2004 u 2005u 2006u 2007u 2008u 2009u 200 au 2028u 2029u 202 fu 205 f u 3000] S Find a non-whitespace character b Find a match at the beginning/end of a word btonb will find ton but not tons, but bton will find tons. B Find a match not at the beginning/end of a word BtonB will find wantons but not tons

Reg. Exp Object Metacharacter Description � Find a NUL character n Find a new

Reg. Exp Object Metacharacter Description Find a NUL character n Find a new line character f Find a form feed character r Find a carriage return character t Find a tab character v Find a vertical tab character xxx Find the character specified by an octal number xxx xdd Find the character specified by a hexadecimal number dd uxxxx Find the Unicode character specified by a hexadecimal number xxxx

Reg. Exp Object o Quantifiers o * is short for {0, }. Matches zero

Reg. Exp Object o Quantifiers o * is short for {0, }. Matches zero or more times. + is short for {1, }. Matches one or more times. ? is short for {0, 1}. Matches zero or one time. E. g: /o{1, 3}/ matches 'oo' in "tooth" and 'o' in "nose". Quantifier Description n+ Matches any string that contains at least one n n* Matches any string that contains zero or more occurrences of n n? Matches any string that contains zero or one occurrences of n {n} Matches exactly n times. {n, } Matches n or more times. {n, m} Matches n to m times. n$ Matches any string with n at the end of it ^n Matches any string with n at the beginning of it ? =n Matches any string that is followed by a specific string n ? !n Matches any string that is not followed by a specific string n

Reg. Exp Object o Regular Expression Method Description Example Reg. Exp. exec(string) Applies the

Reg. Exp Object o Regular Expression Method Description Example Reg. Exp. exec(string) Applies the Reg. Exp to the given string, and returns the match information. var match = /s(amp)le/i. exec("Sample text") match then contains ["Sample", "amp"] Reg. Exp. test(string) Tests if the given string matches the Regexp, and returns true if matching, false if not. var match = /sample/. test("Sample text") match then contains false String. match(pattern) Matches given string with the Reg. Exp. With g flag returns an array containing the matches, without g flag returns just the first match or if no match is found returns null. var str = "Watch out for the rock!". match(/r? or? /g) str then contains ["o", "or", "ro"]

Reg. Exp Object o Regular Expression Method Description Example String. search(pattern) Matches Reg. Exp

Reg. Exp Object o Regular Expression Method Description Example String. search(pattern) Matches Reg. Exp with string and returns the index of the beginning of the match if found, -1 if not. var ndx = "Watch out for the rock!". search(/for/) ndx then contains 10 String. replace(pattern, string) Replaces matches with the given string, and returns the edited string. var str = "Liorean said: My name is Liorean!". replace(/Liorean/g, 'Big Fat Dork') str then contains "Big Fat Dork said: My name is Big Fat Dork!" String. split(pattern) Cuts a string into an array, making cuts at matches. var str = "I am confused". split(/s/g) str then contains ["I", "am", "confused"]

Reg. Exp Object o Regular Expression Method function display() { var str="hello from CHARUSAT

Reg. Exp Object o Regular Expression Method function display() { var str="hello from CHARUSAT and hello from CMPICA". match(/hello/g); var str 1=/hello/g. exec("hello from CHARUSAT and hello from CMPICA"); document. write(" <b> match() : " +str+ "</b> <br/>"); document. write(" <b> exec() : " +str 1+ "</b>"); } match() : hello, hello exec() : hello

Reg. Exp Object o Regular Expression Examples Test for Regular Expression No white space

Reg. Exp Object o Regular Expression Examples Test for Regular Expression No white space charater S/; No alphabets, or hyphen, or period may appear in the string. /[^a-z - . ] /gi ; No letters of digits may appear /[^a-z 0 -9]/gi ; 16 digit credit card number /^d{4} ([ -]? d{4} ){3}$ /

Reg. Exp Object o Regular Expression Method function ver() { var b=/^d{4}([s-]+d{4}){3}$/. test(f 1.

Reg. Exp Object o Regular Expression Method function ver() { var b=/^d{4}([s-]+d{4}){3}$/. test(f 1. txtcredit. value); //var b=/^d{4}([s-]{1}d{4}){3}$/. test(f 1. txtcredit. value); if(b) alert("Valid Credit Card number. "); else alert("Invalid Credit Card number. "); } 1234 1231 1234 1547 1234 -1234 -1547

Reg. Exp Object o Regular Expression Examples US Zip code : Postal codes vary

Reg. Exp Object o Regular Expression Examples US Zip code : Postal codes vary from country to country but in US they appear as either five numbers, or five numbers followed by a hyphen and four numbers. o 97213 -1234 o Regex : ^d{5}(-d{4})? $ US phone number : US phone number have a three-digit area code followed by seven more digits, however people write phone numbers in many different ways like o 505 -555 -1212 o (503) 555 -1212 o 503. 555. 1212 o 503 555 1212 o Regex : (? (d{3}))? [ -. ](d{3})[ -. ](d{4}) n o

Custom Object o o o Objects are useful to organize information. An object is

Custom Object o o o Objects are useful to organize information. An object is just a special kind of data, with a collection of properties and methods. Example n n n A person is an object. Properties are the values associated with the object. The persons' properties include name, height, weight, age, skin tone, eye color, etc. Objects also have methods. Methods are the actions that can be performed on objects. The persons' methods could be eat(), sleep(), work(), play(), etc.

Custom Object o Properties n The syntax for accessing a property of an object

Custom Object o Properties n The syntax for accessing a property of an object is: o n obj. Name. prop. Name You can add properties to an object by simply giving it a value. Assume that the person. Obj already exists - you can give it properties named firstname, lastname, age, and eyecolor as follows: o person. Obj. firstname=“Rajiv"; person. Obj. lastname=“Gandhi"; person. Obj. age=60; person. Obj. eyecolor="black"; document. write(person. Obj. firstname);

Custom Object o Methods n n An object can also contain methods. You can

Custom Object o Methods n n An object can also contain methods. You can call a method with the following syntax: o n n obj. Name. method. Name() Note: Parameters required for the method can be passed between the parentheses. To call a method called sleep() for the person. Obj: o person. Obj. sleep();

Custom Object o Creating Your Own Objects n There are different ways to create

Custom Object o Creating Your Own Objects n There are different ways to create a new object: 1. Create a direct instance of an object n n The following code creates an instance of an object and adds four properties to it: person. Obj=new Object(); person. Obj. firstname=“Rajiv"; person. Obj. lastname=“Gandhi"; person. Obj. age=60; person. Obj. eyecolor="black";

Custom Object 2. Create a template of an object n The template defines the

Custom Object 2. Create a template of an object n The template defines the structure of an object: n function person(firstname, lastname, age, eyecolor) { this. firstname=firstname; this. lastname=lastname; this. age=age; this. eyecolor=eyecolor; } Once you have the template, you can create new instances of the object, like this: n o o myson=new person(“Rahul", “Gandhi", 30, "blue"); mydaughter=new person(“Priyanka", “Gandhi", 32, "green");

Custom Object o You can also add some methods to the person object. This

Custom Object o You can also add some methods to the person object. This is also done inside the template: n function person(firstname, lastname, age, eyecolor) { this. firstname=firstname; this. lastname=lastname; this. age=age; this. eyecolor=eyecolor; this. newlastname=newlastname; } n Note that methods are just functions attached to objects. n function newlastname(newln) { this. lastname=newln; }

Custom Object o Example n n n Create an object : - Circle It

Custom Object o Example n n n Create an object : - Circle It has property : - radius It has methods : o o n computearea() computediameter() Note area = pi r 2 and diameter = radius * 2

Custom Object <html> <head> <script type="text/javascript" > function circle(r){ this. radius=r; this. computearea=computearea; this.

Custom Object <html> <head> <script type="text/javascript" > function circle(r){ this. radius=r; this. computearea=computearea; this. computediameter=computediameter; } function computearea(){ var area=this. radius * 3. 14; return area; } function computediameter(){ var diameter=this. radius * 2 ; return diameter; } </script></head>

Custom Object <body> <script type="text/javascript" > var mycircle = new circle(20); alert("Area is "

Custom Object <body> <script type="text/javascript" > var mycircle = new circle(20); alert("Area is " + mycircle. computearea()); alert("Diameter is " + mycircle. computediameter()); </script> </body> </html>

Try and Catch o o o The try. . . catch statement allows you

Try and Catch o o o The try. . . catch statement allows you to test a block of code for errors. When browsing Web pages on the internet, we all have seen a Java. Script alert box telling us there is a runtime error and asking "Do you wish to debug? ". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page. We will see how to catch and handle Java. Script error messages, so you don't lose your audience.

Try and Catch o The try. . . catch Statement n n n The

Try and Catch o The try. . . catch Statement n n n The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. Syntax : try { //Run some code here } catch(err) { //Handle errors here } Note that try. . . catch is written in lowercase letters. Using uppercase letters will generate a Java. Script error!

Try and Catch <html> <head> <script type="text/javascript"> var txt=""; function message() { try {

Try and Catch <html> <head> <script type="text/javascript"> var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page. nn"; txt+="Click OK to continue. nn"; alert(txt); } } </script></head><body> <input type="button" value="View message" onclick="message()" /> </body></html>

Try and Catch <html> <head> <script type="text/javascript"> var txt=""; function message(){ try { adddlert("Welcome

Try and Catch <html> <head> <script type="text/javascript"> var txt=""; function message(){ try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page. nn"; txt+="Click OK to continue viewing this page, n"; txt+="or Cancel to return to the home page. nn"; if(!confirm(txt)) document. location. href="http: //www. w 3 schools. com/"; } } </script></head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html>

Try and Catch o Java. Script Throw Statement n n n The throw statement

Try and Catch o Java. Script Throw Statement n n n The throw statement allows you to create an exception. If you use this statement together with the try. . . catch statement, you can control program flow and generate accurate error messages. Syntax : o n n throw(exception) The exception can be a string, integer, Boolean or an object. Note that throw is written in lowercase letters. Using uppercase letters will generate a Java. Script error!

Try and Catch <html> <body> <script type="text/javascript"> var x=prompt("Enter a number between 0 and

Try and Catch <html> <body> <script type="text/javascript"> var x=prompt("Enter a number between 0 and 10: ", ""); try { } if(x>10) throw "Err 1"; else if(x<0) throw "Err 2"; else if(is. Na. N(x)) throw "Err 3";

Try and Catch catch(er) { if(er=="Err 1") alert("Error! The value is too high"); if(er=="Err

Try and Catch catch(er) { if(er=="Err 1") alert("Error! The value is too high"); if(er=="Err 2") alert("Error! The value is too low"); if(er=="Err 3") alert("Error! The value is not a number"); } </script> </body> </html>

Java. Script Special Characters o In Java. Script you can add special characters to

Java. Script Special Characters o In Java. Script you can add special characters to a text string by using the backslash sign. n n Insert Special Characters The backslash () is used to insert apostrophes, new lines, quotes, and other special characters into a text string. var txt=“ Welcome to “CICA” which is a part of CHARUSAT” document. write(txt); var txt=“ Welcome to “CICA” which is a part of CHARUSAT” document. write(txt);

Java. Script Special Characters Code Outputs ' single quote " double quote & ampersand

Java. Script Special Characters Code Outputs ' single quote " double quote & ampersand \ backslash n new line r carriage return t tab b backspace f form feed

Java. Script For. . . In Statement o o Java. Script For. . .

Java. Script For. . . In Statement o o Java. Script For. . . In Statement The for. . . in statement loops through the elements of an array or through the properties of an object. Syntax for (variable in object) { code to be executed }

Java. Script For. . . In Statement <html><body> <script type="text/javascript"> var x; var mycars

Java. Script For. . . In Statement <html><body> <script type="text/javascript"> var x; var mycars = new Array(); mycars[0] = " BMW "; mycars[1] = "Volvo"; mycars[2] = “Santro"; for (x in mycars) document. write(mycars[x] + "<br />"); </script> </body></html>

Referencing Elements o o The other way of referencing elements is as follows, Syntax

Referencing Elements o o The other way of referencing elements is as follows, Syntax : - <tag id="id". . . > The assigned id value must be unique within the document; that is, no two tags can have the same id. Also, the id value must be composed of alphabetic and numeric characters and must not contain blank spaces.

Referencing Elements o o Once an id is assigned, then the HTML object can

Referencing Elements o o Once an id is assigned, then the HTML object can be referenced in a script using the notation as follows, Syntax : document. get. Element. By. Id("id")

Getting and Setting Style Properties o o The style properties associated with particular HTML

Getting and Setting Style Properties o o The style properties associated with particular HTML tags are referenced by appending the property name to the end of the object referent. Syntax : n Get a current style property: document. get. Element. By. Id("id"). style. property n Set a different style property: document. get. Element. By. Id("id"). style. property = value

Getting and Setting Style Properties Example : <h 2 id="Head" style="color: blue">This is a

Getting and Setting Style Properties Example : <h 2 id="Head" style="color: blue">This is a Heading</h 2> document. get. Element. By. Id("Head"). style. color = "red" o

Applying Methods o o Methods are behaviors that elements can exhibit, it can be

Applying Methods o o Methods are behaviors that elements can exhibit, it can be referenced in a script using the notation as follows, Syntax: document. get. Element. By. Id("id"). method() Enter your name: <input id="Box" type="text"/> document. get. Element. By. Id("Box"). focus()

Examples <script type="text/javascript"> function Change. Style() { document. get. Element. By. Id("My. Tag"). style.

Examples <script type="text/javascript"> function Change. Style() { document. get. Element. By. Id("My. Tag"). style. font. Size = "14 pt"; document. get. Element. By. Id("My. Tag"). style. font. Weight = "bold"; document. get. Element. By. Id("My. Tag"). style. color = "red"; } </script> <body> <p id="My. Tag" onclick="Change. Style()">This is a paragraph that has its styling changed. </p> </body>

Passing a Self Reference to a Function o o Use of the self-referent keyword

Passing a Self Reference to a Function o o Use of the self-referent keyword this can be combined with a function call to pass a self identity to a function. Syntax : - event. Handler="function. Name(this)“ function. Name(object. Name) { object. Name. style. property = "value"; }

Examples <script type="text/javascript"> function Change. Style(Mytag) { My. Tag. style. font. Size = "14

Examples <script type="text/javascript"> function Change. Style(Mytag) { My. Tag. style. font. Size = "14 pt"; My. Tag. style. font. Weight = "bold"; My. Tag. style. color = "red"; } </script> <body> <p onclick="Change. Style(this)">This is a paragraph that has its styling changed. </p> </body>

Examples <script type="text/javascript"> function Change. Style(Sometag) { Some. Tag. style. font. Size = "14

Examples <script type="text/javascript"> function Change. Style(Sometag) { Some. Tag. style. font. Size = "14 pt"; Some. Tag. style. font. Weight = "bold"; Some. Tag. style. color = "red"; } </script> <body> <p onclick="Change. Style(this)">This is para 1. </p> <p onclick="Change. Style(this)">This is para 2. </p> </body>

HTML DOM Methods o o The HTML DOM defines a standard way for accessing

HTML DOM Methods o o The HTML DOM defines a standard way for accessing and manipulating HTML documents. The DOM presents an HTML document as a tree-structure.

HTML DOM Methods o What is the DOM? n n n The DOM is

HTML DOM Methods o What is the DOM? n n n The DOM is a W 3 C standard. The DOM defines a standard for accessing HTML and XML documents: "The W 3 C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document. " The W 3 C DOM standard is separated into 3 different parts: o o What is the XML DOM? n o Core DOM - standard model for any structured document XML DOM - standard model for XML documents HTML DOM - standard model for HTML documents The XML DOM defines the objects and properties of all XML elements, and the methods to access them. What is the HTML DOM? n n A standard object model for HTML (A W 3 C standard). A standard programming interface for HTML The HTML DOM defines the objects and properties of all HTML elements, and the methods to access them. In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

HTML DOM Methods <html> <head> <title>DOM Tutorial</title> </head> <body> <h 1>DOM Lesson one</h 1>

HTML DOM Methods <html> <head> <title>DOM Tutorial</title> </head> <body> <h 1>DOM Lesson one</h 1> <p>Hello world!</p> </body> </html>

HTML DOM Methods o Programming Interface n The HTML DOM can be accessed with

HTML DOM Methods o Programming Interface n The HTML DOM can be accessed with Java. Script (and other programming languages). n All HTML elements are defined as objects, and the programming interface is the object methods and object properties. n A method is an action you can do (like add or modify an element). n A property is a value that you can get or set (like the name or content of a node).

HTML DOM Methods Method get. Element. By. Id() get. Elements. By. Tag. Name() Description

HTML DOM Methods Method get. Element. By. Id() get. Elements. By. Tag. Name() Description Returns the element that has an ID attribute with the a value Returns a node list (collection/array of nodes) containing all elements with a specified tag name get. Elements. By. Class. Name() Returns a node list containing all elements with a specified class append. Child() remove. Child() replace. Child() insert. Before() create. Attribute() create. Element() create. Text. Node() get. Attribute() set. Attribute() Adds a new child node to a specified node Removes a child node Replaces a child node Inserts a new child node before a specified child node Creates an Attribute node Creates an Element node Creates a Text node Returns the specified attribute value Sets or changes the specified attribute, to the specified value

HTML DOM Properties Method Description inner. HTML The inner. HTML property is useful for

HTML DOM Properties Method Description inner. HTML The inner. HTML property is useful for getting or replacing the content of HTML elements. node. Name The node. Name property specifies the name of a node. Value The node. Value property specifies the value of a node. Type The node. Type property returns the type of node. Type is read only. ( Element , Attribute, Text, Comment, Document)

HTML DOM Methods o get. Element. By. Id() Method n n n The get.

HTML DOM Methods o get. Element. By. Id() Method n n n The get. Element. By. Id() method accesses the first element with the specified id Syntax : document. get. Element. By. Id("id") Example : Alert inner. HTML of an element with a specific ID: <html><head><script> function get. Value() { var x=document. get. Element. By. Id("my. Header"); alert(x. inner. HTML); } </script> </head> <body> <h 1 id="my. Header" onclick="get. Value()">Click me!</h 1> </body> </html>

HTML DOM Methods o get. Elements. By. Name() Method n n n The get.

HTML DOM Methods o get. Elements. By. Name() Method n n n The get. Elements. By. Name() method accesses all elements with the specified name. Syntax : document. get. Elements. By. Name(name) Example : Alert the number of elements with a specific name: <html> <head> <script> function get. Elements(){ var x=document. get. Elements. By. Name("x"); alert(x. length); } </script> </head> <body> Cats: <input name="x" type="radio" value="Cats"> Dogs: <input name="x" type="radio" value="Dogs"> <input type="button" onclick="get. Elements()" value="How many elements named 'x'? "> </body></html>

HTML DOM Methods o get. Elements. By. Tag. Name() Method n n o The

HTML DOM Methods o get. Elements. By. Tag. Name() Method n n o The get. Elements. By. Tag. Name() method accesses all elements with the specified tagname. Syntax : document. get. Elements. By. Tag. Name(tagname) <html><head><script> function get. Elements() { var x=document. get. Elements. By. Tag. Name("input"); alert(x. length); } </script></head> <body> <input type="text" size="20"> <input type="button" onclick="get. Elements()" value="How many input elements? "> </body> </html>