You are on page 1of 81

1

JavaScript is the client side scripting language, developed by Netscape, used along with HTML to build a efficient web site / webpage. In the beginning stages, web pages were developed only using html, which are nothing but static pages. User interaction and dynamic changes are not possible with html. With the advent of scripting languages the problem was solved. There are two types of script languages server side and client side. When a page is requested, the request is sent to the server and data is fetched and viewed in the browser. If the dynamic changes in the webpage are caused in the client side (the browsers like Mozilla / IE) its called client side scripting language (E.g. - JavaScript). If the dynamic changes in the web page are caused in the server side (the server checks the request and based on the data it makes changes in the page before sending the data to the browser) its called server side scripting language (E.g. - php). Java script codes are embedded in HTML files. Whenever a browser requests for a webpage, the HTML file along with script is transferred to the browser. This tutorial will give you an introduction and help you learn java script JavaScript is used in to create dynamic changes, validate forms, detect visitor details, create/use cookies, etc.. JavaScript works in all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, Opera, Safari and more.

Java And JavaScript:


Never confuse javascript with java. Java is an application development language developed by SUN Microsystems and has no links with javascript. Javascript was created long before java was developed. Javascript is many times denoted as java script. This tutorial will help both beginners and advanced users. Learn java script. Script tag is the primary tag which identifies javascript. Any javascript code should be written in between the script tag. <script language="javascript"> </script> Here the attribute language defines the language used. For VBscript user it will be vbscript. The script tag can be written anywhere inside head or body tag of html.

Example: <html> <head></head> <body> <script language=javascript> //code comes here..... //code comes here..... //code comes here..... </script> </body> </html> We will begin with the in built method or function document.write() to code our first javascript program. This method helps to write any given variable on the browser. Example: <html> <head></head> <body> <script language=javascript> document.write("This is my first javascript program"); </script> </body> </html> HTML Code using Javascript: HTML tags or code can also be added using document.write method. i.e. Just use the html code as the argument for document.write or document.writeln functions document.write("-- bold red --"); Example Code: <script language=javascript> document.write("-- <b>bold</b> <font color=red> red </font>--"); </script> Result: -- bold red -Break line for .write method : document.write will append the string to the previous string. i.e. if you call document.write(" -- first line ---"); document.write(" -- second line ---"); the result will be as " -- first line --- -- second line ---";

So in order to break the lines in the browser you have to use an additional code "<br>" at the end. e.g: document.write(" -- first line --- <br>"); Example Code: <script language=javascript> document.write(" -- first line --- <br>"); document.write(" -- second line --- <br>"); </script> Result: -- first line ---- second line --Alert or Popup: The in built function alert can be used for creating a alert or popup message. Use the function with any string as argument. Example: <script language=javascript> alert("This is a test alert message"); </script>

VARIABLES:
Variables are used to store values. i.e. for example if we have to add two numbers, we will declare two variables and assign the numbers to each variable and add them to get the result. var a = 5; var b= 5; var c = a+b; Javascript can handle the following variable types a) Number (Integer and Float) b) String c) Boolean d) Null e) Undefined In javascript all variable types are declared as var, only depending on how we assign the values the data type is defined. var a = "as"; --> This is a string type variable var a = 2; --> This is a integer type variable var a = true; --> This is a boolean type variable Here var defines it as a variable. "a" is the variable name. "as", 2, true are called values.

The variable name can have alphanumeric values. Any lowercase (a-z) or uppercase (A-Z) alphabets, numbers (0-9) or underscore(_). String- E.g: "sdfesdfe" For a variable to be a string type, the value assigned should be given in quotes. A number given within quotes will be considered only as a string and not as an integer. i.e if var a = "2"; var b = "2"; then a+b will give "22" and not 4.

Special Character's: To use the special characters like tab, newline, back space, double quotes, etc.. in string variable the following format should be used Character Single Quote Double Quote Backslash Horizontal Tab New Line Back Space Carriage Return Example Code: <script language="javascript"> var as = "this is \"a\" \'test\'"; document.write(as); </script> Result: this is "a" 'test' Number: Numbers can be used in two different types in javascript. They are integer and float. Integer- E.g: 2 For a variable to be of int type just assign number with out any quotes. i.e if var a = 2; var b = 2; then a+b gives 4. Float- E.g: 2.12 For a variable to be of float type just assign fractional number with out any quotes. i.e if var a = 2.12; var b = 2.12; Code to be used \' \" \\ \t \n \b \r

then a+b gives 4.24 Important: Never forget that number types should not have any quotes. Example Code: <script language="javascript"> var a = 2; var b = 3; var c = a+b; document.write(" addition - "); document.write(c); </script> Result: addition - 5 Boolean Data Type- E.g: true It can have logical values true or false. Variable type Boolean should not have any quotes. i.e. "true" is not equal to true, "true" will be considered as a string. var a = true; var b = false; Boolean variable values are mostly used along with "if", "if else" statements and "while" loops. Example Code: <script language="javascript"> var a = true; if(a == true) { document.write("this is true"); } </script> Result: this is true Data Type Conversion: The following data type conversions are possible a) String to Integer (int) b) Float to Integer (int) c) String to Float d) Integer (int) to String e) Float to String

a) Converting String to Integer To convert a value from string to integer we have to use the function or method "parseInt(). Passing a correct argument to the function (e.g: "4") will return correct value else (e.g: "sd") 0 will be returned. Example parseInt("4"); parseInt("5aaa"); parseInt("4.33333"); parseInt("aaa"); Result 4 4 4 NaN (means "Not a Number")

b) Converting Float to Integer To convert a float value in to integer we have to use the function or method parseInt. Example parseInt(5.133); Result 5

Example Code: <script language="javascript"> var a = "334"; var b = 3; var c = parseInt(a)+b; var d = a+b; document.write("parseInt(a)+b = "+c); document.write(" a+b = "+d); </script> Result: parseInt(a)+b = 337 a+b = 3343 c) Converting String to Float To convert a value from string to float, we have to use the function or method "parseFloat() to convert a string value to float. Example parseFloat("4.333"); parseFloat("5aaa"); Result 4.333 5

parseFloat("6e2"); parseFloat("aaa");

600 NaN (means "Not a Number")

d) Converting Integer/Float to String Integer (int) or float value can be converted to string by using the function or method toString(). Example var a = 3.22; a.toString(); var a = 5; a.toString(); Example Code: <script language="javascript"> var a = 32; var b = 333; var c = a.toString()+b; document.write(" to String function "+c); </script> Result: to String function -> 32333 Result "3.22" 5

OPERATOR:
An operator is a symbol or sign used in javascript to identify a specific operation. For example, when we want to define an expression for adding two numbers, we use 3+4. Here let us assume that we have defined variable a and b for the number, so the expression will become a+b; The symbol "+" defines that the operands a and b has to be added. So "+" is called as an operator. Types Of Operators: There a three type of operators based on operands used, namely unary, binary, ternary. Unary - The Operator works with one operand (e.g: a++, a will be incremented by 1), Binary - The Operator works with two operands (e.g: a+b), Ternary - The Operator works with three operands (e.g: condition? value 1 : value 2).
There a four type of operators based on the type of use.

Arithmetic Operator Logical Operator Comparison Operator Assignment Operator

Arithmetic Operators: They are operators or syntax used to do arithmetic or math operations like addition, subtraction, multiplication, division, increment, decrement, etc.. These are some time misspelled as arithmatic, arithematic. Operator Syntax + * / % ++ -Description Used for addition of two numbers Used for subtraction of two numbers Used for multiplication of two numbers Used for division of two numbers Used to find the division remainder Used to increment a value Used to decrement a value

Example Code: <script language="javascript"> var c = (2+4-2)*10; document.write(" Arithmetic Operations -> "+c); </script> Result: Arithmetic Operations -> 40 Logical Operators: There are used mainly for boolean operations. Operator Syntax && || ! Description Used for logical "and" operation, condition Used for logical "or" operation, condition Used for logical "not" operation, condition

Local operators or used along with if statements and while loops to check multiple criterias. example usage1: if a is animal && (and) b is man, print something. example usage2: if a is tany || (or) a is ramani, say good morning. Example Code: <script language="javascript"> var a = "tany"; var b = "ramani"; if(a == "tany" && b == "ramani") { document.write(" Logical Operator AND '&&', OR '||', NOT '!' "); } </script> Result: Logical Operator AND '&&', OR '||', NOT '!'

Comparison Operators: They are used to compare numerical (numbers), string or boolean values. OperatorSyntax == != > < >= <= === !== Description validates the condition whether two numbers or string values are equal validates the condition whether two numbers or string values are not equal validates the condition whether one numbers is greater than other validates the condition whether one numbers is less than other compares the numbers and checks whether one numbers is greater than or equal to other compares the numbers and checks whether one numbers is less than or equals other used to compare and check whether two values are strictly equal used to compare and check whether two values are strictly not equal

The main difference between "equal to (= =)" and "strictly equal to (= = =)" is that the equality comparison takes place after type conversion for "equal to (= =)" and before type conversion for "strictly equal to (= = =)". i.e "5" = = 5 and "5" != = 5 Example Code: <script language="javascript"> var a = "5"; var b = 5; if(a = = b) { document.write(" Testing Comparative Operator for equals "); } if(a = = = b) { document.write(" Testing Comparison Operator for strictly equals "); } </script> Result: Testing Comparative Operator for equals As a is not strictly equal to b the second message is not printed.

10

Assignment Operators: Assignment Operators are use to assign a value to a variable. Operator Syntax = Description used to assign a value on the right side to the variable of the left side of the operator. Example b = 3;

+=

-=

*=

/= <<= <<=

b = 3; it adds the value on the right to the previous value of the variable b += 4; on the left and assign the new value to the variable. // Now b will become 7 b = 4; it subtracts the value on the right to the previous value of the b -= 2; variable on the left and assign the new value to the variable. // Now b will become 2 b = 4; it multiplies the operand on the right to the previous value of the b *= 2; variable on the left and assaigns the new value to the variable. // Now b will become 8 b = 6; it divides the operand on the right to the previous value of the b /= 2; variable on the left and assaigns the new value to the variable. // Now b will become 3 The operand on the left is shifted left by the value on the right. A signed right shifted is performed on the left operand by the value on the right.

Ternary Operator: As the name indicates ternary operators take three operands. The syntax is condition ? result1 : result2;. Here you use a condition before question mark (?) followed by result 1 and result 2 separated by a colon (:). Result1 is called if the condition is satisfied else result2 is called. Example 1: <script language=javascript> var b=5; (b == 5) ? a="true" : a="false"; document.write(" --------------------------- "+a); </script> Result: --------------------------- true Example 2: <script language=javascript> var b=true;

11

(b == false) ? a="true" : a="false"; document.write(" --------------------------- "+a); </script> Result: --------------------------- false Operators Execution Order: When the expression or the formula has more operators they will follow the following order of precedence. Precedence Order 1 2 3 4 Operator (Symbol) !, ++, --, ~ *, /, %, +, << , >>, >>> <, <=, >, >= Operator in Words Not, Increment, Decrement Multiplication, Division, Modulus, Addition, Subtraction Less Than, Less than or equal to, Greater Than, Greater than or equal to Equals Comparison, Not Equals, Strictly Equals, Strictly Not Equals Bitwise AND, Bitwise OR, Bitwise Exclusive OR, Logical AND, Logical OR Ternary Operator

==, !=, ===, !==

6 7

&, |, ^, &&, || ?: Assignment Operators =, +=, -=, /=, *=, %=, <<=, >>=, >>>=, &=, ^=

Assign, other assignment operators

Say we have an expression a = 4*2+4;. Here as we can note from the table. Operator "*" (multiplication) has top preference than "=" (equals) and "+" (addition), so 4*2 will be executed first. Now the expression is a = 8+4; In this "+" has highest preference so addition will be done. The result is equated to a and so a becomes 12.

12

STATEMENTS
If Statement: If statement is used to check or verify a condition and execute a set of statement only if the condition is true. This should be referred as a statement and not as a function. Syntax: if(condition) { // set of statements that will be executed // only if the condition is true or satisfied } Example Code: <script language="javascript"> var a = "if check"; if(a == "if check") { document.write(" inside if statement "); } </script> Result: inside if statement In the above example the condition is to check whether variable 'a' equals (==) the string "if check". As the condition satisfies, the statements inside the brackets are executed. Nested If: Nested if statement is nothing but using an if statement inside another if statement. Nested if is used when we check a condition only when another condition is true. For an example when we purchase a car, first we verify is the car looks good, only if it satisfies we go to the next condition color, then next and so on.. Syntax: Nested if if(condition 1) { if(condition 2) { // set of statements that will be executed } } If-Else Statement: If else statement also has the same format as of "if" statement. Only additional thing is that an else part is added to if statement. So if the condition satisfies the statements inside if part will be executed else the statement inside else part will be executed

13

Syntax: if(condition){ // set of statements if condition satisfies } else{ // set of statements if condition fails } Example Code: <script language="javascript"> var a = "1234abc"; if(a == "adcdefa"){ document.write(" inside if statement "); }else{ document.write(" inside else part of statement "); } </script> Result: inside else part of statement In the above example the condition is to check if variable 'a' equals (= =) "abcdefa". The condition fails as we have assigned a as "1234abc". So the else part is executed. Switch Case Statement: Switch case is used to when a condition may have multiple results and a different set of operation is done based on each result..
Syntax: Switch(condition) { case result1: // Operation for result1 case result2: // Operation for result2 . . . default : // If result belongs to none of the case specified }

Example Code: <script language="javascript"> for(var i=1; i<5; i++) { switch(i) { case 1: document.write("message for case 1 <br>");

14

break; case 2: document.write("message for case 2 <br>"); break; case 3: document.write("message for case 3 <br>"); break; default: document.write("message for case default<br>"); break; } } </script> Result: message for case 1 message for case 2 message for case 3 message for case default In the above example we have used for loop to explain switch case statement. Here each time the value of i is different and increases as 1, 2, 3, 4. There are three case defined for 1, 2, 3. When value is 4, default is executed. with Statement: "with" statement is used when numerous function of an object is used or a function of an object is to be used numerous times. Syntax: with(object) { // Calling the functions or methods of the object } For this example we will use the object "document" and its methods (functions) "write" and attribute "title". Example Code: <script language="javascript"> with(document) { write(" inside with statement <br>"); write(" using with(object) we can call its functions directly <br>"); write (" TITLE -"+title); } </script> Result: inside with statement

15

using with(object) we can call its functions directly TITLE - Javascript (JS) Tutorial - Using with statement example, code, function In the above example you can clearly see that the write function is executed numerous times with out calling document.write() and also title (document.title) is called. You can use any objects with "with" statement. e.g: date, math, etc. You will know more about these objects in later part of the tutorial.

LOOPS
for LOOP: As we state it, for loop is a looping syntax. A set of statements are executed as a loop until a condition is satisfied, the condition is based on an incremental or decremental counter. In other words "Looping statements in javascript are used to execute the same set of code a specified number of times". Syntax: for(intialvalue; condition; increment) { // set of statements that will be executed } As defined in the syntax, for loop takes three parameters, the initial value (e.g i=0), condition - the statements inside "for" will be executed until this condition is satisfied (e.g i<7), increment - this is where we set the initial value to be increased or decreased after each loop. All the three parameters are separated by semicolon ";". For an example, we will consider a situation where we want to add all numbers between one and ten. Example Code: <script language="javascript"> var i=0; var total=0; for(i=1; i<11; i++) { total = total+i; } document.write("--------- The total ------: "+total); </script> Result: --------- The total ------: 45 The example worked as follows, a) Initially we created the for loop by setting variable i as 1. b) then we set the condition that the loop should execute till i is less than 11 (i<11). c) We made the variable to be incremented at the end of each loop (i++) First loop: i=0, i<11 is true so the statement is executed, now the total becomes 0+1=1 and i

16

is incremented to 2. Second loop: now i=1, i<11 is true so the statement is executed, now the total becomes 1+2=3 and i is incremented to 2. this continues till i=11 Last loop: now i=11, i<11 becomes false and the loop ends here. Note: i++ increments the value at the end on the loop, while ++i to increase the value of i at the start of the loop. while LOOP: 'while' loop is used to execute a set of statements repeatedly until a condition works true. The difference between 'for' and 'while' loop is that 'while' does not take counter as an argument. Syntax: while(condition) { // set of statements that will be executed } As defined in the syntax, while loop has only one parameter, condition to be validated. The statements inside "while" will be executed until this condition becomes false. For an example, we will consider a situation where we want to print first 5 number. Example Code: <script language="javascript"> var i=0; while(i<5) { document.write("The value of i is - "+i+" "); i++; } </script> Result: The value of i is - 0 The value of i is - 1 The value of i is - 2 The value of i is - 3 The value of i is - 4 The execution process is as, a) The initialization of the variable "i" as 1 was done before starting the loop. b) In while loop, the condition was checked, the condition is satisfied (true) as i<5 and so the statements are executed. c) In the last line of the statement we has increased or incremented the value of i by 1. So

17

after the end of the loop the pointer goes back to the beginning of the loop and checks the condition. d) Now "i" will be 1 and i is less than 5. The condition satisfies and the statements are executed. This continues till i is 5. e) When i is five, the condition becomes false and the pointer comes out of the loop. Note: The very important thing to note here is the i++ statement. If i++ has not been included 'i' will always be zero, so the condition will always be true and the loop becomes an infinite loop. This will cause memory issue or infinite loading of the page.

do-while LOOP:
'do-while' loop is similar to while loop and the only difference here is that the set of statements are executed first and the condition is checked next. Syntax: do { // set of statements that will be executed } while(condition) Here the statements are added under do loop and while condition is checked at the end of loop. In 'Do While' the statements are executed once even if the condition will fail. An example Example Code: <script language="javascript"> var i=0; do { document.write("Testing DO-While loop"); } while(i!=0) </script> Result: Testing DO-While loop In the example the condition is 'i' should not be equal to zero. The statements are executed and the condition is checked. The condition failed. The pointer comes out of the loop. So the statements are executed once even when the condition fails.

break statement:
Break is a statement used to exit or terminate a loop in execution. It is used in "for, while, do-while" looping statements. Break statement is used mostly with a conditional statement inside the loop. When the condition satisfies the control breaks/terminates from the loop and moves to the next line below the loop.

18

For an example, we will use a for loop that prints 1 to 5 but will use break or exit the loop iteration when i is 3. Example Code: <script language="javascript"> for(var i=0; i<5; i++) { if(i == 3) break; document.write("i is - "+i); } document.write(" --------- After Looping------ "); </script> Result: i is - 0 i is - 1 i is - 2 --------- After Looping-----The example worked as follows, a) "for loop" has five iterations from i=0 to i=4. b) It executes document.write at every iteration for i=0,i=1,i=2. c) when i is 3 the condition above document.write becomes true and so break statement is called. d) break statement exits or terminates the looping sequence and brings the control to the line next to the end of loop.

continue statement:
Continue statement is used to stop or terminate one iteration of the loop in execution. It is used in "for, while, do-while" looping statements. Continue statement unlike break statement does not completely terminate the loop. It stops processing for only one iteration and brings the control back to the beginning of the loop. For an example, we will try to stop processing inside a for loop when i is 2. Example Code: <script language="javascript"> for(var i=0; i<5; i++) { if(i == 2) continue; document.write("i is - "+i); } </script> Result:

19

i is - 0 i is - 1 i is - 3 i is - 4 The example worked as follows, a) This for loop has five iterations from i=0 to i=4. b) It executes document.write at every iteration. c) when i is 2 the condition above document.write becomes true and so continue statement is called. d) continue statement terminates the looping sequence and brings the control to the beginning of loop, starting the next iteration. e) Thus the print was not done for i as 2.

FUNCTIONS
Function Tutorial: A function is nothing but a group or block of statements doing a specific task. Syntax: function name() { // set of statements that will be executed } A function has to be defined in the above syntax. The name "function" followed by the name we choose for the function and then open and close brackets. The statements that will do the specific operation are then group together under this name using braces. A function may or may not return a value. A function may or may not have parameters value. Invoking a function: The statements inside the function will not be executed automatically. We have to invoke or call the function to execute the statements. Just calling the name of the function will invoke the function. i.e. if we write a function with the name "test" calling it as "test();" will invoke the function. Example Code: <script language="javascript"> function test() { document.write(" ---- This is a test function ---- "); } test(); </script>

20

Result: ---- This is a test function ----

Function with Parameters: Syntax: function name(parameter 1,parameter 2,...) { // set of statements that will be executed } In many cases we pass parameters or arguments to functions, these arguments will be used inside the function for required calculations. For an example we will use two numbers to add, subtract using function. Here we write separate function for each operations add, subtract. Example Code: <script language="javascript"> function add(number1, number2) { var c = number1+number2; document.write(" ---- This added value is ---- "+c; } function sub(number1, number2) { var c = number1-number2; document.write(" ---- This subtracted value is ---- "+c; } var a = 7; var b = 3; add(a,b); sub(a,b); </script> Result: ---- This added value is ---- 10 ---- This subtracted value is ---- 4 Here you can clearly see that the two functions where invoked as "add(a,b);" and "sub(a,b);" where a and b are defined variables. You can even call the function directly with the variables as say "add(9,1);". A function can be invoked any number of times with any proper value.

21

Function - Returning a value: Syntax: function name(parameter 1,parameter 2,...) { // set of statements that will be executed return thevalue; } A function can also return a value after doing the specified operations. To explain, we would consider a requirement where we have to calculate x2/2. We will calculate x2 in a function and return the result of x2. After getting the return value, we will divide it by 2. Example Code: <script language="javascript"> function square(number1) { var c = number1*number1; // Now we will return the result return c; } var x = 4; // Here we invoke the function and capture the result var des = square(x); var res = des/2; document.write(" The result - "+res); </script> Result: The result - 8 In the above example we calculate x2 in the function "square(xxx)". We returned the result. Getting the Result: As the function is to return a value, while we invoke the function we assigned a variable to capture the result as "var des = square(xxxx);". Now the result of x2 is assigned to the variable des. Using the variable 'des' further operations were completed. Note: Once the return statement is called in a function it will break, i.e no further statements below it will be executed.

OBJECTS:
STRING OBJECT
An object is nothing but a class or file with a group of functions or methods. In javascript

22

strings are stored as string objects. We can declare a string in either of the two ways a) var sname = "testing string object"; b) var sname = new String("testing string object"); Both results in the same string object. String object contains some predefined function or methods that are extensively used in javascript. String object has the following functions a)length() b) charAt() c) indexOf() d) lastIndexOf() e) substring() f) split() g) toLowerCase() h) toUpperCase() Method or Function: length Description: This will count the total number of characters (length or size) present in the string and returns the value. Example Code: <script language=javascript> var ss = "a character count - size test "; var result = ss.length; document.write(result); </script> Result: 30 Explanation: In the above example, the string is stored in a variable ss. then the function is called as "ss.length". the method counts the total characters in the string and returns it. the result is of variable type, integer. Method or Function: charAt(int) Description: This method takes an integer value as argument and returns the character at that position in the string. The positioning of the string starts from zero to n. i.e. The first character of the string is assumed to be at position zero (0), next at 1 and so on. Example Code: <script language=javascript> var ss = "a string test ";

23

var result = ss.charAt(3); document.write(result); </script> Result: t Explanation: In the above example, the string is stored in a variable ss. then we called the function or method charAt(3), to get the character at position 3 in the string. the positioning is as 0-a, 1- , 2-r, 3-t, .... character at position 3 is 't' and so 't' is returned as result. the result is of variable type, string. Method or Function: indexOf(string) Description: This method takes a character or string as an argument. Searches the given string in the main string and returns the index or starting (first occurrence) position of the string. Returns -1 if the search string is not present in the main string. Example Code: <script language=javascript> var ss = "a string index of test "; var result = ss.indexOf("ri"); document.write(result); </script> Result: 4 Explanation: In the above example, the main string is stored in a variable ss. the method takes a string "ri" as argument. this function searches in main string (ss) for the search string (ri). the first occurrence of the search word is found at the position 4 and is returned as the result. Method or Function: lastIndexOf(string) Description: This method is similar to indexOf() function and takes a character or string as an argument. Searches the given string in the main string and returns the last occurrence position of the string. Returns -1 if the search string is not present in the main string. Example Code: <script language=javascript> var ss = "a last index test "; var result = ss.lastIndexOf("e"); document.write(result);

24

</script> Result: 14 Explanation: In the above example, the main string is stored in a variable ss. the method take a character "e" as argument. the method searches in main string (ss) for the search string "e". "e" is at two positions 10 and 14. last occurrence value 14 is returned as result. Method or Function: substring(integer, integer) Description: Takes two integer arguments. The first argument is the start index and the second argument is the end index. This method returns a part or portion of the main string beginning from begin index to last index. Example Code: <script language=javascript> var ss = " string test "; var result = ss.substring(3,6); document.write(result); </script> Result: rin Explanation: In the above example, the main string is stored in a variable ss. the method substring takes two arguments 3 and 6. this method takes a portion of the string from the position 3 up to 6 and forms a new string. i.e "rin" the result is of variable type string. Method or Function: split(string) Description: It takes one argument called as delimiter. The argument is used to split the string in to an array of string. Every part that comes in between the delimiter is separated as a string. A delimiter can be any string or a character or even blank space. Example Code: <script language=javascript> var ss = "testing-delimiter-split-function"; var result = ss.split("-"); document.write(result); </script> Result: testing,delimiter,split,function Explanation: In the above example,

25

the main string is stored in a variable ss. the method split takes the one argument, here it is "-". the delimiter character "-" is used to split or concatenate the string. any thing that comes in between the delimiter ("-") is separated in to a new string. the result variable is an array of string.

Method or Function: toLowerCase(), toUpperCase() Description: These methods are used to cover a string or alphabet from lower case to upper case or vice versa. e.g: "and" to "AND". Converting to Upper Case: Example Code: <script language=javascript> var ss = " testing case conversion method "; var result = ss.toUpperCase(); document.write(result); </script> Result: TESTING CASE CONVERSION METHOD Converting to Lower Case: Example Code: <script language=javascript> var ss = " TESTING LOWERCASE CONVERT FUNCTION "; var result = ss.toLowerCase(); document.write(result); </script> Result: testing lowercase convert function Explanation: In the above examples, toUpperCase() method converts any string to "UPPER" case letters. toLowerCase() method converts any string to "lower" case letters. Object:

Date

Date is a predefined object in javascript. This object contains methods that can be used to get or set the system date, time, month, day, hours, minutes, seconds, etc.... Contains methods to get and set properties of UTC universal coordinated time. Universal Coordinated Time, UTC is the world time standard also called as Greenwich Mean Time. A new object has to be created before using its methods. Creation of new date object: Example Code: var exd = new Date();

26

Calling "new Date()" will create a new date object. This object can be used to execute its methods or functions. We have to capture the object in a variable. In the example the object it stored in a variable name exd. The below table uses the object exd as an example.
Method getDate() Example Code exd = new Date(); exd.getDate(); Result 17 Description getDate() method returns today's date of the month as in your computer. The range is from 1 to 31. getUTCDate() method return the date value of Universal Coordinated Time. UTC is the world time standard also called as Greenwich Mean Time. getMonth() method returns the Month of this year, as in your computer. The result can range from 0 to 11. 0 for january to 11 for december. getUTCMonth() returns the UTC month of the year, as in your computer. getDay() method returns the day of the week, as in your computer. The result can range from 0 to 6. 0 for Sunday, 1 for Monday, up to 6 for Saturday. getUTCDay() returns the UTC day of the week, as in your computer. getHours() method returns the current hour of the day, as in your computer. The result can range is from 0 to 24. getUTCHours() returns the UTC hours of the day, as in your computer. [Indian Standard Time is 5.30 hours ahead of UTC]. getMinutes() method returns the minutes of this hour, as in your computer. The result can range is from 0 to 59. getUTCMinutes() returns the UTC minutes of the hour, as in your computer. getSeconds() method returns the Seconds of this minute, as in your computer. The result can range is from 0 to 59. getUTCSeconds() returns the

getUTCDate()

exd = new Date(); exd.getUTCDate();

17

getMonth()

exd = new Date(); exd.getMonth();

getUTCMonth()

exd = new Date(); exd.getUTCMonth();

getDay()

exd = new Date(); exd.getDay();

getUTCDay()

exd = new Date(); exd.getUTCDay(); exd = new Date(); exd.getHours();

getHours()

getUTCHours()

exd = new Date(); exd.getUTCHours();

getMinutes()

exd = new Date(); exd.getMinutes();

10

exd = new Date(); getUTCMinutes() exd. getUTCMinutes(); getSeconds() exd = new Date(); exd.getSeconds();

40

15 15

getUTCSeconds() exd = new Date();

27
exd. getUTCSeconds(); getMilliseconds() exd = new Date(); 316 exd.getMilliseconds(); UTC seconds of the minute, as in your computer. getMilliseconds() method returns the milli seconds of current second, as in your computer. Result: 1266370815316 getTime() method returns the current time since 1/1/1970 in milli seconds, as in your computer. getYear() method returns the year since 1900, as in your computer. getFullYear() method returns the full year, as in your computer. toGMTString() method returns the date and time in Internet Greenwich Mean Time Format (GMT).

getTime()

exd = new Date(); exd.getTime();

getYear() getFullYear()

exd = new Date(); exd.getYear(); exd = new Date(); exd.getFullYear(); exd = new Date(); exd.toGMTString();

110 2010 Wed, 17 Feb 2010 01:40:15 GMT

toGMTString()

JavaScript dates are stored as the number of milliseconds since midnight of January 1, 1970. This date is called Opoch date.

OBJECT: MATH
Math object contains the methods or function that can be used to easily do mathematical calculations. Math object is an in built object and so it is not required to instantiate the object as done for Date object. Math also contains pre-defined variables that will give values of important constants like Pi, LN2, log base 10 etc... To use math object: Syntax: Math.methodName() Explanation: To call a math method, just use the name Math followed by its method name, separated by a dot. Example: Math.random() This method call generates a random number. Math object can be categorized as Basic Math Functions

abs() ceil() floor() log() max() min()

28

pow() random() round()

Trigonometric Functions

sin() cos() tan() asin() acos() atan()

Math Variables or Constants


E LN2 LN10 LOG2E LOG10E PI SQRT1_2 SQRT2 Object: Math funcitons Math object has the following methods that can be used to do specific & basic operations like getting random numbers, rounding a number, square root calculation, etc.. in javascript The below table lists the methods that are available for math calculations

Description abs() method returns the absolute value of abs(value) Math.abs(2.822); 2.822 the argument passed. ceil() method returns the nearest greater integer value of the value passed as ceil(value) Math.ceil(3.44); 4 argument. The argument can be an integer or float. floor() method returns the nearest lowest floor(value) Math.floor(2.44); 2 (least) integer value of the argument passed. Result: 1.0986122886681098 log(value) Math.log(3); log(x) function returns the natural logarithm of the value used. Math.max(value1, value2) compares the two max(value1, Math.max(14, 12); 14 values and returns the maximum value of the value2) two values passed. Math.min(value1, value2) compares the two min(value1, Math.min(14, 12); 12 values and returns the minimum value of the value2) two values passed. pow(value1, Math.pow(4, 2); 16 Math.pow(value1, value2) function is used to

Constant

Example Code Result

29
value2) random()
Math.random();

82

round()

Math.round(9.678); 10

calculate xy calculation. Here it is 42. Math.random() gives a random value between 0 and 1. more... Math.round() function is used to round a float (decimal) value to the nearest integer value. i.e. round of 4.5 will give 5, rounding of 4.4 will give 4.

These functions can be used for rounding a number to the nearest greater, lowest values, comparing two numbers, finding log, absolute value, etc.... Next we will look in to function of math object that can be used for trigonometric calculations. Method: Random Math.random() will create a decimal number between 0 and 1 (e.g: 0.833556767). We have to use the following procedure to convert the decimal number to a random number of use.

Creating a random number less than a value:


To create a random number less than any value, we will have to use two functions, random and round of Math object. For an example we will try to create a random number less than 1000 Example: <script language=javascript> var xx = Math.random(); var rnumber = Math.round(xx*1000); document.write(rnumber); </script> Result: 966 In the above example, First a random decimal number was created using Math.random() Now we multiply it with the number below which we want random number to be. Pass is as the argumnet to Math.Round to remove the decimal points. If we would want a number below 100, we would have to use 100 instead of 1000. Object: Trignometric functions We can also calculate trigonometrical values using the predefined math object methods or function. We can calculate sin, cos, tan, arc cosine, arc sine, arc tan values. The get the value for angle or degree, e.g: sin(30o), convert the degree to radians when using Math.sin method. i.e: Math.sin(30*Math.PI/180). The below table lists the methods and their usage.

30
Constant Example Code Result 0.8414709848078965 Description

sin(int) Math.sin(1); cos(int) Math.cos(1); tan(int) Math.tan(1); asin(int) Math.asin(1); acos(int) Math.acos(1); atan(int) Math.atan(1);

Math.sin(x) where x in radians returns the sine value of x. Math.cos(x) returns the cosine value of 0.5403023058681398 x. Math.tan(1) returns the tangent value of 1.5574077246549023 x. Math.asin(x) returns the arc sine value of 1.5707963267948966 radians. Math.acos(x) returns the arc cosine value 0 of radians. Math.atan(x) returns the arc tangent 0.7853981633974483 value of radians.

Object: Math constants or variables Math object has the following variables that give the values of constants like PI, logarithm, Eulers, etc..
Constant E Example Code
Math.E;

Result

Description

2.718281828459045 Math.E returns the Eulers constant. Math.LN2 returns the value of natural Math.LN2; LN2 0.6931471805599453 logarithm of base 2. Math.LN10 returns the constant value LN10 Math.LN10; 2.302585092994046 of natural logarithm to the base 10. Math.LOG2E returns the logarithmic LOG2E Math.LOG2E; 1.4426950408889634 value of E to the base 2. Math.LOG10E returns the logarithmic LOG10E Math.LOG10E; 0.4342944819032518 value of E to the base 10. Math.PI returns the value of constant Math.PI; PI 3.141592653589793 PI. Math.SQRT1_2 returns the Square SQRT1_2 Math.SQRT1_2; 0.7071067811865476 Root of 0.5. Math.SQRT2 returns the value of SQRT2 Math.SQRT2; 1.4142135623730951 Square Root of 2.

Object: Number Number Object does not have any functions that we would be using while writing scripts. Number object has few properties. The properties and methods of GLOBAL object are used in place of number object.
Property MAX_VALUE Description This number is the maximum possible numeric value.

MIN_VALUE

This number is the minimum possible numeric value.

31

NaN

Defines as Not a Number (NaN).

NEGATIVE_INFINITY POSITIVE_INFINITY

This number is negative infinity.

This number is positive infinity.

Object: Global Global object is defined to associate an object with globally accessible variables and functions defined in previous versions of javascript. Global object method can be used or referenced directly. The below table lists the methods that are available in global objects
Description escape(string) method converts the special characters escape(string) escape("test val"); test%20val like space, colon etc of the given string in to escape sequences. eval method evaluates a eval(expression) eval(2*(3+5)); 16 regular expression and returns the result. isFinite(number) method isFinite(number) isFinite(234455); true returns true if the number is finite, else false. isNaN function validate the argument for a number and isNaN(value) isNaN(23); false returns true if the given value is not a number else returns false. unescape(string); function replaces the escape sequences unescape(string) unescape("test%20val"); test val with original values. %20 is the escape sequence for space " ". Method Example Code Result

Thus the global object functions can be used to evaluate a regular expression (eval), validate a number (isNaN), handle escape characters, etc..

Arrays:
Arrays are special type of javascript objects. It is used to store data's in contiguous manner. In other words arrays help you to store similar data's under one name in a defined order. Syntax: var varname = new Array(3);

32

In the above syntax we have declared a new array of size 3 under the name varname. We can create new array only using the syntax new Array. It is case sensitive and so "Array" should not be defined as "array". The size of the array is set as 3. So, we can store 3 variables in the array varname. It can be declared with any size according to our requirement. Assigning Values: Arrays always start from 0th index or position. If we have set the size as 3, the array will have 3 position 0,1 & 2. We can assign values to the array as follows, varname[0] = "testing array"; varname[1] = "position 2"; varname[2] = "position 3"; To assign a value in to an array, we have to call the variable name on which the array was created, followed by the position [where we want to store the value] and then assign the value. Retrieving Values: To retrieve a value from an array is very simple. Just calling the array with its position will retrieve the value at that position in the array. E.g: var val = varname[0]; Example Code: <script language="javascript"> var varname = new Array(2); varname[0] = "testing array"; varname[1] = "position 2"; document.write("Result of array is - "+varname[1]); </script> Result: Result of array is - position 2 The above example shows how to create a new array of size two, add values in to array and retrieve them. In next tutorial chapter, you will learn dense array, dynamic array.. Dynamic Arrays: In many a cases we will not want to create the array with a fixed size or length. In such cases we can create an array with out passing length. This array will dynamically set its value as and when a new variable or entry is added. Syntax: var araay = new Array();

33

Now we can assign value at any position in this array as it has no length limit. We can test this by using the attribute "length". e.g: varname[6] = "testing array"; As we have assigned a value at 6th position the length of array will now be 7. Example Code: <script language="javascript"> var araay = new Array(); araay[6] = "testing array"; document.write("Size of dynamic array is - "+araay.length); </script> Result: Size of dynamic array is - 7 Dense Array: Dense array is nothing different in functionality from a normal array. The only difference is that the values are assigned to the array at the time of initialization of the array. E.g: var arraa = new Array("index 0","index 1","index 2"); Example Code: <script language="javascript"> var arraa = new Array("array test 1","array test 2"); document.write("Result from dense array is - "+arraa[1]); </script> Result: Result from dense array is - array test 2 In the next chapter we will look into the predefined methods of Array object ..

Array Methods :
Array has the following predefined methods. toString() joint() reverse() sort() Method: toString() : This method is used to convert the array elements in to a string. The string will have each element in the array separated by comma(,). Example Code: <script language="javascript"> var varname = new Array();

34

varname[0] = "testing to string 1"; varname[1] = "testing to string 2"; document.write("toString -- "+varname.toString()); </script> Result: toString -- testing to string 1,testing to string 2 Method: join() : This method is used to join the elements in the array separated by a separator. This function is much similar to toString method. Here we can specify the delimiter or separator that comes instead of comma. Example Code: <script language="javascript"> var aarray = new Array(); aarray[0] = "element 1"; aarray[1] = "element 2"; var xx = aarray.join(" +++ "); document.write("join() -- "+xx); </script> Result: join() -- element 1 +++ element 2 Method: sort() : This method is used for sorting elements in the array. The values will be sorted in a dictionary order. Example Code: <script language="javascript"> var sorting = new Array(); sorting[0] = "b for balloon"; sorting[1] = "d for donkey"; sorting[2] = "a for apple"; aarray.sort(); document.write("sort function -- "+sorting.toString()); </script> Result: sort function -- a for apple,b for balloon,d for donkey Method: concat() : This function is used to concat two or more arrays into a single array. The concatenation function appends the second array with first array. Syntax: array1.concat(array2,array3,...arrayx);

35

Example Code: <script language="javascript"> var alphabets = ["a", "b","c"]; var numbers = ["1", "2"]; var symbols = ["@", "$","^"]; var alphano = alphabets.concat(numbers,symbols); document.write(alphano); </script> Result: a,b,c,1,2,@,$,^ Thus, array concatenation can be carried out by using this function. Method: pop() : This method is used to delete the last element of an array and to return the deleted element. The length of the array gets affected by this function. Syntax: array1.pop(); Example Code: <script language="javascript"> var stack=["a","b","c","d"] var ele = stack.pop(); document.write(ele); </script> Result: d Method: push() : This function add new elements to the end of array and gives the length of the array as the return value Syntax: array1.push(element1,element2,...); Example Code: <script language="javascript"> var stack=["0","1"] var leng = stack.push(2,3); document.write(leng); </script> Result: 4 Thus, to add new elements, this method can be used.

36

Method: shift() : This function delete the first element of the array and shift the index of the subsequent elements to the lower value to occupy the vacant space and returns the deleted element. Syntax: array1.shift(); Example Code: <script language="javascript"> var a=["H","E","L","L","O"]; var ele = a.shift(); document.write(ele); </script> Result: H Method: unshift() : This function add new elements into the Beginning of the array and shift the index of the subsequent elements to the higher value. It also returns the new length of the array. Syntax: array1.unshift(); Example Code: <script type="text/javascript"> var a["a","b","c","d"] var ele = stack.unshift(3); document.write(ele); </script> Result: 5 In the above example, this method add new element to the beginning of the array and has displayed the result as"5". Method: slice() This function is used to select a part of an array. The resultant new array contains the element specified by the first argument and all the subsequent elements but not including the element specified by the second argument. Syntax: array1.slice(firstargument,secondargument); Example Code for this method: <script language="javascript"> var name = ["john", "peter","samuels","joseph","marry"]; var subarray = name.slice(1,3); document.write(subarray); </script>

37

Result: peter,samuels To Select a part of an array, this function is used and the result is displayed. Method: splice() : This function is used to insert or delete element in the given array. It returns deleted items. Note: The method modifies the value of the original array. Syntax: array1.splice(argument1,argument2,.....); argument1 - specifies the array position in which the insertion/deletion to be performed. argument2 - specifies the number of elements should be deleted. The arguments following after second argument specifies the elements that are to be included after the first argument. Example Code:Deleting elements <script type="text/javascript"> var name = ["john", "peter","samuels","joseph","marry"]; var subarray = name.splice(1,3); document.write(subarray); </script> Result: peter,samuels,joseph Example Code:Inserting elements <script type="text/javascript"> var name = ["john", "peter","samuels","joseph","marry"]; name.splice(1,0,"reobuck","ram"); document.write(name); </script> Result: john,reobuck,ram,peter,samuels,joseph,marry

COOKIES

38

Cookies were originally invented by Netscape to give 'memory' to web servers and browsers. The HTTP protocol, which arranges for the transfer of web pages to your browser and browser requests for pages to servers, is state-less, which means that once the server has sent a page to a browser requesting it. Cookies were invented to solve this problem. A cookie is a well-known computer science term that is used when describing an opaque piece of data held by an intermediary. Cookie consists of 6 parameters that can be passed to it. They are: Syntax: setCookie(cookieName, cookieValue[, expire[, path[, domain[, isSecure]]]] ) * The name of the cookie, * The expiration date of the cookie, * The path the cookie is valid for, * The domain the cookie is valid for, * The need for a secure connection to exist to use the cookie. Name=Value: This sets both the cookie's name and its value. Example: username=john Expire=Date: This optional value sets the date that the cookie will expire on. The date should be in the format returned by the toGMTString() method of the Date object. If the expire value is not given, the cookie will be destroyed the moment the browser is closed. Example: expires=02/02/2010 00:00:00 Path=Path: This optional value specifies a path within the site to which the cookie applies. Only documents in this path will be able to retrieve the cookie. Usually this is left blank, meaning that only the path that set the cookie can retrieve it. Example: path=/hscripts/tutorials Domain=Domain: The domain parameter is used to set the domain the cookie is accessable to. A path can be set for your own domain only and the domain path must include at least two periods (.domain.com). It must match your server's domain name. Therefore cookies are not a security risk since only the server that sets them can use them. Example: domain=tofocus.info Secure: This optional flag indicates that the browser should use SSL when sending the cookie to the server. This flag is rarely used. Example: secure These are the parameters to be checked to set cookie.

39

A cookie is nothing but a variable that is stored in the browsers. With JavaScript, you can set, get or delete the cookie values. There are three types of cookie functions in javascript. They are: setcookie() - Used to set the cookies getcookie() - Used to retrive the cookies deletecookie() - Used to delete the cookies The setCookie function is used to set the cookies in javascript. Example to set cookies, expiry date, value: function setCookie(c_name,value,expiredays) { var exdate=new Date();//assigns the current date to the variable exDate exdate.setDate(exdate.getDate()+expiredays);//sets the expiry date document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());//sets the cookie } The above function sets the name of the cookies with its value along with the expiry date of the cookie. The get_cookie() function is used to retrive the cookies in javascript. Example function get_cookie(c_name) { if (document.cookie.length>0)//checks for the availability of cookie name { c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start,c_end));//returns the cookie after decoding } } return ""; } The above function gets and retrive the name of the cookies with its value along with the expiry date of the cookie. The del_cookie() function is used to delete the cookie in javascript. Deleting cookies is extremely simple, (i.e.) set the cookie with an expiry date of one day ago.

40

Example function del_cookie(name) { document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;'; } The above function deletes the name of the cookie which has been set already by setting the expiry date of the cookies one day before.

Browser Objects
In addition to the objects we have seen in the previous chapters there are browser objects. These objects deal with the characteristic and properties of the web browser. These browser objects are arranged with parent child relationship. The following diagram shows the hierarchy of browser object.

Hierarchy Diagram of Browser Objects Window Object is the topmost and all other objects precede it. Browser Objects document, history and navigator form the next order in the hierarchy. We will look deep in to each object in the coming chapters. Window being the topmost object doesn't require any reference while using its child objects. E.g: for making an alert, its enough if we call document.alert(), it's not required to use window.document.alert(). WINDOW OBJECT: Any browser that is used to access a html document forms the Window Object. Whenever we open a new window, a new window object is created. As seen earlier, Window is the topmost object in the hierarchy. It has many properties that can be used to get information about the window. It also has methods that can be used to do specific tasks. The following topics will introduce you to the

41

properties, methods and their usage. Properties Supported by Window object Methods or Functions under Window object The following tutorials explain the functions in detail a)Using confirm method b)Using prompt method c)New Window using javascript d)Using close method e)Timed execution of functions using setTimeout f)Cancel a timeout using clearTimeout Window Object Property: The following table lists the properties that can be used to get parent window, location as string url, name, status etc.. associated with Window object. All the tests will return the property of current page.
Property closed status defaultStatus document frames history length location name opener parent self top Description Property "Closed" is used to identify whether a window is closed. Returns true if the window is closed. Property "status" is used to get the current status of the browser window. i.e It will say loading, if the page is loading. The message is as shown in the status bar. Property "defaultStatus" is used to declare the default status of the browser window. Returns the document object of the current browser page. All its properties and methods will be handled in the coming chapters. Returns an array containing all the frame objects present in the browser window. Returns the history object of the current window. All its properties and methods will be seen in the coming chapters. Returns an integer defining the number of frames in the page being tested. Property 'location' - returns the full url path of the document viewed as string. Property 'name' - is used to find the name of the browser window. Return empty string if no name was given. Property 'opener' - Used to identify the object from which the window under testing was created . Property 'parent' - Used to identify the parent window object . Property 'self' - Returns the instance of the current window. Property 'top' - Used to get the topmost browser window in a series of nested windows.

42

Window Object Functions: The following table lists the methods associated with Window object.
Method alert() confirm() prompt() open() close() scroll(x,y) blur() focus() setTimeout() clearTimeout() Description Method "alert('message string')" is used to popup an alert message. Method "confirm('message string')" is used to display a confirm dialog box. Method "prompt('message string')" is used to get user input. Method "open(url, name)" is used to open a new window using javascript. Method "close()" is used to close a window using javascript. Method "scroll(x, y)" is used to move a window to a new position of at axis x,y. Method "blur()" is used to remove focus from the window. To test this, open two or more windows and test. Method "focus()" is used to bring a window in focus. Method "setTimeout()" is used to execute an expression or function after a time interval. Method "clearTimeout()" is used to clear a timeout set using the above method.

Method or Function: confirm(string) Description: This method is used to interact with user by popping up a message window and getting a confirmation. It takes the message as argument. Then shows a popup dialog box with the message and two buttons "ok" and "cancel". If user selects "ok" it returns true, else return false. We can get the returned value and do our action. Example: For an example we will popup a message. If the user confirms, we will set the size of a text field as 4 else 10. Example Code: <form name=tett> <input type=text name=tf value="testing confirm function" size=20> </form> <script language=javascript> var df = confirm(" can we change the size to 4"); if(df) document.tett.tf.size = 4; else document.tett.tf.size = 20; </script> Result:
testing confirm functio

43

Explanation: In the above example, first we created a form named tett. form containing a text and button. in the javascript code, we popup a message using confirm function. the return value is captured in the variable named df. if user clicks "ok" df will be true and the if portion will be invoked and the size of text field is set to 4. Method or Function: prompt(string) Description: This method is used for getting dynamic user input or data. It takes the message as argument. User is prompted with input box to enter the data. Example: For an example we will prompt a message box asking for his name. Once the user enters the name we will get it and show it in the text field. Example Code: <form name=tett> <input type=text name=tf value="testing prompt" size=15> </form> <script language=javascript> var df = prompt(" enter your name "); document.tett.tf.value = df; </script> Result:
testing prompt

Explanation: In the above example, first we created a form named tett. form containing a text and button. in the javascript code, we invoke a prompt box with a message. we get the user input in the variable named df. we set the name as value to the text field tf. Method or Function: open(url,name[,properties]) Opening a new window: Open method or function is used to create or open new browser window in javascript. We have to pass two arguments url path and a name for that window. The window will be blank if you pass empty string ("") for url. Example: Opening a link/url on button click

44

Code: <script language=javascript> open("http://www.hscripts.com","test"); </script>


Opening a new window with specified size, height, location, menu, status, scroll bar, etc..:

The new browser window can be created with specified height, width, location and other properties. These properties have to be passed as the third argument separated by comma. Syntax: open("url","name","height=200,width=200,location=true,..."); The following table shows all the possible option that can be used while opening a new browser window.
Option Height Values Integer Description used to set the height of the new window. used to set the width of the new window. used to display / hide the location bar in the new window. location bar is the place in the browser where the url is displayed. if resizable is set to yes, window resizing can be done by users. By default the window resizing is disabled. used to display/hide the Menu bar in the new browser window. Scrollbars option is used to display/hide scroll bars in the new browser window. Status option is used to display / hide the status bar in new browser window. Toolbar option is used to display / hide the tool bar in new browser window. Example Code: open("","","height=150"); Code: open("", "", "height=150,width=150"); Code: open("", "", "height=250,width=250, location=yes"); Code: open("", "", "height=250,width=250, resizable=yes"); Code: open("", "", "height=250,width=250, menubar=yes"); Code: open("", "", "height=250,width=250, scrollbars=yes"); Code: open("", "", "height=250,width=250, status=yes"); Code: open("", "", "height=250,width=250, toolbar=yes");

Width

Integer

Location Boolean

Resizable Boolean

Menubar Boolean

Scrollbars Boolean

Status

Boolean

Toolbar Boolean

Method or Function: close() Closing current window: Closing the current page or window is very simple. Just calling close() or this.close() will close the window.

45

Closing a newly opened window: Closing the window that was created or opened by open method. For this we should use the reference that we obtain when the new browser window is created. The procedure is as follows a) On opening a window, store the return object (window) in a variable e.g: var xcv = open('url','name'); b) call close function or method on that window object e.g: xcv.close(); Example: This example will close the window when a button click is done. Code: <script language=javascript> function closer() { this.close(); } </script> <form name=xcv> <input type=button onClick="closer()" value="click to close"> </form> Method or Function: setTimeOut() Syntax: setTimeout(name,milliseconds); setTimeout method is used to execute an expression or function after a specified (set) time gap/interval. It takes two arguments, - first the expression or function to be invoked, inside quotes - second the time interval in milliseconds after which the execution will take place. It's similar to setting a timer. Example Code: <script language=javascript> function testtimeout(){ setTimeout("printer()",3000); } function printer(){ alert(" test set time out"); } </script> <form name=xcv> <input type=button onClick="testtimeout()" value="test time out"> </form>

46

Result: In the above example, in function testtimeout() we invoke printer() method using setTimeout and set the interval as 3 seconds. So the alert will popup after three seconds once testtimeout is executed. Repeated Actions: To make a repeated action after a specified time gap, we have to use setTimeout() inside the same function, which does the action. Example: This example will repeatedly add 1 to a number and show it after every 3 seconds (3000 milliseconds) . Code: <script language=javascript> var x = 0; function testtimeout() { x = x+1; alert(" value of x is - "+x); setTimeout("testtimeout()",3000); } </script> <form name=xcv> <input type=button onClick="testtimeout()" value=close> </form> Method or Function: clearTimeout() Syntax: clearTimeout(instance-name); To stop or clear a timeout execution we can use the method clearTimeout. For using the method we should use the identifier or instance of the setTimeout. The steps are as follows a) Capture the instance or identifier of the time out call in a variable while calling setTimeout Example: var ctime = setTimeout("xxxxx",30000); b) use the identifier as argument to stop or clear or cancel the timeout call. clearTimeout(ctime); Example:

Example: This example will repeatedly add 1 to a number and show an alert after every 3 seconds (3000 milliseconds). clearTimeout will be called once you click stop button and will cancel the repeated execution. Code: <script language=javascript> var x = 0; var timer; function testtimeout(){ x = x+1; alert(" value of x is - "+x); timer = setTimeout("testtimeout()",3000); }

47

function stoper() { clearTimeout(timer); } </script> <form name=xcv> <input type=button onClick="testtimeout()" value=start> <input type=button onClick="stoper()" value=stop> </form>

DOCUMENT OBJECT:
The complete html portions that a user can write and display on a browser window forms the document object in javascript. Document object is the parent to access any html element. The following are the properties that can be used with document object.
Property Description Example Code To Set: e.g: document.alinkColor = "green"; Code To Get: e.g: var dd = document.alinkColor;

alinkColor

Property "alinkColor" is used to set and get value for alink attribute of body tag.

anchor

Property "anchor" is the object reference of an anchor contained in the document. Code To Get: Property "anchors" is used to get an var dd = document.anchors; array of all the anchor objects in the var total = dd.length; document. Property "bgColor" is used to set background color or get the background color attribute of body tag. Code To Set: document.bgColor = "blue"; Code To Get: var dd = document.bgColor;

anchors

bgColor

cookie domain

embeds

fgColor

form

Property "cookie" is used to identify the value of a cookie. Property "domain" is used to get the Code To Get: domain name of the server from var dd = document.domain; which the document is loaded. Property "embeds" is return an array Code To Get: containing all the plugins contained in var dd = document.embeds; the document. alert(dd.length); Code To Get: Property "fgColor" is used to set/get var dd = document.fgColor; the foreground color attribute of body Code To Set: tag. document.fgColor = "fefaaa"; Property "form" is the object reference of a form object contained in the document.

48
Property "forms" is used to get an array of all the form objects in the document page. Property "image" is the object reference of an image object contained in the document. Property "images" is used to get an array of all the image objects in the document or web page. Property "link" is the object reference of a link object contained in the document. Property "links" is used to get an array of all the link objects in the document or web page. Property "linkColor" is used to set/get value of link attribute of body tag. Code To Get: var dd = document.forms; var length1 = dd.length;

forms

image

images

Code To Get: var dd = document.images; var img = dd[0].width;

link

links

Code To Get: var dd = document.links; var link1 = dd[0]; Code To Get: var dd = document.linkColor;

linkColor

lastModified

referrer

title

Code To Set: document.linkColor = "afefaa"; Property "lastModified" is used to get Code To Get: the time at which the document or var dd = document.lastModified; web page was last modified. Property "referrer" is used to get the Code To Get: url or link of the referrer document or var dd = document.referrer; web page from which the user has reached this page. Code To Get: var dd = document.title; Property "title" is used to set or get title of the document using Code To Set: javascript. document.title = "test title"; Property "url" is used to get the url string of current page or document. Property "vlinkColor" is used to get/set the "visited link" color attribute of body tag. Code To Get: var dd = document.url; Code To Get: var dd = document.vlinkColor; Code To Set: document.vlinkColor = "afafdd";

url

vlinkColor

HISTORY OBJECT:
History Object has the complete list, information of url/links visited during this session. Its methods or functions can be used to move forward(next page) or backward(previous page). We can also go to any link or url page in the history list. History object also has the following properties
Property next Description Property "next" represents the next page url in the history object list, if any.

49
Property "previous" represents the previous page url in the history object list, if any. Property "current" represents the current page url in the history object

previous

current

length

Property "length" returns the number of objects in the history list.

Methods or Function: The following are the methods defined under history object.

back() forward() go()

Methods or Function: back()

back() function is used to go back to the previous web page in the history list. This does the same function as of back button in the browser window. Code: history.back(); Example: To create a back button that takes to the previous page when users click on it. Code: <script language="javascript"> function goback(){ history.back(); } </script> <input type=button value="go back" onClick=goback()>
Result:

In the above example a) we created a button b) added an onClick event listener to the button. c) when user click on the button the javascript function goback() will be invoked. d) in that function we call history.back(). Methods or Function: forward() forward() function is used in javscript to go to the next page in the history list. This does the same function as of next button in the browser window. Code: history.forward(); Example: To create a button that takes to the next page when users click on it using javascript. Code: <script language="javascript"> function gonext(){ history.forward();

50

} </script> <input type=button value="go next" onClick=gonext()> Result: To test this go to next web page, come back and do the testing In the above example a) we created a button b) added an onClick event listener to the button. c) when user clicks on the button the javascript function gonext() will be invoked. d) in the gonext() function we call history.forward(). Methods or Function: go() go() function takes one argument. It can take an integer argument or a string argument. Code: go(n); where n can be a negative, zero or positive integer. a) if n<0, it takes to the previous pages in the history list. i.e go(-1) takes to previous page, go(-2) takes two page back and so on.. b) if n=0, nothing happens c) if n>0, it takes to the next pages in the history list. i.e go(1) takes to next back, go(2) takes two pages ahead and so on.. Example: To create a button that loads two pages backward using javascript. Code: <script language="javascript"> function gourl(){ history.go(-2); } </script> <input type=button value="go back" onClick=gourl()> Result: In the above example a) we created a button b) added a onClick event listener to the button. c) when user clicks on the button the javascript function gourl() will be invoked. d) in the function we call history.go(-2) to go two steps backward.

NAVIGATOR OBJECT:
Navigator object in javascript contains the information about the client browser window. The following table lists the properties of navigator object. Not all browsers have same

51

navigator properties. Internet Explorer may have some properties that may not be there in mozilla and vice versa.
Property appCodeName appName appVersion language Description Result

mimeTypes

platform

plugins

userAgent

appCodeName is used to get the code Mozilla name of the browser appName is used to get the name of the Netscape browser appVersion is used to get the version of 5.0 (Windows; en-US) the browser property "language" is used to get the language configured in browser en-US preference. property "mimeTypes" is used to get an array of mimeTypes supported by the [object MimeTypeArray] browser property "platform" will return the OS(operating system) in which the Win32 browser is running (e.g: Win32, linux, etc..) property "plugins" is used to get an array [object PluginArray] of plugins installed in the browser. property "userAgent" is used to get the Mozilla/5.0 (Windows; U; user-agent header. user agent string Windows NT 6.1; en-US; information will be added in the HTTP rv:1.9.2) Gecko/20100115 protocol used for data transfer from Firefox/3.6 browser to the server.

The result part in the above table shows the browser properties like name, version, language, platform, userAgent or user agent string , etc... of the browser you are using currently.

Dynamic Object Model (DOM):


Before going ahead to learn about form object and event handling, we should know where they belong too. Any action or event that causes a dynamic change in a web page using javascript should be grouped under DOM (dynamic object model). Every html element can be accessed and changed dynamically using javascript DOM. The W3C 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 Document Object Model (DOM) is an application programming interface (API) for valid HTML. All html elements and their attributes can be accessed through the DOM tree. Their contents can be modified or deleted, new elements can be created by using DOM. For an example, the form with name "ssss" in a html document can be accessed as document.ssss;

52

Event Handling: Events are action that occur on a web page and are mostly triggered by users. There are in build handler programs to handle those events. For an example: we will consider a form button or a link. Say when a user moves the mouse over it, a mouse over event is triggered. We can capture such events and invoke a javascript function to do an action. The event handler is usually added as an attribute to html tag. A mouse over event is captured using the handler onMouseOver. In the below example we will do an alert when a mouse is moved over a button. Example Code: <script language="javascript"> function testdom() { alert("on Mouse Over"); } </script> <input name=xx type=button value=click onMouseOver="testdom()"></input> Result: Step 1: We created a form button Step 2: Invoked mouse over handler using the attribute onMouseOver and passed the javascript function testdom as its value. So testdom() method will be called when a mouse over event occurs. Step 3: We wrote a javascript function testdom() and called an alert inside the function. In the coming chapters you will learn about the event handlers that are associated with each form types and DOM methods that can be used with form elements.

Button Object :
Button is one of the most commonly used form types. The following syntax will get the button object in javascript Syntax: document.formname.buttonname Example Code: <form name=buttonform> <input name=button1 value=test type=button> </form> <script language="javascript"> var buttonobject= document.buttonform.button1; </script> Here are the events, dom properties and method associated with button element. Event Handlers: Associated with Form Button: All the example below use a javascript function output

53

<script language=javascript> function output() { alert("testing button events"); } </script> Event Handler Description This is invoked when a mouse is onMouseOver moved over the button This is invoked when a mouse is onMouseOut moved over and then out of the button This is invoked when a mouse is onMouseDown pressed down on the button This is invoked when a mouse is onMouseUp pressed down on the button and released "onClick" function is invoked when a onClick mouse click is done on the button Executes some code when the button onBlur loses focus using tab Executes some code when the button onFocus gets focus using tab DOM Properties: The following are the list of DOM (Dynamic Object Model) properties that can be used to get and alter button properties in javascript. The below examples are based on the form <form name=testb> <input name=myb type=button value=xxx> </form> DOM Description Property name Used to get button's name Example To Get: var ss = document.testb.myb.name; To Get: var ss = document.testb.myb.type; To Get: var ss = document.testb.myb.value; To Set:: document.testb.myb.value = "testy"; Example <input type=button onMouseOver="output()"> <input type=button onMouseOut="output()"> <input type=button onMouseDown="output()"> <input type=button onMouseUp="output()"> <input type=button onClick="output()"> <input type=button onBlur="output()"> <input type=button onFocus="output()">

type

Used to get form type

value

Used to set or get button's value

54

Used to disable or enable a button. By setting this disabled property as true we can disable. DOM Methods:

To Disable: document.testb.myb.disabled = true; To Enable:: document.testb.myb.disabled = false;

The following are the list of DOM (Dynamic Object Model) methods that can be used to do dynamic changes like button click using javascript. DOM Method click() blur() focus() Description Used to dynamically make a button click Used to dynamically make the button blur Used to dynamically get focus on the button Example To Click: document.testb.myb.click(); To Blur: document.testb.myb.blur(); To Focus: document.testb.myb.focus();

Example: Change Button value on mouse over <script language=javascript> function bevent() { var xx = document.xx.btest; xx.value= "testing button event"; } </script> <form name=xx> <input type=button name=btest onMouseOver="bevent()"> </form>

Checkbox Object :
The following syntax will get the checkbox object in javascript Syntax: document.formname.checkboxname Example Code: <form name=testform> <input name=cb1 value=test type=checkbox> <input name=cb2 value=test2 type=checkbox> </form> <script language="javascript"> var cbobject= document.testform.cb1; </script> The object cbobject is an array of check box element. To use the first check box, we have to

55

call cbobject[0], for second box it is cbobject[1] and so on.. Here are the events, dom properties and method associated with checkbox element. Event Handlers: Associated with Form type Check Box: All the examples below use a javascript function output <script language=javascript> function output() { alert("testing checkbox events"); } </script> Event Handler Description Example This is invoked when a mouse is <input type=checkbox onMouseOver moved over the checkbox onMouseOver="output()"> This is invoked when a mouse is <input type=checkbox onMouseDown pressed down on the checkbox onMouseDown="output()"> This is invoked when a mouse is <input type=checkbox onMouseUp pressed down on the checkbox and onMouseUp="output()"> released onClick is invoked when a mouse click <input type=checkbox onClick is done on the checkbox onClick="output()"> Executes some code when the check <input type=checkbox onBlur box loses focus using tab onBlur="output()"> Executes some code when the check <input type=checkbox onFocus box gets the focus using tab onFocus="output()"> DOM Properties: The following are the list of DOM (Dynamic Object Model) properties that can be used to get and alter checkbox properties in javascript. The below examples are based on the form <form name=testb> <input name=mycb type=checkbox value=111> box1 <input name=mycb type=checkbox value=222> box2 </form> DOM Property Description Example To Check: Used to check or select checkbox. Each element has to var ss = document.testb.mycb[0].checked; var ss1 = document.testb.mycb[1].checked; be checked individually. The To Select: element if selected will return document.testb.mycb[0].checked = true; true else false. To Get: var ss = document.testb.mycb[0].defaultChecked;

checked

Used to check whether the defaultChecked check box is selected by default

56

form

Used to get the parent node (form object) of this check box Used to get checkbox name

To Get: var ss = document.testb.mycb[0].form; To Get: var ss = document.testb.mycb[0].name; To Get: var ss = document.testb.mycb[0].type; To Get: var ss = document.testb.mycb[0].value; To Set:: document.testb.mycb[0].value = "testy";

name

type

Used to get form type

value

Used to set or get checkbox value

DOM Methods: The following are the list of DOM (Dynamic Object Model) methods that can be used to do dynamic changes like dynamic check box selection, using javascript. DOM Method click() blur() focus() Description Used to dynamically make a checkbox checked Used to dynamically make the check box blur Used to dynamically get focus on the check box Example To Click: document.testb.mycb.click(); To Blur: document.testb.mycb.blur(); To Focus: document.testb.mycb.focus();

Example: Making Check Box Select on Mouse Over <script language=javascript> function cbevent() { var xx = document.xx.cbtest; xx.checked = true; } </script> <form name=xx> <input type=checkbox name=cbtest onMouseOver="cbevent()"> Checking </form> Result: Checking

Radio Button Object :

57 The following syntax will get the Radio Button object in javascript

Syntax: document.formname.radioname
Example Code:

<form name=testform> <input name=rb1 value=test type=radio> <input name=rb2 value=test2 type=radio> </form> <script language="javascript"> var rbobject= document.testform.rb1; </script> The object cbobject is an array of radio elements. To use the first radio button, we have to call rbobject[0], for second box it is rbobject[1] and so on. Here are the events, dom properties and method associated with Radio Button element. Event Handlers: Associated with Form type Radio Button: All the examples below use a javascript function output <script language=javascript> function output() { alert("testing RadioButton events"); } </script> Event Handler Description Example This is invoked when a mouse is moved <input type=radio onMouseOver over the Radio Button onMouseOver="output()"> This is invoked when a mouse is <input type=radio onMouseDown pressed down on the Radiobutton onMouseDown="output()"> This is invoked when a mouse is <input type=radio onMouseUp pressed down on the radio and released onMouseUp="output()"> This is invoked when a mouse click is <input type=radio onClick done on the radio onClick="output()"> Executes some code when the Radio <input type=radio onBlur Button loses focus using tab onBlur="output()"> Executes some code when the radio <input type=radio onFocus button gets the focus using tab onFocus="output()"> DOM Properties: The following are the list of DOM (Dynamic Object Model) properties that can be used to get and alter RadioButton properties in javascript. The below examples are based on the form <form name=testrb> <input name=myrb1 type=radio value=xxx> Checking 1

58

<input name=myrb2 type=radio value=xxx> Checking 2 </form> DOM Property Description Example To Check: var ss = document.testb.myrb[0].checked; To Select: document.testb.myrb[1].checked = true; This will select second element. Used to check whether the Radio defaultChecked Button is checked by default Used to get the parent node (form form object) of this RadioButton name Used to get Radio Button name Used to get form type To Get: var ss = document.testb.myrb[0].defaultChecked;

checked

Used to check or select RadioButton selection

To Get: var ss = document.testb.myrb[0].form; To Get: var ss = document.testb.myrb[0].name; To Get: var ss = document.testb.myrb[0].type; To Get: var ss = document.testb.myrb[0].value; To Set:: document.testb.myrb[0].value = "testy";

type

value

Used to set or get RadioButton value

DOM Methods: The following are the list of DOM (Dynamic Object Model) methods that can be used to do dynamic changes like dynamic Radio Button selection using javascript. DOM Method click() blur() focus() Description Used to dynamically make a Radio Button checked Used to dynamically make the Radio Button blur Used to dynamically get focus on the Radio Button Example To Click: document.testb.myrb.click(); To Blur: document.testb.myrb.blur(); To Focus: document.testb.myrb.focus();

Example: Making Radio Button Select on Mouse Over <script language=javascript> function rbevent()

59

{ var xx = document.xx.rbtest; xx.checked = true; } </script> <form name=xx> <input type=radio name=rbtest onMouseOver="rbevent()"> Checking </form> Result: Checking

Text Object :
The following syntax will get the Text Field input box object in javascript Syntax: document.formname.textname Example Code: <form name=testform> <input name=textn value=test type=text> </form> <script language="javascript"> var cbobject= document.testform.textn; </script> Here are the events, dom properties and method associated with Text element. Event Handlers: Associated with Form type Text Field: All the examples below use a javascript function output <script language=javascript> function output() { alert("testing Text events"); } </script> Event Handler Description Example <input type=text onMouseOver is invoked when a mouse onMouseOver="output()"> onMouseOver is moved over the text field test Result: <input type=radio onMouseDown is invoked when a mouse onMouseDown="output()"> onMouseDown is pressed down inside the input box test Result: onMouseUp is invoked when a mouse is <input type=text onMouseUp pressed down inside the text field and onMouseUp="output()"> released

60
test

onClick

onBlur

onFocus

Result: <input type=text onClick is invoked when a mouse click is onClick="output()"> done inside the input box test Result: <input type=text onBlur Executes some code when the text onBlur="output()"> field loses focus using tab test Result: <input type=text onFocus Executes some code when the onFocus="output()"> text field gets the focus using tab test Result:

DOM Properties: The following are the list of DOM (Dynamic Object Model) properties that can be used to get and alter Text Field properties in javascript. The below examples are based on the form <form name=form1> <input name=testf type=text value=xxx> </form> DOM Property Description Example To Get: var ss = document.form1.textf.defaultValue; To Get: var ss = document.form1.textf.form; To Get: var ss = document.form1.textf.name; To Get: var ss = document.form1.textf.type; To Get: var ss = document.form1.textf.value; To Set:: document.form1.textf.value = "testy"; To Get: var ss = document.form1.textf.size; To Set:: document.form1.textf.size = 4; To Check:

Used to get and set the defaultValue default value of the text field Used to get the parent node (form object) of form this Text Node name Used to get Text Field name Used to get form type

type

value

Used to set or get Text Field value

size

Used to set or get Text Field size Used to check or

readOnly

61

change readonly property. Users cannot enter any value if the text field is set as readonly.

var ss = document.form1.textf.readOnly; To Set:: document.form1.textf.readOnly = true;

DOM Methods: The following are the list of DOM (Dynamic Object Model) methods that can be used to do dynamic changes like dynamic text field selection using javascript. DOM Method select() blur() Description Used to dynamically select a text field Used to dynamically make the Text Field blur Used to dynamically get focus on the Text Field Example To Select: document.form1.textf.select(); To Blur: document.form1.textf.blur(); To Focus: document.form1.textf.focus();

focus()

Example: Making Text Field Select on a button Mouse Over <script language=javascript> function rbevent() { var xx = document.xx.testtext.focus(); } </script> <form name=xx> <input type=text name=testtext"> <input type=button name=rbtest onMouseOver="rbevent()"> </form> Result:
test

Text Area Object :


The following syntax will get the TextArea object in javascript Syntax: document.formname.textarea Example Code: <form name=testform> <textarea name=textn > testing text area </textarea> </form>

62

<script language="javascript"> var cbobject= document.testform.textn; </script> Here are the events, dom properties and method associated with Text element. Event Handlers: Associated with Form type Text Area All the examples below use a javascript function output <script language=javascript> function output() { alert("testing TextArea"); } </script> Event Handler Description Example <textarea name=textn onMouseOver="output()"> testing text onMouseOver is invoked when a area </textarea> onMouseOver mouse is moved over the text area
testing text area

Result: <textarea name=textn onMouseDown is invoked when a onMouseDown="output()"> testing text onMouseDown mouse is pressed down inside the area </textarea> text area Result: <textarea name=textn onMouseUp="output()"> testing text area onMouseUp is invoked when a </textarea> onMouseUp mouse is pressed down inside the text area and released testing text area Result: <textarea name=textn onClick="output()"> testing text area onClick is invoked when a mouse </textarea> click is done inside the text area
testing text area

onClick

onBlur

onBlur Executes some code when the text area loses focus using tab onFocus Executes some code when the text area gets the focus

Result: <textarea name=textn onBlur="output()"> testing text area </textarea>


testing text area

onFocus

Result: <textarea name=textn onFocus="output()"> testing text area

63

using tab.

</textarea>
testing text area

Result: DOM Properties: The following are the list of DOM (Dynamic Object Model) properties that can be used to get and alter TextArea properties in javascript. The below examples are based on the form <form name=form1> <textarea name=textn> testing text area </textarea> </form> DOM Property Description Example To Get: var ss = document.form1.textn.defaultValue; To Get: var ss = document.form1.textn.form; To Get: var ss = document.form1.textn.name; To Get: var ss = document.form1.textn.type; To Get: var ss = document.form1.textn.value; To Set:: document.form1.textn.value = "testy"; To Get: var ss = document.form1.textn.size; To Set:: document.form1.textn.size = 4; To Check: var ss = document.form1.textn.readOnly; To Set:: document.form1.textn.readOnly = true;

Used to get and set the defaultValue default value of the text area Used to get the parent node (form object) of form this Text area Node name Used to get TextArea name Used to get form type

type

value

Used to set or get Text Area value

size

Used to set or get Text Area size Used to check or change readonly property. Users cannot enter any value if the text area is set as readonly.

readOnly

DOM Methods: The following are the list of DOM (Dynamic Object Model) methods that can be used to do dynamic changes like dynamic text area selection using javascript.

64

DOM Method select() blur() focus()

Description Used to dynamically select a text area Used to dynamically make the Text Area blur Used to dynamically get focus on the Text Area

Example To Select: document.form1.textn.select(); To Blur: document.form1.textn.blur(); To Focus: document.form1.textn.focus();

Example: Making Text Area Focus on a button Mouse Over <script language=javascript> function rbevent() { var xx = document.xx.testarea.focus(); } </script> <form name=xx> <textarea name=testarea> Testing text area </textarea> <input type=button name=rbtest onMouseOver="rbevent()"> </form> Result:
Testing text area

Select option Object :


The following syntax will get the Select object in javascript Syntax: document.formname.selectname Example Code: <form name=testform> <select name=sel> <option value=test> test select option </option> </select> </form> <script language="javascript"> var cbobject= document.testform.rb1; </script> Here are the events, dom properties and method associated with Select Box element. Event Handlers: Associated with Form type SelectBox:

65

All the examples below use a javascript function output <script language=javascript> function output() { alert("testing Select Option events"); } </script> Event Handler Description onMouseOver onMouseOver is invoked when a mouse is moved over the Select Box Example Result:

onMouseDown

onMouseDown is invoked when a mouse is pressed Result: down on the Select Option

onMouseUp

onMouseUp is invoked when a mouse is pressed down on the select option and released

Result:

onChange

onChange is invoked when a new option is selected Result:


test2

onBlur

onBlur Executes some code when the SelectBox loses focus using tab onFocus Executes some code when the SelectBox gets the focus using tab

Result:
test

onFocus

Result:

DOM Properties: The following are the list of DOM (Dynamic Object Model) properties that can be used to get and alter Select properties in javascript. The below examples are based on the form <form name=tests> <select name=sel> <option value=test> test select option </option> <option value=test2> test2</option> </select> </form>

66

DOM Property length

Description

Example

name

Used to get the length (total To Get: number of options) in the select var len = document.tests.sel.length; object To Get: Used to get Select Box name var ss = document.tests.sel.name; Returns the array of options listed in the select object To Get: var ss = document.tests.sel.options; To Get: var ss = document.tests.sel.selectedIndex; Returns 1 if the second option is the selected one. To Set: document.tests.sel.selectedIndex = 0; To Get: var dd = document.tests.sel.selectedIndex; var ss = document.tests.sel[dd].text;

options

selectedIndex is used to get or selectedIndex set the position of the option selected

text

Returns the text value present in the select box

DOM Methods: The following are the list of DOM (Dynamic Object Model) methods that can be used to do dynamic changes in select option using javascript. DOM Method blur() focus() Description Used to dynamically make the Radio Button blur Used to dynamically get focus on the Radio Button Example To Blur: document.testb.mycb.blur(); To Focus: document.testb.mycb.focus();

Example: Making the second option as selected when ever you move the mouse over it. <script language=javascript> function sevent() { var xx = document.xx.sbox; document.xx.sbox.selectedIndex = 1; } </script> <form name=xx> <select name=sbox onMouseOver="sevent()"> <option value="option 1">option 1</option>

67

<option value="option 2">option 2</option> </select> </form> Result:

Form Object :
Form object is created for every html form element. We can dynamically submit, reset, handle other object like button, checkbox etc.. in the form using form object in javascript. Methods or Functions: The following are the list of DOM (Dynamic Object Model) function or methods that can be used to do dynamic changes in a form using javascript. All the below examples use the following form element <form name=tform action="index.php" method=post> <input type=button value=xxx> </form> DOM Method Description Example Used to dynamically To Submit: submit a form using submit() document.tform.submit(); javascript Used to dynamically To Reset: reset the values of the reset() document.tform.reset(); form Used to invoke event handleEvent() handlers

The form object has the following properties. All the below examples use the following form element <form name=tform action="index.php" method=post> <input type=button value=xxx> </form> DOM Description Property action Used to get or set the action attribute of form field. property "elements" returns an array Example To Get: var ss = document.tform.action; To Set: document.tform.action = "form-object.php"; To Get: var ss = document.tform.elements;

elements

68

containing all the objects (like button, checkbox, etc..) in a form Used to get or set the encoding enctype attribute of form field. Property "length" is used to check the number of elements present in the form. Property "method" is used get or set the attribute "method" of form field as POST or GET. Property "name" is used to get or set the name of the form. Property "target" is used get or set the attribute "target" of the form. To Get: var ss = document.tform.encoding; To Set: document.tform.encoding = ""; To Get: var ss = document.tform.length; To Get: var ss = document.tform.method; To Set: document.tform.method= "GET"; To Get: var ss = document.tform.name; To Get: var ss = document.tform.target; To Set: document.tform.target = "xxxx";

length

method

name

target

HTML DOM Style Object Properties:


The Style object of the DOM allows you to change the values of your CSS properties at runtime. The change makes an immediate effect on your webpages. It is possible to modify the properties set by both the inline and external style sheets. Syntax :

document.getElementById("id").style.property="value";
The Style object properties are categorized as follows: Background Layout Misc Printing Text Border and Margin List Positioning Table Standard

69

HTML DOM Style Object Background Properties:


The backgroud property is used to change the background of an element at runtime. The background properties of the style object were listed in the table given below: syntax: object.style.property=value; Background Property Description background backgroundAttachment specifies the background properties. values color,image,repeat attachment,position

specifies whether a background-image scroll/fixed is fixed or scrolls with the page name,rgb,hex backgroundColor specifies the background-color transparent url, backgroundImage specifies the background-image none top left, top center, top right center left, center center, specifies the starting position of a backgroundPosition center right background-image bottom left, bottom center, bottom right specifies the x-coordinates of the left, center, right backgroundPositionX backgroundPosition property x%,xpos specifies the y-coordinates of the left, center, right backgroundPositionY backgroundPosition property y%,ypos specifies if/how a background-image repeat,norepeat,repeatbackgroundRepeat will be repeated x,repeat-y Set the various values listed in the above table to the corresponding properties. Example <script type="text/Javascript"> function sstyle() { document.getElementById('test').style.backgroundColor = "#e0ffff"; } </script> <input type=button id ='test' value='click here' onclick='sstyle()'> Result:

HTML DOM Style Object Table Border Property:


The table object border property is used to set the various values to the border element at runtime.The border properties of the style object were listed in the table given below:

70

syntax: object.style.property=value

Table Property border

Description specifies all properties for the four borders in one

borderBottom

specifies all properties for the bottom border

borderBottomColor specifies the color of the bottom border

borderBottomStyle specifies the style of the bottom border

borderBottomWidth specifies the width of the bottom border

borderColor

specifies the color of all four borders (can have up to four colors) specifies all properties for the left border in one

borderLeft

borderLeftColor

Specifies the color of the left border

borderLeftStyle

specifies the style of the left border

borderLeftWidth

specifies the width of the left border

borderRight

specifies all properties for the right border in one

borderRightColor

specifies the color of the right border

values border Widthborder StyleborderColor borderWidth borderStyle borderColor name rgb hex hidden dotted dashed solid double groove thin medium thick length name rgb hex borderWidth borderStyle borderColor name rgb hex hidden dotted dashed solid double groove thin medium thick length borderWidth borderStyle borderColor name rgb hex

71

borderRightStyle

specifies the style of the right border

borderRightWidth specifies the width of the right border

borderStyle

specifies the style of all four borders (can have up to four styles)

borderTop

specifies all properties for the top border in one

borderTopColor

specifies the color of the top border

borderTopStyle

specifies the style of the top border

borderTopWidth

specifies the width of the top border

borderWidth

specifies the width of all four borders (can have up to four widths) specifies the margins of an element (can have up to four values) specifies the bottom margin of an element

hidden dotted dashed solid double groove thin medium thick length hidden dotted dashed solid double groove borderWidth borderStyle borderColor name rgb hex hidden dotted dashed solid double groove thin medium thick length thin medium thick length margin auto length % auto length % auto length % auto length

margin marginBottom

marginLeft

specifies the left margin of an element

marginRight marginTop

specifies the right margin of an element specifies the top margin of an element

72

outline

specifies all outline properties in one

outlineColor

specifies the color of the outline around a element

outlineStyle

specifies the style of the outline around an element

outlineWidth

specifies the width of the outline around an element specifies the padding of an element (can have up to four values) specifies the bottom padding of an element specifies the left padding of an element specifies the right padding of an element specifies the top padding of an element

% width style color name rgb hex hidden dotted dashed solid double groove thin medium thick length padding length % length % length % length %

padding paddingBottom paddingLeft paddingRight paddingTop

Set the various values listed in the above table to the corresponding table object border property. Example <html> <head> <style type="text/css"> p { border: thin solid #00FF00; outline: thick solid #ffdab9; } </style> <script type="text/javascript"> function changeColor() { document.getElementById("p").style.outlineColor="#6495ed"; } </script> </head>

73

<body> <input type="button" onclick="changeColor()" value="Change outline color" /> <p id="p">www.hscripts.com</p> </body> </html> Result: www.hscripts.com

HTML DOM Style Object - Table Layout Property:


The layout property is used to set, change the layout of the elements at runtime. The layout properties of the style object were listed in the table given below: syntax: object.style.property=value; Layout Property Description clear specifies on which sides of an element other floating elements are not allowed specifies the shape of an element values left right both none rect(top,right,bottom,left) auto

clip content

specifies meta-information Specifies a list of counter names, followed by an integer. The integer indicates by how much the counterIncrement counter is incremented for every occurrence of the element. The default is 1 specifies a list of counter names, followed by an integer. The integer gives the value that the counterReset counter is set to on each occurrence of the element. The default is 0 cssFloat specifies where an image or a text will appear (float) in another element left right none auto pointer text wait ltr rtl inherit inline compact marker table inline-table

cursor

specifies the type of cursor to be displayed

direction

specifies the text direction of an element

display

specifies how an element will be displayed

74

height markerOffset marks maxHeight maxWidth minHeight minWidth

specifies the height of an element specifies the distance between the nearest border edges of a marker box and its principal box specifies whether cross marks or crop marks should be rendered just outside the page box edge

auto length %

overflow

verticalAlign

visibility

width

length % length specifies the maximum width of an element % length specifies the minimum height of an element % length specifies the minimum width of an element % visible Specifies what to do with content that does not fit hidden in an element box scroll auto sub super specifies the vertical alignment of content in an top element middle bottom visible specifies whether or not an element should be hidden visible collapse auto specifies the width of an element length % specifies the maximum height of an element

Set the various values listed in the above table to the corresponding layout property. Example <html> <head> <script type="text/javascript"> function setFloat() { document.getElementById("img1").style.cssFloat="left"; } </script> </head> <body> <img id="img1" src="hscripts2.gif" width="95" height="84" /> <p>www.hscripts.com</p> <input type="button" onclick="setFloat()" value="Set image to float to the left" />

75

</body> </html> Result:

HTML DOM Style Object listStyle Property:


The liststyle property is used to change the values to the list items at runtime. The list properties of the style object were listed in the table given below: syntax: object.style.property=value; ListStyle Property listStyle listStyleImage listStylePosition Description Sets all properties for the list in one Sets an image as the list-item marker Positions the list-item marker values listStyleType listStylePosition listStyleImage url none inside outside disc circle square decimal decimal-leading-zero lower-alpha upper-alpha

listStyleType

Sets the list-item marker type

Set the various values listed in the above table to the corresponding liststyle property. Example <html> <head> <script type="text/javascript"> function changeList() { document.getElementById("ul").style.listStyleType="upper-alpha"; } </script> </head> <body> <ul id="ul"> <li>pen</li> <li>sketch</li>

76

<li>scale</li> <li>eraser</li> </ul> <input type="button" onclick="changeList()" value="Change list-item to uppercase" /> </body> </html> Result:

pen sketch scale eraser

HTML DOM style Object Misc property:


The misc property is used to change the additional values to an element at runtime. The misc properties of the style object were listed in the table given below: syntax: object.style.property=value; Property Description Sets or returns a Boolean value indicating whether the element contains an accelerator accelerator key behavior Returns the content of a css rule in its entirety, from the selector to the cssText corresponding CSS declaration(s). imeMode Sets or retrieves the state of an Input Method Editor (IME).

HTML DOM Style Object Position Property:


The position property is used to set the position of the css elements at runtime. The position properties of the style object were listed in the table given below: syntax: object.style.property=value Description values

Alignment Property bottom

left

position

auto specifies how far the bottom edge of an element is above/below the % bottom edge of the parent element length auto specifies how far the left edge of an element is to the right/left of the % left edge of the parent element. length static relative places an element in a static, relative, absolute or fixed position absolute fixed

77

right

top

auto % length auto specifies how far the top edge of an element is above/below the top % edge of the parent element length specifies how far the right edge of an element is to the left/right of the right edge of the parent element

Set the various alignment values listed in the above table to the corresponding properties. Example <html> <head> <style type="text/css"> input { position:absolute; } </style> <script type="text/javascript"> function setEdge() { document.getElementById("p").style.left="500px"; } </script> </head> <body> <input type="button" id="p" onclick="setEdge()" value="Set left edge to 500 px" /> </body> </html>

HTML DOM Style Object Printing Properties:


The printing property is used to change the properties of a print document at runtime.The misc properties of the style object were listed in the table given below: syntax: object.style.property=value; values

Printing Property Description specifies the minimum number of lines for a orphans paragraph that must be left at the bottom of a page specifies the minimum number of lines for a widows paragraph that must be left at the top of a page specifies the page type to be used when page displaying an element pageBreakAfter Specifies the page-breaking behavior after an element

auto,always avoid,left right

78

pageBreakBefore pageBreakInside

specifies the page-breaking behavior before an element specifies the page-breaking behavior inside an element Sets the orientation and size of a page

auto,always avoid,left right auto avoid

size

Set the various printing values listed in the above table to the corresponding properties. Example <html> <head> <script type="text/javascript"> function PageBreak() { document.getElementById("p").style.pageBreakAfter="right"; } </script> </head> <body> <p id="p">www.hscripts.com.</p> <input type="button" onclick="PageBreak()" value="page-break" /> <p>www.hscripts.com</p> </body> </html> </html>

HTML DOM Style Object Table Properties:


The table property is used to set the various values to the table at runtime.The table properties of the style object were listed in the table given below: syntax: object.style.property=value Table Property Description specifies whether the table border should be collapsed into a single borderCollapse border or detached as in standard HTML borderSpacing specifies the distance between cell borders captionSide values separate collapse length top bottom specifies the position of the table caption left right hide specifies whether to show empty cells in a table or not show automatic specifies the rules used to display the table cells, rows, and columns fixed

emptyCells tableLayout

79

Set the various values listed in the above table to the corresponding table property. Example <html> <head> <script type="text/javascript"> function BorderCollapse() { document.getElementById('Table').style.borderCollapse="collapse"; } </script> </head> <body> <table border="1" id="Table"> <tr> <td>red</td> <td>green</td> </tr> <tr> <td>pink</td> <td>violet</td> </tr> </table> <br /> <input type="button" onclick="BorderCollapse()" value="Collapse"> </body> </html> Result: red green pink violet

HTML DOM Style Object Text Properties:


The text property is used to set the various values to the text at runtime.The text properties of the style object were listed in the table given below: syntax: object.style.property=value; Text Property color Description specifies the color of the text values name/rgb/hex Style/Variant/Weight /Size/Family caption icon menu

font

specifies all font properties in one

80

fontFamily fontSize fontSizeAdjust

specifies the font of an element specifies the font-size of an element adjusts the size of a text

fontStretch

specifies how to condense or stretch a font

fontStyle fontVariant

specifies the font-style of an element Displays text in a small-caps font

fontWeight

specifies the boldness of the font

letterSpacing

specifies the space between characters

lineHeight

specifies the distance between lines

textAlign

Aligns the text

textDecoration textIndent

Sets the decoration of a text Indents the first line of text

message-box small-caption status-bar font1, font2,.... small medium large number ultra-condensed condensed ultra-expanded wider narrower normal italic oblique normal small-caps normal lighter bold bolder normal length normal number length % left right center justify underline overline blink length %

Set the various values listed in the above table to the corresponding property. Example <html> <head> <script type="text/javascript"> function changeStyle() { document.getElementById("p").style.fontStyle="italic"; }

81

</script> </head> <body> <p id="p"><b>kiruba</b></p> <input type="button" onclick="changeStyle()" value="Change font-style" /> </body> </html> Result: kiruba

HTML DOM Style Object Standard Properties:


The standard property is used to set the various values which are applicable globally to a html coding.The standard properties of the style object were listed in the table given below: syntax: object.style.property=value; Standard Property dir lang title Example: <html> <body dir="ltr" lang="en-us" title="kiruba"> <script type="text/javascript"> x=document.getElementsByTagName('body')[0]; document.write("Body title: " + x.title); document.write("<br />"); document.write(" language: " + x.lang); document.write("<br />"); document.write(" direction: " + x.dir); </script> </body> </html> Result Body title: kiruba language: en-us direction: ltr
--------------------------------------------------------THE ENDLESS--------------------------------------Presented by,

Description specifies the direction of text specifies the language code for an element specifies an element's title

N.Kirubanandhan MCA

You might also like