Java Script

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 145

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

Sometimes JavaScript is referred to as ECMAscript, ECMA is European Computer Manufacturers Association, it is a private organization that develops standards in information and communication systems.
2

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.


3

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

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.

Understanding Javascript

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

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

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.

HTML and Javascript

Integrating script under the <head> tag Syntax :<html> <head> <script type=text/javascript > ----------------</script> </head> <body> </body> <html>
9

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.

10

HTML and Javascript

Integrating script under the <body> tag Syntax :<html> <head> </head> <body> <script type=text/javascript > ----------------</script> </body> <html>

11

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 dont have a <script> tag.
12

HTML and Javascript

Importing the external javascript Syntax :<html> <head>

<script src=first.js > ----------------</script>


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

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

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 dont specify type attribute it assumes that the scripting language is javascript. However use of type attribute is specified as mandatory by W3C.
15

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

Javascript statement

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

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.
18

Elements of javascript

Example :<script type=text/javascript > { document.write(First javascript stmt.); document.write(Second javascript stmt.); }

</script>
19

Elements of javascript

Javascript comments

It supports both single line and multi line comments. // - Single line comments /*---------*/ - Multi line comments

20

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

Variables

Basic syntax of variable declaration


Syntax:- var variablename; 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

Naming conventions

Variables

Once you declare a variable you can initialize 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;


23

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

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.


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

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.
26

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;
27

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

28

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;
29

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

/=

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

30

Operators

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

!=

<

>

<=

>=

31

Operators

Logical Operators
Logical Operator && Comparison

And operator. condition1 && condition2 The condition1 and condition2 tests both must be true for the expression to be evaluated as true. Or operator. condition1 || condition2 Either the condition1 or condition2 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.
32

||

If condition

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

33

If else condition

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

34

Nested if condition

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

35

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...}]
36

The Switch Statement

Syntax:switch (expression) { case "value1": do this... break case "value2": do this... break ... [ default: do this... ] }
37

Iterations

For statement:for (exp1;exp2;exp3) { do this... } exp1:initial expression exp2:conditional expression exp3:incremental expression
38

Iterations

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

39

Iterations

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

40

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 array of size zero is created. In the second syntax size is explicitly specified, hence this array will hold a pre-determined set of values.
41

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;
42

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);

43

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.
44

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 :45

myarr = new Array(one,two,1,2, true, new Array(3,4) );

Special Operators

Strict Equal (= = =)

Example 5 == 5 true but 5 === 5 false It do not perform type conversion before testing for equality. Example :- condition ? Exp1 : Exp2

Ternary operators (? :)

Delete operator

It is used to delete a property of an object or an element at an array index. Example :- delete arrayname[5]
46

Special Operators

New operator

It is used to create an instance of object type. Example :- myarr = new Array(); It does not return a value It is specially used to return a URL with no value.

Void operator

47

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 Examples :


Built in functions

eval() parseInt() parseFloat()


48

Functions

eval

It is used to convert a string expression to a numeric value. Example :- var g_total = eval (10 * 10 + 5); 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 49 var str2no =parseInt(xyz); //NaN

parseInt

Functions

parseFloat

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 str2no = parseFloat(1.2xyz); //1.2

50

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

51

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 }
52

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.
53

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.
54

Functions

Function call

A variable or a static value can be passed to a function. Example:printName(Bhoomi); var firstname=Bhoomi; printName(firstname);

55

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; }
56

Functions

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

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


58

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.

59

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

Alert Dialog Box : Example

61

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.
62

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.

63

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>

64

Prompt Dialog Box : Example

65

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.

66

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

Confirm Dialog Box : Example

68

Different types of Objects

W3C DOM objects


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. JS allows you to create your own objects that can contain related functionality.

Built-in objects

Custom objects

JavaScript Object Hierarchy

W3C DOM objects

To access a documents property or method the general syntax is as follows,


objectname.property objectname.method() Property :- alinkcolor, bgcolor, fgcolor, lastmodified, linkcolor, referrer, title, vlinkcolor.

Document object

Example :- document.lastModified

Method :- write(str) , writeln(str)

W3C DOM objects

Form object

Property :- action, method, length, name, target

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

73

HTML form elements

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

reset a reset button (<input type=reset /> ) submit a submit button ( <input type=submit /> ) select a selection list.
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 /> )

( <select> <option> option1 </option> <option> option2 </option> </select> )


Properties of form elements


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

value

Indicates the current value of the object.

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 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 index number of the currently selected option. defaultselected select Indicated 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 onFocus() Text, password,text area onBlur() Text, password,text area onSelect() 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 onChange() Text, password,text area onClick() Button, radio, checkbox, submit, reset Description Fires when the text is changed in an object. Fires when an object is clicked on.

Events

Events
Event Handler
onclick

Event
The mouse button is clicked and released with the cursor positioned over a page element. The mouse button is double-clicked with the cursor positioned over a page element. The mouse button is pressed down with the cursor positioned over a page element. The mouse cursor is moved across the screen. The mouse cursor is moved off a page element. The mouse cursor is moved on top of a page element. The mouse button is released with the cursor positioned over a page element.
82

ondblclick onmousedown onmousemove onmouseout onmouseover onmouseup

Example

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 onClick=calculate(this.form) /> <input type=text name=result /> </form> </body> </html>

Built-in objects

String object Date object Math object

String object

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

Property length

Method bold()

Description Changes the text in a string to bold. TextString.bold() "A text string".bold()
Changes the text in a string to italic. TextString.italics() "A text string".italics() Changes the text in a string to strike-through characters. TextString.strike() "A text string".strike()

Returns
A text string

italics()

A text string

strike()

A text string

sub()

Changes the text in a string to subscript. "Subscript" + TextString.sub() "Subscript" + "A text string".sub()
Changes the text in a string to superscript. "Superscript" + TextString.sup() "Superscript" + "A text string".sup() Changes the text in a string to lower-case. TextString.toLowerCase() "A text string".toLowerCase()

SubscriptA text string

sup()

SuperscriptA text string

toLowerCase()

a text string

toUpperCase()

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

A TEXT STRING

fixed()

A text string

fontcolor ("color")

A text string

fontsize("n")

A text string

link("href")

A Text String

Method
charAt(index)

Description
Returns the character at position index in the string. TextString.charAt(0) "A text string".charAt(0) Returns the Unicode or ASCII decimal value of the character at position index in the string. TextString.charCodeAt(0) "A text string".charCodeAt(0) Returns the starting position of substring "chars" in the string. If "chars" does not appear in the string, then -1 is returned. TextString.indexOf("text") "A text string".indexOf("text") TextString.indexOf("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. TextString.lastIndexOf("text") "A text string".lastIndexOf("text") TextString.lastIndexOf("taxt")

Returns
A

charCodeAt(index)

65

indexOf("chars")

2 2 -1

lastIndexOf("chars")

2 2 -1

substr(index[,length])

Returns a substring starting at position index and including length characters. If no length is given, the remaining characters in the string are returned. TextString.substring(7,6) "A text string".substring(7,6) Returns a substring starting at position index1 and ending at (but not including) position index2. TextString.substring(7,13) "A text string".substring(7,13) Converts a value to a string. var NumberValue = 10 var StringValue = NumberValue.toString() Returns a string containing a number formatted to n decimal digits. var NumberValue = 10.12345 var StringValue = NumberValue.toFixed(2) Returns a string containing a number formatted to n total digits. var NumberValue = 10.12345 var StringValue = NumberValue.toPrecision(5)

string

substring(index1,index2)

string

toString()

10

toFixed(n)

10.12

toPrecision(n)

10.123

Math object

It has following properties


E - Euler's constant LN2 - Natural log of the value 2 LN10 - Natural log of the value 10 LOG2E - The base 2 log of euler's constant (e). LOG10E - 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. SQRT2 - The square root of 2.

Math object

It has following methods


Method Description Returns the absolute (non-negative) value of a number: Math.abs(-100) Returns 100

Math.abs(expression)

Math.max(expr1,expr2) Returns the greater of two numbers: Math.max(10,20) Math.min(expr1,expr2) Returns the lesser of two numbers: Math.min(10,20)

20

10

Math object
Math.round(expression) 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) Returns the next lowest integer value below a number: Math.floor(3.25) Returns the y power of x: Math.pow(2,3) Returns the square root of a number: Math.sqrt(144) Returns a random number between zero and one: Math.random() 1 2 2

Math.ceil(expression)

Math.floor(expression)

Math.pow(x,y) Math.sqrt(expression) Math.random()

8 12 0.039160

Date object
Method
getDate() getDay()

Description
Returns the day of the month. TheDate.getDate() Returns the numeric day of the week (Sunday = 0). TheDate.getDay() Returns the numeric month of the year (January = 0). TheDate.getMonth() Returns the current year. TheDate.getYear() TheDate.getFullYear()

Returns
4 4

getMonth()

getYear() getFullYear()

2013 2013

Date object
Method getTime() Description Returns the number of milliseconds since January 1, 1970. TheDate.getTime() Returns the military hour of the day. TheDate.getHours() Returns the minute of the hour. TheDate.getMinutes() Returns the seconds of the minute. TheDate.getSeconds() Returns 1280911017797

getHours() getMinutes() getSeconds()

14
6 57 797

getMilliseconds()

Returns the milliseconds of the second. TheDate.getMilliseconds()

Date object
Method
toTimeString()

Description
Converts the military time to a string. TheDate.toTimeString() Converts the time to a string. TheDate.toLocaleTimeString() Converts the date to an abbreviated string. TheDate.toDateString() Converts the date to a string. TheDate.toLocaleDateString() Converts the date and time to a string. TheDate.toLocaleString()

Returns
14:06:57 UTC+0530 09:45:48 UTC+0530 2:06:57 PM 9:45:48 AM

toLocaleTimeString() toDateString()

Wed Jul 11 2012


Thursday, July 04, 2013

toLocaleDateString() toLocaleString()

Thursday, July 04, 2013 9:44:00 AM

Form Elements
TextBox <input type=text name=txtusr />
Properties name value defaultValue Methods focus() blur() select() Events onFocus() onBlur() onSelect() onChange()

Password <input type=password name=p1 />


Properties name value defaultValue Methods focus() blur() select() Events onFocus() onBlur() onSelect() onChange()

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

Reset <input type=reset value=Reset />


Properties name value Methods click() Events onClick()

Form Elements
Checkbox <input type=checkbox name=chk />
Properties Methods Events

name value checked defaulChecked

click()

onClick()

Radio <input type=radio name=Radio />


Properties name checked index length Methods click() Events onClick()

Form Elements
Textarea <textarea cols=20 rows=30> </textarea>
Properties name value defaultValue rows cols Methods focus() blur() select() Events onFocus() onBlur() onSelect()

Select and option <select name=city> <option> Changa</select>


Properties name text value selected index selectedIndex defaultSelected Methods focus() blur() change() Events onFocus() onBlur() onChange()

Referencing Elements

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

Once an id is assigned, then the HTML object can be referenced in a script using the notation as follows, Syntax :document.getElementById("id")

Getting and Setting Style Properties

The style properties associated with particular HTML tags are referenced by appending the property name to the end of the object referent. Syntax :

Get a current style property: document.getElementById("id").style.property

Set a different style property: document.getElementById("id").style.property = value

Getting and Setting Style Properties

Example :<h2 id="Head" style="color:blue">This is a Heading</h2> document.getElementById("Head").style.color document.getElementById("Head").style.color = "red"

Applying Methods

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

Examples
<script type="text/javascript"> function ChangeStyle() {
document.getElementById("MyTag").style.fontSize = "14pt"; document.getElementById("MyTag").style.fontWeight = "bold"; document.getElementById("MyTag").style.color = "red";

} </script> <body> <p id="MyTag" onclick="ChangeStyle()">This is a paragraph that has its styling changed. </p> </body>

Passing a Self Reference to a Function

Use of the self-referent keyword this can be combined with a function call to pass a self identity to a function . Syntax :- eventHandler="functionName(this) function functionName(objectName) { objectName.style.property = "value"; objectName.style.property = "value"; }

Examples
<script type="text/javascript"> function ChangeStyle(Mytag) {
MyTag.style.fontSize = "14pt"; MyTag.style.fontWeight = "bold"; MyTag.style.color = "red";

} </script> <body> <p onclick="ChangeStyle(this)">This is a paragraph that has its styling changed. </p> </body>

Examples
<script type="text/javascript"> function ChangeStyle(Sometag) { SomeTag.style.fontSize = "14pt"; SomeTag.style.fontWeight = "bold"; SomeTag.style.color = "red"; } </script> <body> <p onclick="ChangeStyle(this)">This is para1.</p> <p onclick="ChangeStyle(this)">This is para2.</p> </body>

Navigator object

The JavaScript 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 :- userAgent, appVersion, cookieEnabled Methods :- javaEnabled(), tiantEnabled() Navigator Objects

Mime type Plugin Window

Window object

The JavaScript Window Object is the highest level JavaScript object which corresponds to the web browser window. Internal Objects :- window, self, parent, top
Window
Properties Methods Events

name length status defaultStatus

alert() confirm() prompt() blur() close() focus() open() close()

onBlur onClick onError onFocus onmouseout onmouseover onmouseup

History object

The JavaScript 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" onClick="history.back() /> </FORM>

Frame object

The JavaScript 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 JavaScript Frame object is a property of the window object.
Document
Properties frames name length parent self Methods blur() onBlur focus() onFocus setInterval() clearInterval() setTimeout(exp, milliseconds) clearTimeout(timeout) Events

Document object

The JavaScript 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 onClick ondblclick ondragstart onkeydown onkeypress ,onkeyup onmousedown ,onmousemove onMouseOut ,onMouseOver

Image object

The JavaScript Image Object is a property of the document object.


Document
Properties border, complete height, hspace lowsrc , name. prototype , src vspace Width onAbort onError onLoad Events

Javascript Global

The JavaScript global properties and functions can be used with all the built-in JavaScript objects.
Property Description

Infinity

A numeric value that represents positive/negative infinity

NaN
undefined

"Not-a-Number" value

Indicates that a variable has not been assigned a value

Javascript Global
Function decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() escape() eval() Description Decodes a URI Decodes a URI component Encodes a URI Encodes a URI component Encodes a string Evaluates a string and executes it as if it was script code

isFinite()
isNaN() Number()

Determines whether a value is a finite, legal number


Determines whether a value is an illegal number Converts an object's value to a number

parseFloat()
parseInt() String() unescape()

Parses a string and returns a floating point number


Parses a string and returns an integer Converts an object's value to a string Decodes an encoded string

RegExp Object

A regular expression is an object that describes a pattern of characters. Regular expressions are used to perform patternmatching and "search-and-replace" functions on text. Regular expressions can be created in two ways as follows, Syntax :

var txt= new RegExp(pattern,modifiers); var txt=/pattern/modifiers;

RegExp Object

Modifiers

Modifiers are used to perform case-insensitive and global searches:


Modifier
i g

Description
Perform case-insensitive matching Perform a global match (find all matches rather than stopping after the first match)

Perform multiline matching

RegExp Object

Brackets

Brackets are used to find a range of characters:


Expression [abc] [^abc] [0-9] Description Find any character between the brackets Find any character not between the brackets Find any digit from 0 to 9

[A-Z]
[a-z] [A-z] [adgk] [^adgk] (red|blue|green)

Find any character from uppercase A to uppercase Z


Find any character from lowercase a to lowercase z Find any character from uppercase A to lowercase z Find any character in the given set Find any character outside the given set Find any of the alternatives specified

RegExp Object

Metacharacters

Metacharacters are characters with a special meaning:


Description Find a single character, except newline or line terminator Find a word character Find a non-word character Find a digit Find a non-digit character

Metacharacter . \w \W \d \D

\s
\S \b \B

Find a whitespace character


Find a non-whitespace character Find a match at the beginning/end of a word Find a match not at the beginning/end of a word

RegExp Object
Metacharacter \0 Description Find a NUL character

\n
\f \r \t \v \xxx

Find a new line character


Find a form feed character Find a carriage return character Find a tab character Find a vertical tab character Find the character specified by an octal number xxx

\xdd
\uxxxx

Find the character specified by a hexadecimal number dd


Find the Unicode character specified by a hexadecimal number xxxx

RegExp Object

Quantifiers
* 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+
n* n? {n} {n,} {n,m} n$ ^n ?=n ?!n

Matches any string that contains at least one n


Matches any string that contains zero or more occurrences of n Matches any string that contains zero or one occurrences of n Matches exactly n times. Matches n or more times. Matches n to m times. Matches any string with n at the end of it Matches any string with n at the beginning of it Matches any string that is followed by a specific string n Matches any string that is not followed by a specific string n

RegExp Object

Regular Expression Method


Example

Description RegExp.exec(string)

Applies the RegExp to the given string, var match = /s(amp)le/i.exec("Sample text") and returns the match information. match then contains ["Sample","amp"] RegExp.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 RegExp. var str = "Watch out for the With g flag returns an array containing rock!".match(/r?or?/g) the matches, without g flag returns just the first match or if no match is str then contains ["o","or","ro"] found returns null.

RegExp Object

Regular Expression Method


Example var ndx = "Watch out for the rock!".search(/for/) ndx then contains 10 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!"

Description String.search(pattern) Matches RegExp with string and returns the index of the beginning of the match if found, -1 if not. String.replace(pattern,string) Replaces matches with the given string, and returns the edited string.

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"]

RegExp Object

Regular Expression Examples


Regular Expression \S/; /[^a-z \- \.] /gi ; /[^a-z0-9]/gi ;

Test for No white space charater

No alphabets, or hyphen, or period may appear in the string.


No letters of digits may appear 16 digit credit card number

/^\d{4} ( [-]? \d{4} ){3}$ /

Custom Object

Objects are useful to organize information. An object is just a special kind of data, with a collection of properties and methods. Example

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

Properties

The syntax for accessing a property of an object is:

objName.propName

You can add properties to an object by simply giving it a value. Assume that the personObj already exists - you can give it properties named firstname, lastname, age, and eyecolor as follows:

personObj.firstname=Rajiv"; personObj.lastname=Gandhi"; personObj.age=60; personObj.eyecolor="black"; document.write(personObj.firstname);

Custom Object

Methods

An object can also contain methods. You can call a method with the following syntax: objName.methodName() Note: Parameters required for the method can be passed between the parentheses. To call a method called sleep() for the personObj:

personObj.sleep();

Custom Object

Creating Your Own Objects

There are different ways to create a new object: The following code creates an instance of an object and adds four properties to it: personObj=new Object(); personObj.firstname=Rajiv"; personObj.lastname=Gandhi"; personObj.age=60; personObj.eyecolor="black";

1. Create a direct instance of an object


Custom Object
2. Create a template of an object

The template defines the structure of an object:


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:
myson=new person(Rahul",Gandhi",30,"blue"); mydaughter=new person(Priyanka",Gandhi",32,"green");

Custom Object

You can also add some methods to the person object. This is also done inside the template:

function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.newlastname=newlastname; }

Note that methods are just functions attached to objects.


function newlastname(newln) { this.newlastname=newln; }

Custom Object

Example

Create an object :- Circle It has property :- radius It has methods :

computearea() computediameter()

Note area = pi r2 and diameter = radius * 2

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 * 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 " + mycircle.computearea()); alert("Diameter is " + mycircle.computediameter()); </script> </body> </html>

Try and Catch


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 JavaScript 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 JavaScript error messages, so you don't lose your audience.

Try and Catch

The try...catch Statement


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 JavaScript error!

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.\n\n"; txt+="Click OK to continue.\n\n"; 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 guest!"); } catch(err) { txt="There was an error on this page.\n\n"; txt+="Click OK to continue viewing this page,\n"; txt+="or Cancel to return to the home page.\n\n"; if(!confirm(txt)) document.location.href="http://www.w3schools.com/"; } } </script></head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html>

Try and Catch

JavaScript Throw Statement


The throw statement allows you to create an exception. 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 :

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 JavaScript error!

Try and Catch


<html> <body> <script type="text/javascript"> var x=prompt("Enter a number between 0 and 10:",""); try { if(x>10) throw "Err1"; else if(x<0) throw "Err2"; else if(isNaN(x)) throw "Err3"; }

Try and Catch


catch(er) { if(er=="Err1") alert("Error! The value is too high"); if(er=="Err2") alert("Error! The value is too low"); if(er=="Err3") alert("Error! The value is not a number"); } </script> </body> </html>

JavaScript Special Characters

In JavaScript you can add special characters to a text string by using the backslash sign.

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);

JavaScript Special Characters


Code
\' \" \&

Outputs
single quote double quote ampersand

\\
\n \r \t

backslash
new line carriage return tab

\b
\f

backspace
form feed

JavaScript For...In Statement


JavaScript 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 }

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

You might also like