You are on page 1of 54


• JAVASCRIPT is a programming language used to make web page validation before submitting into server • Developed by Briden Eich of Netscape Navigator in 1996

• Initially it is called as Live Script and later it was contracted to Sun Microsystem it is named as Javascript
• It works on all major browsers such as ,Firefox,Opera,Chrome and safari

What is Javascript?
• Javascript is client side scripting language

• Web browsers will be running the script
• Script will execute without preliminary compilation

Where Do We Place the Code?
• We place javascript coding either internally in html page or externally include javascript file(saved with .js)

Internal(In HTML page) • To insert a JavaScript into an HTML page, use the<script> tag. Eg: <html> <head> <script type=“text/javascript”> document.write (“<h1>WELCOME TO JAVASCRIPT</h1>”); </script> </head> </html>


External Javascript
• Scripting code is typed in separate text editor as filename.js

document.writeln (“<h1>WELCOME TO JAVASCRIPT</h1>”);
In html include this external(sample.js) file as <html> <head> <script type=“text/javascript” src=“sample.js” > <script> </head> <html> The output will be same as Internal javascript

Javascript Statements • Javascript is a sequence of statements executed by the browser • Javascript is case sensitive • It is a command to the browser about what to do Javascript Code • It is sequence of javascript statements Javascript Blocks • Blocks starts with left curly bracket { and end with } right curly bracket .

Datatypes • Datatypes are declared with var keyword var a.Write and writeln • Write –writes a line • Writeln-writes a line with new line character Eg: document. .14. var point=3. var text=”hello”. var i=10.write(“hai”) or document.writeln(“hai”).

floating point values • String. .BASIC DATATYPES Basic data types • Number .String of characters enclosed in double quotes • • Boolean .Store true or false Composite data types – Arrays and Objects • Functions also treated as a data type.integers.

Multi line comments start with /* and end with */.JAVASCRIPT COMMENTS • • • • • JavaScript comments can be used to make the code more readable. Using Comments at the End of a Line . Single line comments start with //.

JAVASCRIPT OPERATORS Operator are used to perform the task. Types of operators: • • • • • • • Arithmetic Operator Relational Operator Logical Operator Assignment Operator Increment & Decrement Operator Conditional Operator Bitwise Operator .

>>. ~.! Conditional Operators The ? : operator (also called the "ternary" operator).returns true if the two operands are not equal.Returns true if the first operands is less than or equal to the second one. != . |.-=. *.*=.&=.Returns true if the first operands is greater than the second one. .|=. >= .<<=.>>>= Increment operators ++ and --. !== . Eg: var e = (a == b) ? c : d.>>=. and % &. and >>> Assisgnment The assignment operator = assigns a value to a variable Operators +=. /.returns true if the two operands are identical. ^./=. Comparison Operators .||.%=. <<.returns true if the two operands are not identical. == Logical Operators &&.Returns true if the first operands is less than the second one. < . -.returns true if the two operands are equal. > .Returns true if the first operands is greater than or equal to the second one.(increment or decrement the variable) Pre and post-increment operators: For eg(++a) Pre-incrementor:++a increments a and returns the new value of a (a++)Post-incrementor: a++ increments a and returns the old value of a. <= .Arithmetic Operator Bitwise Operators +.^=. === .

else • If… elseif…else • Nested If statements Looping Statements • for • while • do…while • Switch case .CONTROL STRUCTURES Conditional Statements • Simple if • If….

} .CONDITIONAL STATEMENTS If Statement Use the if statement to execute some code only if a specified condition is true.writeln(“A is lessthan 5”). Syntax if (condition) { code to be executed if condition is true } Example: if(a<5) { document.

Syntax if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } Ex: if(a<6) { document.write(“A is Greater than 6”)...write(“A is Lessthan 6”).else statement to execute some code if a condition istrue and another code if the condition is not true...If. } else { document. } ..else Statement Use the if.

} . } else if(a==1) { alert(“Dividend is 1”)...else statement ..if..else if.use this statement to select one of many blocks of code to be executed Syntax if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if condition1 and condition2 are not true } Example: if(a==0) { alert(“Divide by 0 error”).. } else { c=a/b. alert(“The division is”+c).

• Switch will evaluate one of several statements. } . If no given value matches the variable.SWITCH CASE • switch statement control the flow of program execution via a multiway branch • This has a similar function as the If condition . break. case value2: statement. break. depending on the value of a given variable. " " default : statement. Syntax: switch (expression){ case value1: statement. the default statement is executed.but it is more useful in situations when there is many possible values for the variable.

write(“no number").write(“Ten"). break. break. case 10: document.Example: <script type="text/javascript"> var a=10. case 6: document. default: document.write(“Five"). } </script> . break. switch (a) { case 5: document.write(“Six").

• The counter variable is something that is created and usually used only in the for loop to count how many times the for loop has looped. increment or decrement) { //loops through a block of code a specified number of times } Eg: for(i=0.Looping Statements For-loop • For loop executes code for a specified number of times.write(i).} .i<5. • The counter variable is incremented after every loop in the increment section of the for loop. It is what decides whether the for loop continues executing or not.i++) { document. test condition. The code that is executed for each loop through the for loop. Syntax: for( Initialization. • The conditional statement.

while loop is a variant of the while loop. This loop will execute the block of code ONCE. .while (condition) { //loops through a block of code while a specified condition is true } do { //The do.. }while (condition). and then it will repeat the loop as long as the specified condition is true..

} Continue The continue statement will break the current loop and continue with the next value.Jump Statement Break The break statement will break the loop and continue executing the code that follows after the loop (if any).write (“The value of i:”+i). for ( i=0.i<=10.i++) { if(i==5) { break. for ( i=0. } . } document.i<=10. } document.i++) { if(i%2==0) { continue.write (“The value of i:”+i).

.Popup Boxes Three methods Pop up windows alert() confirm() prompt() • Alert Displays the message with OK button Ex: alert ("Successfully completed").

Returns Boolean True for OK and False for Cancel Ex: var result = confirm ("Mail will be deleted?"). .•Confirm Displays the message with OK and Cancel button.

•Prompt Prompts the user for input with OK and Cancel buttons Returns the entered data Can also display default input data Ex: var choice = prompt (“Enter your choice. “3”) . Pls”.

Types: • One-Dimensional Array • Two-Dimensional Array One-Dimensional Array Syntax: var array_name = new Array(number_of_elements) . The item can then be referenced later by calling the array variable along with the index number of the item you want to access. it is given a number called an index.ARRAYS • • • • • • • • An array is a variable that can store many variables within it. Arrays are simply an ordered stack of data items with the same data type. When an item is added to the array.

Example-onedimensional array. mycars[2] = “c”. mycars[0] = “a". mycars[1] = “b". var mycars = new Array(3). Syntax: var array_variable= new Array(number_of_elements) . </script> </body> </html> Two-Dimesional Array creating an "array of an array".write(“The array is”+mycars).html <html> <body> <script type="text/JavaScript"> var x. document.

html <script> var a = new Array(3) for (i=0. i <3. i++) { a [i]=new Array(3) a[0][1] = “one" a[0][2] = “Two” a[0][3] = “Three" a[1][1] = “Four” a[1][2] = “Five” a [1][3] = “Six“ a[2][1] = “Seven" a[2][2] = “Eight” a[2][3] = “Nine" } </script> .Example-Two-dimensional array.

Syntax for (variable in object) { code to be executed } Note: The code in the body of the statement loops through the elements of an array or through the properties of an object..In Statement The for.. } loop is executed once for each element/property... for (x in mycars) { document.JavaScript For.write(mycars[x] + "<br />").

Example: Function sample(var a) { Document.write(“The value in function is:”+a). } Sample(“Hello World!”). .Functions in JavaScript Is a self-contained block of code which is used to perform a particular task. Syntax: Function functionname (parameters) { //block of code } Functionname(arguments).

Checks if a value is not a number • parseFloat() .Build In Function • isNaN() .Parses a string and returns an integer .Parses a string and returns a floating point number • parseInt() .

and the function will not be executed before the event occurs! Attribute The event occurs when Onabort Loading of an image is interrupted Onblur An element loses focus Onchange The user changes the content of a field Onclick Mouse clicks an object Ondblclick Mouse double-clicks an object Onerror An error occurs when loading a document or an image Onfocus An element gets focus Onkeydown A keyboard key is pressed Onkeypress A keyboard key is pressed or held down .Events Events are normally used in combination with functions.

Onkeyup Onload Onmousedown Onmousemove Onmouseout Onmouseover Onmouseup Onreset Onresize Onselect Onsubmit Onunload A keyboard key is released A page or an image is finished loading A mouse button is pressed The mouse is moved The mouse is moved off an element The mouse is moved over an element A mouse button is released The reset button is clicked A window or frame is resized Text is selected The submit button is clicked The user exits the page .

JavaScript Objects Introduction • JavaScript is an Object Oriented Programming (OOP) language. • An OOP language allows you to define your own objects and make your own variable types. Javascript Objects: String Object Math Object Array Object Date Object .

String Object Methods • • • • • • • • • • • Method Description anchor() Creates an HTML anchor big() Displays a string in a big font blink() Displays a blinking string bold() Displays a string in bold charAt() Returns the character at a specified position charCodeAt() Returns the Unicode of the character at a specified position concat() Joins two or more strings fixed() Displays a string as teletype text fontcolor() Displays a string in a specified color fontsize() Displays a string in a specified size .

searching backwards from the specified position in a string • link() Displays a string as a hyperlink13 .• fromCharCode() Takes the specified Unicode values and returns a string • indexOf() Returns the position of the first occurrence of a specified string value in a string • italics() Displays a string in italic • lastIndexOf() Returns the position of the last occurrence of a specified string value.

abs(x) Returns the absolute value of a number acos(x) Returns the arccosine of a number asin(x) Returns the arcsine of a number atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians ceil(x) Returns the value of a number rounded upwards to the nearest integer cos(x) Returns the cosine of a number exp(x) Returns the value of Ex floor(x) Returns the value of a number rounded downwards to the nearest integer .Math Object • • • • • • • • • • The Math Object The Math object allows you to perform mathematical tasks.

y) y • pow(x.y) • random() • round(x) • sin(x) • sqrt(x) • tan(x) Returns the number with the highest value of x Returns the number with the lowest value of x and Returns the value of x to the power of y Returns a random number between 0 and 1 Rounds a number to the nearest integer Returns the sine of a number Returns the square root of a number Returns the tangent of an angle .y) and y • min(x.• max(x.

The elements are separated by a specified delimiter • pop() Removes and returns the last element of an array • push() Adds one or more elements to the end of an array and returns the new length • reverse() Reverses the order of the elements in an array .Array Object • Method Description • concat() Joins two or more arrays and returns the result • join() Puts all the elements of an array into a string.

• shift() Removes and returns the first element of an array • slice() Returns selected elements from an existing array • sort() Sorts the elements of an array • splice() Removes and adds new elements to an array • toString() Converts an array to a string and returns the result • unshift() Adds one or more elements to the beginning of an array and returns the new length .

Date Object • The Date object is used to work with dates and times. from a • getHours() 23) • getMilliseconds() (from Description Returns today's date and time Returns the day of the month from a Date (from 1-31) Returns the day of the week from a Date (from 0-6) Returns the year. • Method • Date() • getDate() object • getDay() object • getFullYear() number. as a four-digit Date object Returns the hour of a Date object (from 0Returns the milliseconds of a Date object 0-999) .

Use getFullYear() instead !! • parse() Takes a date string and returns the number of milliseconds since midnight of January 1. 1970 • getYear() Returns the year. as a two-digit or a three/fourdigit number. depending on the browser.• getMinutes() Returns the minutes of a Date object (from 0-59) • getMonth() Returns the month from a Date object (from 0-11) • getSeconds() Returns the seconds of a Date object (from 0-59) • getTime() Returns the number of milliseconds since midnight Jan 1. 1970 • setDate() Sets the day of the month in a Date object (from 1-31) • setFullYear() Sets the year in a Date object (four digits) • setHours() Sets the hour in a Date object (from 0-23) .

• setMilliseconds() Sets the milliseconds in a Date object (from 0-999) • setMinutes() Set the minutes in a Date object (from 059) • setMonth() Sets the month in a Date object (from 0-11) • setSeconds() Sets the seconds in a Date object (from 059) • setTime() Calculates a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1. 1970 • toDateString() Returns the date portion of a Date object in readable form • toLocaleString() Converts a Date object. to a string toString() Converts a Date object to a string . according to local time.

Exception Handling • EvalError – raised when the eval() functions is used in an incorrect manner • RangeError its allowed range raised when a numeric variable exceeds • ReferenceError – raised when an invalid reference is used • SyntaxError – raised when a syntax error occurs while parsing JavaScript code • TypeError expected – raised when the type of a variable is not as • URIError. .raised when the encodeURI() or decodeURI() functions are used in an incorrect manner.

Finally • • • • • • • • • • • • • • <script> try { alet(“hai”). } finally { alert (“Thank you for playing come back soon”). } catch(e) { alert (“The Following error occurred: ” +e.Catch.message).Try. } </script> .name+ ”-” +e.

but after a specified time interval. it is possible to execute some code NOT immediately after a function is called.Timing Events • JavaScript’s Window object comes with four methods that you can use to create timed or looping events in your web pages. • Some of the most common and beneficial uses of JavaScript’s involve timer functions. This is called timing events.executes a code some time in the future • clearTimeout() – cancels the setTimeout() . • With JavaScript. The two key methods that are used are: • setTimeout ().

• First parameter – like alert msg or call the method • Second parameter – indicates how many milliseconds from now you want to execute • clearTimeout() • Syntax • clearTimeout(setTimeout_variable) .• setTimeout() • Syntax • Var t=setTimeout (“ javascript statement ”. milliseconds).

setInterval() • The setInterval() method calls a function/evaluates an expression at specified intervals in milliseconds. • The ID value returned by setInterval() is used as the parameter for the clearInterval() • Method.milliseconds) • Code – the code to be executed • Millisec . • The setInterval() method will continue calling the function until clearInterval() is called or the window is closed. Syntax • setInterval(code.number of milliseconds .

• The ID value returned by setInterval() is used as the parameter for the clearInterval() • Method.clearInterval • The clearInterval() method cancel a timeout that is set with the setInterval() method. Syntax • clearInterval (id_of setinterval) .


on the client. such as title.value • • • • • .• Every page has the following objects: • Navigator: has properties for the name and version of the navigator bring used. and forms.formname. document: contains properties based on the content of the document. window: the top-level object has properties that apply to the entire window. for the MIME types supported by the client. and for the plug-ins installed .fieldname. Reflection : document. links. location : has properties based on the current URL. background color. There is also a window object for each “child window” in a frames document. history: Contains properties representing URLs the client has previously requested.

A Frame object is defined by the FRAME tag in a FRAMESET document. You can create multiple windows in a Navigator JavaScript application.• • • • 1) 2) 3) 4) 5) 6) 7) Window & Frame Objects The window object is the “parent” object for all the other objects in Navigator. The window object has numerous useful methods: Open and close the window Alert Confirm Prompt Blur and focus Scroll setTimeout . A Frame object have the same properties and methods as window object and differ only in the way they are displayed.

anchors[]. unvisited link. applets[] • URL Current document location Methods • Write() . Forms[]. fgcolor (document’s background and foreground colors) • Array as propertiesImages[]. Links[]. visited link) • bgcolor.Document Object – Properties • alinkcolor. vlinkcolor (active link. linkcolor.

Methods Reload.forces a reload of the window’s current document.loads the specified URL over the current history entry.form[] • Accessing the form object • document. • Histroty.go() .Form Objects • Form object represents HTML form • Element of the document.form[index] • document. history.back().formname Location & History Objects • • • • The location object has properties based on the current URL. history. • The History object contains a list of strings representing the URLs the client has visited. Replace.forward().

”toolbar=no. Window methods: • Window.Working with Windows and Frames • The window object is the top-level object in the JavaScript client hierarchy. • Frame objects are similar to window objects.close() • Self.”displaymsg ”. but correspond to • “sub-windows” created with the FRAME tag in a FRAMESET document.close() . scrollbar=no” ) • (“url ”.