Java ScriptJavaScript is a powerful, object-based scripting language;JavaScript programs can be embedded directly in HTML web pages.When combined with the Document Object Model (DOM) defined by a web browser, JavaScript allows you to create Dynamic HTMLcontent and interactive client-side web applications. JavaScriptsyntax is based on the popular programming languages C, C++, andJava, which makes it familiar and easy to learn for experiencedprogrammers. At the same time, JavaScript is an interpreted scripting language, providing a flexible programming environment in which new programmers can learn easily.
What is JavaScript? Html is providing static web pages but with the developments in internet & World Wide Web the interactive communication became a necessity. The World Wide Webis a heap of pages having information if form of text, graphics, pictures, sounds etc. Every page is linked to another page on web and the linked page can have links to other pages. Browser is a program responsible to understand and interpret the language and perform according to the instructions written in HTML file. Internet Explorer,Netscape Navigator, Fire Fox etc. are such programs. HTML, JavaScript is integrated with browser & this integration enables the programmer to add dynamic interaction to the text, picture, information on the web page. JavaScript is case sensitive language i.e.; state is different from State or STATE (these are three different words for JavaScript). JavaScript is capable of sensing the events like mousing clicking, mousing moving etc. JavaScript files are directly executed when user double clicks on them or opens them in Browser.
JavaScript is Java or what? No, JavaScript is not java.Java is a complex and much more powerful language like C & C++. WhileHTML, JavaScript are integrated with browser & this integration enables the programmer to add dynamic interaction to the text, picture, information on the web page. JavaScript is case sensitive language i.e.; state is different from State orSTATE (these are three different words for JavaScript). JavaScript is capable of sensing the events like mousing clicking, mousing moving etc. JavaScript files are directly executed when user double clicks on them or opens them in Browser. HTML coders are not programmer but using JavaScript an html operator can do programming in a very simple way because JavaScript is very simple and easy to learn and understand. JavaScript is capable of making a static page as dynamic page, where the programmer can put variables. JavaScript has the ability to sense theevents like mouse click, movement, keyboarding events etc. We can use HTML inJavaScript i.e. JavaScript can understand HTML. The JavaScript program hence decreasing the unnecessary traffic on lines and useless processing at server end can validate the data fed by the user at client end.
| What we can do using JavaScript? | ||
| HTML coders are not programmer but using JavaScript a html operator can do programming in a very simple way because JavaScript is very simple and easy to learn and understand. JavaScript is capable of making a static page as dynamic page, where the programmer can put variables. JavaScript has the ability to sense the events like mousing click, movement, keyboarding events etc. We can use HTML in JavaScript i.e. JavaScript can understand HTML. The JavaScript program hence decreasing the unnecessary traffic on lines and useless processing at server end can validate the data fed by the user at client end. | ||
|
|
||
| What we should know before learning JavaScript ? | ||
| We should have knowledge of HTML before learning JavaScript. A JavaScript program can be typed in head or in body part of the HTML page or it could beattached externally to the web page. | ||
|
|
What minimum Hardware and Software requirements are to run JavaScript? Hardware Requirements
| Processor: | 486 dx4 or above |
| RAM: | 16 MB |
| VDU: | VGA or SVGA |
| HDD: | 1.2 GB or above |
Software Requirements
| Operating System: | Windows or Linux with browser |
| Text Editor: | Any text editor likes notepad or editplus etc. |
Is semi colon needed to end the statement in JavaScript?
Putting semi color at the end of the statement is optional, if you want you can place else you can leave. Putting semi color at end of the statement depends on the user’s choice.
HTML coders are not programmer but using JavaScript an html operator can do programming in a very simple way because JavaScript is very simple and easy to learn and understand. JavaScript is capable of making a static page as dynamic page, where the programmer can put variables. JavaScript has the ability to sense the events like mouse click, movement, keyboarding events etc. We can use HTML inJavaScript i.e. JavaScript can understand HTML. The JavaScript program hencedecreasing the unnecessary traffic on lines and useless processing at server end can validate the data fed by the user at client end. HTML, JavaScript are integrated with browser & this integration enables the programmer to add dynamic interaction to the text, picture, information on theweb page. JavaScript is case sensitive language i.e.; state is different from State orSTATE (these are three different words for JavaScript). JavaScript is capable of sensing the events like mousing clicking, mousing moving etc. JavaScript filesare directly executed when user double clicks on them or opens them in Browser.
| Number | |
| The number type deals with digits, It covers both floating point numbers and integers. | |
| Floating point numbers are like – 412.562, 9.2, 0.468 | |
| Integer numbers are like : 25, 1258, 968 | |
| Initializing number type variables | |
| Var age = 25 | |
| Var is javascript keyword, age is a variable name, 25 is value assigned to age variable, variable age is of number type because the value assigned to age is ofnumber type. | |
| Var hra = 1585.56 | |
| Var is javascript keyword, hra is a variable name, 1585.56 is value assigned to hra variable, variable hra is of number type because the value assigned to hra is of number type. | |
| In the example given below we have used keyword document.write (messge ) which is used to print the message or variable value given with it. | |
| Example | |
| <html>
<head></head> <body> <script type=”text/javascript”> var age=25 document.write(“Age is : “+age); </script > </body> </html> |
|
| Understanding the program | |
| <script > tag is the start of a javascript program, var is to declare a variable of name age and 25 is the value assigned to the variable age. document.write is used to print the given message and/or value of a given variable. We have used + sign here which is used to concatenate the message ( Age is : ) and the value of variable a (25). | |
| Output of this program | |
| Age is : 25 | |
| Click here to view this program in browser | |
| Example | |
| <html>
<head> </head> <body> <script type=”text/javascript”> var hra=1585.25 document.write(“HRA is : “+hra); </script > </body> </html> |
|
| Understanding the program | |
| <script > tag is the start of a javascript program, var is to declare a variable of name hra and 1585.25 is the value assigned to the variable hra. document.write is used to print the given message and/or value of a given variable. We have used + sign here which is used to concatenate the message ( HRA is : ) and the value of variable a (1585.25). | |
| Output of this program | |
| HRA is : 25 | |
| Click here to view this program in browser | |
|
|
|
| Boolean | |
| Boolean type has only two values true and false. These constant values are case-sensitive. | |
| Initializing Boolean type variables | |
| var present = true | |
| var is JavaScript keyword, present is a variable name, true is value assigned to present variable, variable present is of Boolean type because the value assigned to present is of boolean type. | |
| In the example given below we have used keyword document.write (message ) which is used to print the message or variable value given with it. | |
| Example 1 | |
| <html>
<head> </head> <body> <script type=”text/javascript”> var present = true var attend = false document.write(“Student Status in School : “+present); document.write(“<br>Class Attended : “+attend); </script > </body> </html> |
|
| Understanding the program | |
| present & absent are two variables of Boolean type having values true and falseres |
String String type deals with a single character or a series of characters enclosed with single quotes or double quotes respectively. Initializing string type variables var sect = ‘a’var is JavaScript keyword, sect is a variable name, a is value assigned to sect variable, variable sect is of string type because the value assigned to sect is of string type. var country=”India”var is JavaScript keyword, country is a variable name, India is value assigned to country variable, variable country is of string type because the value assigned to country is of string type. In the example given below we have used keyword document.write (message ) which is used to print the message or variable value given with it. Example 1
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
var sect=’a’
document.write(“Section is : “+sect);
</script >
</body>
</html>
Understanding the program <script > tag is the start of a JavaScript program, var is to declare a variable of name sect and ‘a’ is the value assigned to the variable sect. document.write is used to print the given message and/or value of a given variable. We have used + sign here which is used to concatenate the message ( Section is : ) and the value of variable sect (a). Output of this program sectoion is : aClick here to run this program in browser Example 2:
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
var country=’India’
document.write(“Country is : “+country);
</script >
</body>
</html>
Understanding the program <script > tag is the start of a JavaScript program, var is to declare a variable of name country and “India” is the value assigned to the variable country.document.write is used to print the given message and/or value of a given variable. We have used + sign here which is used to concatenate the message ( Country is :) and the value of variable country (India). Output of this program Country is : IndiaClick here to run this program in browser
null & undefined Null type has only one value, null. The null value means ‘no data’ or this variable do not have any useful data. Undefined type has one value, undefined, undefined means nothing is stored in this variable. Undefined is not even null. Initializing null type variable var food = null
var is JavaScript keyword, food is a variable name, null is value assigned to food variable.
In the example given below we have used keyword document.write (message ) which is used to print the message or variable value given with it. Example 1
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
var food=null
document.write(“food is : “+food);
</script >
</body>
</html>
Understanding the program food is a variable of null type having no type of values or data. output of this programfood is : nullclick here to view result of this program in browser Knowing undefined type variablevar food ;var is JavaScript keyword, food is a variable name, no value is assigned to variable food. In the example given below we have used keyword document.write (message ) which is used to print the message or variable value given with it. Example 2
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var food;
document.write(“food is : “+food);
</script >
</body>
</html> Understanding the program food is a variable of undefined type , because nothing is defined to it . Output of this programfood is : undefinedclick here to view result of this program in browser
nfinity and NAN infinity is a property of a number. It represents mathematical infinity. Example Var infi= 1e400*1e350;Var is javascript keyword, infi is a variable name, 1e400 * 1e350 value assigned toinfi variable. In the example given below we have used keyword document.write (message ) which is used to print the message or variable value given with it. Example 1
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var infi = 1e300 * 1e300;
document.write(“Value stored in infi is : “+infi);
</script >
</body>
</html>
Output of this program Value stored in infi is : InfinityClick here to view result of this program in browser Nan Stands for not a number and is a result of a mathematical operation which do not have any sense. This happens generally when we divide a 0 by 0. Example var k = 0/0 ;var is JavaScript keyword, k is a variable name, 0/0 value is assigned to variablek. In the example given below we have used keyword document.write (message ) which is used to print the message or variable value given with it. Example 2
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
var k = 0/0;
document.write(“Value stored in k is : “+k);
</script >
</body>
</html> Output of this programValue stored in k is : NaNClick here to view result of this program in browser
Arrays If we require many variables of same or different types then a problem ofremembering names of variables and many functional problems will arise.Concept of array allows us to store different data type data pieces under the same name in an ordered way. It helps in creating many variables. There is no need of remembering their names because they all have the same name but different positions in the array. The count of location in an array starts from 0 not from 1, means thefirst location is 0th location and 12th is 11th . Declaring an array variable Method 1var d = new Array (“One”, “Two”, “Three”, “Four”); Understanding the declaration var – is reserve word d – is the name of the array new – is a reserve word , sets that much number of locations in memory as much parameters given with Array( ); Array( ) – is a reserve word , provides the input to new that how much memory locations are to be reserved. “One”, “Two”, “Three”,” Four” – are the values to set in d named array variable as much the count of these variables is that much of locations in memory will be reservedby new (reserve word). Method 2var sales = new Array (12); Understanding the declaration var – is reserve word sales – is the name of the array new – is a reserve word , sets that much number of locations in memory as much parameters given with Array( ), in this case 12 locations will be occupied; Array( ) – is a reserve word , provides the input to new that how much memory locations are to be reserved. 12 – is the count of locations to be reserved. Assigning values to an array locations Sales[0] = “Rubber”; Sales [1] = 12000; Sales[2] = “Plastic”; Sales [3] = 18000; At 0th position of sales named array the value is “Rubber “ and at 1st position12000 is stored. So we can place different data types data in the same array. Example 1 <html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
var d = new Array(“One”,”Two”,”Three”,”Four”);
document.write(“Value at 0th position of d is “+d[0]);
document.write(“<br>Value at 1st position of d is “+d[1]);
document.write(“<br>Value at 2nd position of d is “+d[2]);
document.write(“<br>Value at 3rd position of d is “+d[3]);
</script >
</body>
</html> Output isValue at 0th position of d is One
Value at 1st position of d is Two
Value at 2nd position of d is Three
Value at 3rd position of d is Four Example 2 <html>
<head>
</head>
<body>
<script type=”text/javascript”>
var sales = new Array(12);
sales[0]=”Rubber”;
sales[1]=12000;
sales[2]=”Plastic”
sales[3]=18000;
document.write(“Value at 0th position of sales is “+sales[0]);
document.write(“<br>Value at 1st position of sales is “+sales[1]);
</script >
</body>
</html> Output isValue at 0th position of sales is Rubber
Value at 1st position of sales is 12000Click here to see the animated presentation of Data Type & Variable (With Voice).
Alert Box Alert box is a dialog box which displays a message in a small window with an OKbutton, user have to click on the ok button to proceed.
Example
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
alert(“Hit me to proceed”)
document.write(” Have a nice day “);
</script >
</body>
</html>
Understanding the program:User can type his desired message with the alert box in the quotes likealert(“what ever text user want “). This message will be displayed with the alert window to guide the user. Output is:Have a nice dayClick here to view result of this program on browser
Prompt Box Prompt box is a dialog box which displays a message in a small window with a text box along with two buttons . One OK and other Cancel. Prompt method has ability to return the text kept with the prompt method’s text box , this value can be assigned to some variable and can be used as and when require. Example
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
prompt (“Enter your name”, “”)
</script >
</body>
</html>
Understanding the program:A dialog box with a text box and two buttons will appear, the message typed withprompt method will be displayed on the dialog box the text box will appear blank , if any text is typed at the place of blank (“ ”), that text will appear in the text box ondialog box.Click here to view result of this program on browser Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
prompt (“Enter your name”, ” enter your name here”)
</script >
</body>
</html>
Understanding the program :A dialog box with a text box and two buttons will appear, the message typed withprompt method will be displayed on the dialog box the text box will appear filled with“ enter your name here “ text.Click here to view result of this program on browser Storing value accepted from a prompt box in variables :
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var name,address name=prompt (“Enter your name”, ” enter your name here”)
address = prompt (“Enter your address”, “Address Please “)
document.write(“Your Name : “+name);
document.write(“<br>Your Address : “+address);
</script >
</body>
</html>
Understanding program :As we know that prompt method has the ability to return the text stored in it’s text box, so the name fed by the user will be stored in the name variable and address of user in address variable, which will be displayed on the screen by document.write method. Output is :Your Name : RhythmYour Address : A -45, Preet Vihar, Delhi – 110092Click here to view result of this program on browser
Confirm Box Confirm box is a dialog box which displays a message in a small window with two buttons. One Ok and other Cancel. This method can be used to get the response of user in positive by clicking on ok and in negative by clicking on cancel. The value returned by the confirm method in case of OK is true and in case of Cancel is false. A programmer can program the code for positive and negative situations depending on the response returned by the user.
Example
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
a=confirm(” Want to Proceed ? “);
document.write(“Your have clicked on : “+a);
</script >
</body>
</html>
Understanding the program:If user will clicks on Ok then you have clicked on true will appear
If user will clicks on Cancel then you have clicked on false will appearClick here to view result of this program on browserClick here to see the animated presentation of Using Popup Boxes.(With Voice)
Confirm Box Confirm box is a dialog box which displays a message in a small window with two buttons. One Ok and other Cancel. This method can be used to get the response of user in positive by clicking on ok and in negative by clicking on cancel. The value returned by the confirm method in case of OK is true and in case of Cancel is false. A programmer can program the code for positive and negative situations depending on the response returned by the user.
Example
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
a=confirm(” Want to Proceed ? “);
document.write(“Your have clicked on : “+a);
</script >
</body>
</html>
Understanding the program:If user will clicks on Ok then you have clicked on true will appear
If user will clicks on Cancel then you have clicked on false will appearClick here to view result of this program on browserClick here to see the animated presentation of Using Popup Boxes.(With Voice)
ogical Operators
Logical operators are used to perform Boolean operations on operands. Logical operators are and (&&), or ( || ) , not (!) . The value returned after using a logical operator is Boolean value true or false. Logical operators are connectors of expressions also.
| Operator | Description |
| && | Both the expression should be correct then it returns trueelse it returns false. It is known as “and” operator |
| || | If Any of the given expressions is found true then it returnstrue else it returns false. |
| ! | If the given expression is true it returns false and if given expression is false it returns true. |
Example
<html>
<head>
</head>
<body>
<script>
var a=9
var b=8
var c=25
document.write(“<br> a is : “+a)
document.write(“<br> a is : “+b)
document.write(“<br> a is : “+c)
document.write(“<br>is a greater than b and greater c also ? : “+(a>b && a>c)) document.write(“<br>is a greater than b or greater c ? : “+(a>b || a>c)) document.write(“<br>not c is greater than a ? : “+!(c>a))
</script>
</body>
</html>
Output: a is : 9
a is : 8
a is : 25
is a greater than b and greater c also ? : false
is a greater than b or greater c ? : true
not c is greater than a ? : falseclick here to view results on browser
Assignment Operators
As the name suggest these operators are used to assign values to variables. Theright hand value or variable is assigned to the left hand variable. Different assignment operators are listed below with these use.
| Operator | Description | Example |
| = | This operator is used to assign value of variable/value only at right hand of it to the variable at left hand of this operator. | a=5 b=6 c=a+b |
| += | Increments the left hand variable with the right hand variable | a+=b or a=a+b |
| -= | Decrements the left hand variable with the right hand variable | a-=b or a=a-b |
| *= | Multiplies the left hand variable with the right hand variable | a*=b or a=a*b |
| /= | Divides the left hand variable with the right hand variable | a/=b or a=a/b |
| %= | Keeps the remainder of division of left hand variable by right hand variable in the left hand variable | a%=b or a=a%b |
Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var a,b
a=5
b = 6
document.write(“<br>Value of a : “+a);
document.write(“<br>Value of b : “+b);
a+=b;
document.write(“<br>Value of a after a+=b : “+a);
a-=b
document.write(“<br>Value of a after a-=b : “+a);
a*=b
document.write(“<br>Value of a after a*=b : “+a);
a/=b
document.write(“<br>Value of a after a/=b : “+a);
a%=b
document.write(“<br>Value of a after a%=b : “+a);
</script>
</body>
</html>
Output: Value of a : 5
Value of b : 6
Value of a after a+=b : 11
Value of a after a-=b : 5
Value of a after a*=b : 30
Value of a after a/=b : 5
Value of a after a%=b : 5Click here to view result of this program on browser
Operators Comparison Operators
As the name suggest these operators are used to compare two variable values. The left hand variable is compared with the right hand operator using these operators. The answer returned after use of these expressions is a Boolean value which tell that whether comparisons is true or false. A programmer can program for either situation.Different comparison operators are listed below.
| Operator | Description | Example |
| == | This operator is used to compare value or variable at right hand of it to the variable at left hand of this operator. | A==b 5==9 (returns false) |
| === | This three times equal sign is called strictly equal sign it checks for values as well type of datas contained by the variables at left hand and right hand | A=90 B=90 C=”90” A===B will return true because value of A & B is 90 and both are number A===C will return false because value of A & C is 90 but types are different |
| != | This operator is called not equal it checks whether the left and right operands are not equal then it returns true else returns false | A=50 B=90 C=50 A!=B will return true A!=C will return false |
| > | This operator is known as greater than if the left operand is greater than right operand then returns true else return false | A=45 B=15 C=90 a>b will return true a>c will return false |
| < | This operator is known as less than if the left operand is less than right operand then returns true else return false | A=45 B=15 C=90 A<b will return false A<c will return true |
| >= | This operator is known as greater than equal to if the left hand operand is greater than or equal to right hand operand then it returns true else false | A=45 B=95 C=45 A>=b will return false A>=c will return true because both are equal. |
| <= | This operator is known as less than equal to if the left han operand is lesser than or equal to the right hand operand then it returns true else it returns false. | A=45 B=95 C=45 A<=b will return true A<=c will return true because both are equal. |
Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var a,b,c; var d;
a=5
b = 6
c=4
d=”6″
document.write(“<br>Value of a : “+a);
document.write(“<br>Value of b : “+b);
document.write(“<br>Value of c : “+c);
document.write(“<br>Value of d : “+d);
document.write(“<br>Result of a==b : “+(a==b));
document.write(“<br>Result of a===b : “+(a===b));
document.write(“<br>Result of b===d : “+(b===d));
document.write(“<br>Result of a!=b : “+(a!=b))
document.write(“<br>Result of a>=b : ” +(a>=b));
document.write(“<br>Result of a<=b : ” +(a<=b));
document.write(“<br>Result of (a>d) : ” + (a>d));
document.write(“<br>Result of (b<=c) : ” + (b<c));
</script>
</body>
</html>
Output: Value of a : 5
Value of b : 6
Value of c : 4
Value of d : 6
Result of a==b : false
Result of a===b : false
Result of b===d : false
Result of a!=b : true
Result of a>=b : false
Result of a<=b : true
Result of (a>d) : false
Result of (b<=c) : false Understanding the program:In above program, we have used all the operators described and the result is also displayed from which we can understand the functioning of comparison operators.Click here to view result of this program on browser
String Operators
A string operator joins two string values of two string variables and creates a third string value. String operators concatenates two strings. Even the value is numeric in a string variable it is also concatenated.
Like “20” + “30”the answer will be 2030, not 50.
| Operator | Description | Example |
| + | This operator joins the string at left hand side with the string at right hand side | A=”India” B=”Gate” C=A+B – C is holding a value IndiaGate |
Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var a=” India ”
var b = “Gate”
var c= a+b
document.write(“<br>Value of a “+a);
document.write(“<br>Value of b “+b);
document.write(“<br>Value of c “+c);
</script >
</body>
</html>
Output: Value of a India
Value of b Gate
Value of c IndiaGateClick here to view result of this program on browser
Ternary Operators
Ternary operator require one expression, on variable or value for true case and one variable or value for false case. If the condition in given expression is found true it assigns value to variable present in true value position else the value of false value position will be assigned.
variable = condition ? true value : false value Variable to which you want to assign value = condition ? in case of condition is truethis value will be assigned : in case of condition is false this value will be assignedlike:var p=90
var a = p>100 ? 25:50 p is having value 90 we are comparing that whether p is greater than 100 which is false because p is 90 so the value 50 will be assigned to a. If p =150 then value 25will be assigned to a. Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var a=50
var b b= a>=50 ? “Greater then or equal to 50 ” : “Lesser than 50” document.write(“<br>Value of a “+a);
document.write(“<br>Value of b “+b);
</script >
</body>
</html>
Understanding program :value of a is 50 we are checking that if a is greater than or equal to 50 then“Greater than or equal to 50” should be assigned to it else “Lesser than 50”should be assigned to variable b . here value of a is 50 so the condition becomes true and “Greater than or equal to 50” will be placed in variable b. Output: Value of a 50
Value of b Greater then or equal to 50Click here to view result of this program on browser
Type Convertion Conversion to Boolean
Conversion to Boolean means a number or string type variable is changing it’s type to Boolean. In JavaScript a variable can contain any type of data and the data contained by the variable represents the type of that variable. Type conversion inJavaScript is done implicitly . The conversion to Boolean is very easy it could be seen by below given program.
Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var str, num, bool str=”ram”;
num=20 bool=true
document.write(” <br>type of str is : “+typeof(str));
document.write(” <br>Value of str is : “+ (str));
document.write(” <br>type of num is : “+typeof(num));
document.write(” <br>Value of num is : “+ (num));
document.write(“<br> type of bool is : “+typeof(bool));
document.write(” <br>Value of bool is : “+ (bool));
str=bool num = bool
document.write(” <br>type of str is : “+typeof(str));
document.write(” <br>Value of str is : “+ (str));
document.write(” <br>type of num is : “+typeof(num));
document.write(” <br>Value of num is : “+ (num));
document.write(“<br> type of bool is : “+typeof(bool));
document.write(” <br>Value of bool is : “+ (bool));
</script >
</body>
</html>
Understanding program :bool is having value true of Boolean type, str of type string and num of number type, so str and num will get the value of bool and will become of type Boolean. We have used a method typeof() , which is used to know the data type of any variable given with this method. Output: type of str is : string
Value of str is : ram
type of num is : number
Value of num is : 20
type of bool is : boolean
Value of bool is : true
type of str is : boolean
Value of str is : true
type of num is : boolean
Value of num is : true
type of bool is : boolean
Value of bool is : trueClick here to view result of this program on browser
Conversion to Number
Conversion to Number means a Boolean or string type variable is changing it’s type to Number. In JavaScript a variable can contain any type of data and the data contained by the variable represents the type of that variable. Type conversion in JavaScript is done implicitly . The conversion to Number is very easy it could be seen by below given program.
Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var a,b,c;
c= false
b= “23”
a=20
document.write(“<br>Value of c “+c);
document.write(“<br>Value of b “+b);
document.write(“<br>Value of a “+a);
document.write(“<br>Data type of c “+typeof(c));
document.write(“<br>Data type of b “+typeof(b));
document.write(“<br>Data type of a “+typeof(a));
c=a
document.write(“<br>After conversion Data type of c “+typeof(c));
b=a
document.write(“<br>After conversion Data type of b “+typeof(b));
</script>
</body>
</html>
Understanding program :In the above given program a is of number type , b is of string type, c is ofBoolean type but when number variable (a) is assigned to b& c they both becomes of number type. Output: Value of c false
Value of b 23
Value of a 20
Data type of c boolean
Data type of b string
Data type of a number
After conversion Data type of c number
After conversion Data type of b numbeClick here to view result of this program on browser
Conversion to String
Conversion to String means a number or Boolean type variable is changing it’s type to String. In JavaScript a variable can contain any type of data and the data contained by the variable represents the type of that variable. Type conversion inJavaScript is done implicitly . The conversion to String is very easy it could be seen by below given program.
Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var a,b,c;
c= false
b= “23”
a=20
document.write(“<br>Value of c “+c);
document.write(“<br>Value of b “+b);
document.write(“<br>Value of a “+a);
document.write(“<br>Data type of c “+typeof(c));
document.write(“<br>Data type of b “+typeof(b));
document.write(“<br>Data type of a “+typeof(a));
c=b
document.write(“<br>After conversion Data type of c “+typeof(c));
a=b
document.write(“<br>After conversion Data type of a “+typeof(a));
</script>
</body>
</html>
Understanding program :In the above given program a is of number type , b is of string type, c is ofBoolean type but when string variable (b) is assigned to a & c they both becomes of string type. Output: Value of c false
Value of b 23
Value of a 20
Data type of c boolean
Data type of b string
Data type of a number
After conversion Data type of c string
After conversion Data type of a stringClick here to view result of this program on browser ParseInt():-This function is used to convert a number data of string type to number type. If there are two numbers of string type data and we want to perform arithmetic calculation with them then we should use parseInt or parseFloat() functions to convert the type of values to number because the arithmetic calculations can be performed only with number type data.
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var a,b,c;
c= “15”
b= “25”
a=20
document.write(“<br>Value of c “+c+” type of c is “+typeof(c)); document.write(“<br>Value of b “+b+ “type of b is ” + typeof(b)); document.write(“<br>Value of a “+a+”type of a is “+typeof(a));
a = c+b+a
document.write(“<br>without using any conversion function result of a=a+b+c is “+a);
a=20
a = parseInt(c)+parseInt(b)+parseInt(a)
document.write(“<br>After using parseInt function result is “+a);
</script >
</body>
</html>
output is: Value of c 15 type of c is string
Value of b 25type of b is string
Value of a 20type of a is number
without using any conversion function result of a=a+b+c is 152520
After using parseInt function result is 60 ParseFloat() :-This function is used to convert a floating number of string type to number type. Example:
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var a,b,c;
c= “15.25”
b= “25.62”
a=20.45
document.write(“<br>Value of c “+c+” type of c is “+typeof(c)); document.write(“<br>Value of b “+b+ “type of b is ” + typeof(b)); document.write(“<br>Value of a “+a+”type of a is “+typeof(a));
a = c+b+a
document.write(“<br>without using any conversion function result of a=a+b+c is “+a);
a=20.45
a = parseFloat(c)+parseFloat(b)+parseFloat(a)
document.write(“<br>After using parseInt function result is “+a);
</script >
</body>
</html>
Output is:Value of c 15.25 type of c is string
Value of b 25.62type of b is string
Value of a 20.45type of a is number
without using any conversion function result of a=a+b+c is 15.2525.6220.45
After using parseInt function result is 61.32000000000001Click here to view result of this program on browser
If statement
We can use this statement if we want to execute a set of code in case the given condition is true. Let us say if today is Sunday go to market.
syntax (How it is written):
if (condition)
{
job to be done if condition is found true
}
Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var a,b;
a=100
b=50
document.write(“<br>Value of a “+a);
document.write(“<br>Value of b “+b);
if (a>b)
{
document.write(“<br>value of a is greater than b “);
}
</script>
</body>
</html>
Understanding program :Value of a is 100 and value of b is 50. In if statement, we are checking that if a isgreater than b then the message should be printed. Output: Value of a 100
Value of b 50
value of a is greater than bClick here to view result of this program on browser
if – – else statement
We can use this statement if we want to execute a set of code in case the given condition is true and other code in case of given condition is false. For example:
if today is Sunday
go to market
else go to office
syntax (How to write):
if (condition)
{
job to be done if condition is found true
}
else
{
job to be done if condition is found false
}
Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var a,b;
a=parseInt(prompt(“Enter value for a”,””))
b=parseInt(prompt(“Enter value for b”,””))
document.write(“<br>Value of a “+a);
document.write(“<br>Value of b “+b);
if (a>b)
{
document.write(“<br>value of a is greater than b “);
}
else
{
document.write(“<br>value of a lesser than or equal to b “);
}
</script>
</body>
</html>
Understanding program :In the above program we have used prompt method which is used to accept inputfrom user , we learnt this in dialog box section, parseInt function will convert the accepted value to number type because the value returned by the prompt method will be of string type and we can not compare or perform any arithmetic calculation with a string value, so we used parseInt method. Output: Value of a 25
Value of b 45
value of a lesser than or equal to b ExplanationIf the value of a is entered greater than value of b then the above output will be shown else the below output will be shown. Value of a 50
Value of b 20
value of a is greater than bClick here to view result of this program on browser
| f – – else if .. else statement | |||
| We can use this statement if we want to execute a set of code out of many sets of codes. Fox example | |||
| if today is Sunday
go to market else if time is 9 ‘O’ Clock or more go to office else go to yoga class |
|||
| syntax (How to write) : | |||
| if (condition1)
{ job to be done if condition1 is found true } else if (condition2) { job to be done if condition2 is found false } else { job to be done if condition1 and condition both are false or not true } |
|||
| Example | |||
| <html>
<head> </head> <body> <script type=”text/javascript”> var a a=parseInt(prompt(“Enter value for a”,””)) document.write(“<br>Value of a “+a); if (a<5) { document.write(“<br>a is lesser than 5 “); } else if (a>5 && a<10) { document.write(“<br>a is greater than 5 but lesser than 10”); } else { document.write(“<br> a is greater than or equal to 10”); } </script> </body> </html> |
|||
| Understanding program: | |||
| In the above program we have used prompt method which is used to accept inputfrom user , we learnt this in dialog box section, parseInt function will convert the accepted value to number type because the value returned by the prompt method will be of string type and we can not compare or perform any arithmetic calculation with a string value, so we used parseInt method. | |||
| If the value of a is less than 5 then the first set of code will get executed, else thesecond condition will be checked that if the value of a is greater than 5 and lesser than 10 then second set of code will be executed if this check also fails then the third set of code will be executed. | |||
| Output is: | |||
| If the value of a is entered as 10 or more than 10, then the output will be: | |||
| Value of a 10 a is greater than or equal to 10 |
|||
| If the value of a is entered less than 5 then output will be: | |||
| Value of a 4 a is lesser than 5 |
|||
| If the value of a is entered in between 5 – 10 output will be: | |||
| Value of a 9 a is greater than 5 but lesser than 10 |
|||
| Click here to view result of this program on browser | |||
|
|
|||
Switch statement
We can use this statement if we want to execute a block of code for a situation, out of many blocks of codes for different situations. For example
syntax (How to write) :
switch(variablename)
{
case 1 :
code to be executed
break
case 2 :
code to be executed
break
case 3 :
code to be executed
break
default :
code to be executed if non of the above give cases are found
}
Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var day
a=parseInt(prompt(“Enter Weekday please”,””))
switch(a)
{
case 1:
document.write(“<br> It is Sunday “);
document.write(“<br> Enjoy…”);
break
case 2:
document.write(“<br> It is Monday “);
document.write(“<br> go to College “);
break
case 3:
document.write(“<br> It is Tuesday “);
document.write(“<br> go to College “);
break
case 4:
document.write(“<br> It is Wednesday “);
document.write(“<br> go to College “);
break
case 5:
document.write(“<br> It is Thrusday “);
document.write(“<br> go to College “);
break
case 6:
document.write(“<br> It is Friday “);
document.write(“<br> go to College “);
break
case 7:
document.write(“<br> It is Saturday “);
document.write(“<br> go to College “);
break
default :
document.write(“<br> Invalid weekday enter value from 1-7”)
}
</script>
</body>
</html>
Understanding program :In the above program, we have used prompt method which is used to accept input from user , we learnt this in dialog box section, parseInt function will convert the accepted value to number type because the value returned by the prompt method will be of string type and we can not compare or perform any arithmetic calculation with a string value, so we used parseInt method. The output of the above program will depend on the value entered by the user, for different values different block of statements will be executed and break command will make it to jump out of switch scope. Output:I If the weekday entered by user is 4 then output will beIt is Wednesdaygo to College If the weekday entered by user is 1 then output will beIt is Sunday
Enjoy…Click here to view result of this program on browserClick here to see the animation of Condition Checking.(With Voice)
while
This loop continues while the given condition is found true else the loop gets terminated. The variable meets the condition at the gate of while loop if the variable do not fulfill the condition then the loop will not be executed for even a single time.
syntax:
While (condition )
{
code to be executed
}
Example
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
var a=0;
while(a<10)
{
document.write(“\t “+a); a++
}
</script>
</body>
</html>
Understanding program :value of a is initially 0, the condition with loop is while a is less than 10 the statements typed should be executed. a++ means a=a+1, so the a will get incremented with 1 every time. As soon as a becomes 10 the loop gets terminated. Output:0 1 2 3 4 5 6 7 8 9Click here to view result of this program on browser
do – while
This loop continues while the given condition is found true else the loop gets terminated, the difference in this and while looping is even the condition is false but this loop gets executed at least once but while loop gets terminated at initial level if condition is not satisfying.
syntax:
do
{
code to be executed
}
While (condition )
Example
</head>
<body>
<script type=”text/javascript”>
var a=1;
do
{
document.write(” “+a);
a+=2
}
while(a<20)
</script>
</body>
</html>
Understanding program :Value of a is initially 1 , the condition with loop is while a is less than 20 the statements typed should be executed. a+=2 means a=a+2, so the a will getincremented with 2 every time. As soon as a becomes 20 the loop gets terminated. Output:1 3 5 7 9 11 13 15 17 19Click here to view result of this program on browser
for
This loop contains the initial value, termination value , increment/decrementvalue in a single line, which in on other looping are used in separate line, the scope of a for loop is inside the curly brackets used with it. The initialization segment is executed only once at the start of the loop and termination andincrement/decrement segments are executed every time till the condition remains true.
syntax:
for(initialization; termination; increment/decrement)
{
code to be executed
}
Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var a;
for(a=100;a>0;a-=5)
{
document.write(” “+a)
}
</script>
</body>
</html>
Understanding program :Value of a is initially 100 , the condition with for loop is while a is greater 0 the statements typed should be executed. a-=5 means a=a-5, so the a will getdecremented with 5 every time. As soon as a becomes 0 the loop gets terminated. Output:100 95 90 85 80 75 70 65 60 55 50 45 40 35 30 25 20 15 10 5Click here to view result of this program on browser
| break and continue | |||
| These statements are used with in a loop. Break as the name suggests is used tobreak or terminate the loop in between & continue is to continue the loop breakingit for current loop value. | |||
| break: | |||
| This statement breaks the loop & shifts the control out of the loop. | |||
| continue: | |||
| This statement breaks the loop for current value and resumes the loop with new value. | |||
| Example for break: | |||
| <html>
<head> </head> <body> <script type=”text/javascript”> var count; for(count=0;count<100;count++) { if (count>10) { break } document.write(” “+count) } </script> </body> </html> |
|||
| Understanding program: | |||
| The loop gets terminated because we have kept a condition that if the count is more than 10 than break, break statement will end the loop at that point. | |||
| Output is: | |||
| 0 1 2 3 4 5 6 7 8 9 10 | |||
| Click here to view result of this program on browser | |||
| Example for continue: | |||
| <html>
<head> </head> <body> <script type=”text/javascript”> var count; for(count=0;count<20;count++) { if (count==10) { continue } document.write(” “+count) } </script> </body> </html> |
|||
| Understanding program: | |||
| As soon as the value of count becomes equals to 10 , the loop gets terminated for this value and the loop resumes with new value. | |||
| Output is: | |||
| 0 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 | |||
| Click here to view result of this program on browser | |||
|
|
|||
| for – – in | |||
| This loop is used with arrays and objects , to access their elements and properties respectively.
In for..in looping the variable starts from zero and increases itself with one until it reach to the length of array. |
|||
| Syntax: | |||
| for( variablename in objectname)
{ lines to be executed } |
|||
| Example: | |||
| <html>
<head> </head> <body> <script type=”text/javascript”> var color; var shop=new Array() shop[0]=”Red” shop[1]=”Blue” shop[2]=”Green” shop[3]=”Yellow” shop[4]=”Magenta” for(color in shop) { document.write(“<br> “+shop[color]); } </script > </body> </html> |
|||
| Understanding program: | |||
| Color is a undefined variable and shop is an array, when color is kept as a subscript of array shop then the color variable becomes of number type and from 0 to 4 gets incremented by for – in loop. It is increased up to 4 only because shop array have 5 elements and an array start from 0 position. | |||
| Output is: | |||
| Red Blue Green Yellow Magenta |
|||
| Click here to view result of this program on browser | |||
| Click here to see the animation of Looping.(With Voice) | |||
|
|
|||
Function User defined simple functions
Function is a set of statements recognized by a name and can be used as and when required (it is reusable). In JavaScript functions can be created inside theJavaScript tag only. “function” is a reserve word after which we type the name of the function to be created and then brackets. The code from where the function starts and where ends is kept in side curly braces.
Syntax:
function functionname()
{
lines to be kept under this name
}
Example:
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
function ff()
{
document.write(“Have a nice day”);
}
function pp()
{
document.write(“Try again”);
}
var a
a=parseInt(prompt(“Enter value”,””));
if(a>10)
{
ff()
}
else
{
pp()
}
</script>
</body>
</html>
Understanding program:In the above program ff function is being called if the value entered is more than 10 else pp function is called. Function ff contains a line showing a message “have a nice day” and function pp contains a line showing messages “Try again “ , so which function will be called depends on the value entered. Output is:If value entered is more than 10 thenHave a nice dayElseTry againClick here to view result of this program on browser Example
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
function ff()
{
document.bgColor=”red”;
}
</script >
<input type=”Button” value=” Hit me” name=”b1″ onClick=”ff()”>
</body>
</html>
Understanding program:We created a button and onclick event of that button we called the function ff() , in which we have typed that the background color of the document should be turned to red.Click here to view result of this program on browser
Parameterized functions
Function is a set of statements recognized by a name and can be used as and when required (it is reusable).
A function can accept parameters and can used those accepted values for his purpose. A function can accept many parameters to which we can manage or use as per requirement in the code of that function.
Syntax:
function functionname(var1, var2,..)
{
lines to be kept under this name
}
Example:
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
function ff(f1)
{
var a,b,c
a=parseInt(f1.t1.value)
b=parseInt(f1.t2.value)
c=parseInt(f1.t3.value)
if (a>b && a>c)
{
f1.t4.value=”First Value is greatest”
}
if (b>a && b>c)
{
f1.t4.value=”Second Value is greatest”
} if(c>a && c>b)
{
f1.t4.value=”Third Value is greatest”
}
}
</script >
<form name = “f1″>
Enter first Value<input type=”text” name=”t1″><br>
Enter Second Value<input type=”text” name=”t2″><br>
Enter Third Value<input type=”text” name=”t3″><br>
<input type=”Button” value=” Hit me” name=”b1″ onClick=”ff(f1)”><br>
Result<input type=”text” name=”t4″><br>
<input type=”reset”>
</form>
</body>
</html>
Understanding program:In the above program we type numeric values in top three textboxes and on clicking on hit me button we get result in fourth textbox which one value is greater.Click here to view result of this program on browser Example:
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
function ff(f1)
{
document.bgColor=f1.t1.value;
}
</script >
<form name = “f1″>
Enter the Background Color you want<input type=”text” name=”t1″><br>
<input type=”Button” value=” Hit me” name=”b1″ onClick=”ff(f1)”>
</form>
</body>
</html>
Understanding program:we created a button and onclick event of that button we called the function ff() , to which we passed the function name (f1), this f1 (form) contains a textbox named t1, the value of t1 on form f1 can be accessed by f1.t1.value to which we areassigning to the background color of document so whatever color you will type in the text box will appear on the background.Click here to view result of this program on browser
Functions Returning Values
Function is a set of statements recognized by a name and can be used as and when required (it is reusable).
A function can accept parameters and can return a value back to the calling position. The parameters accepted by a function can be used in the code of that function.
Syntax:
function functionname(var1, var2,..)
{
lines to be kept under this name return(variablename)
}
Example:
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
function max(m)
{
var x,y
y=m[0];
for(x=0;x<m.length;x++)
{
if(m[x]>y)
{
y=m[x]
}
}
return(y)
}
var m=new Array()
m[0]=50
m[1]=12
m[2]=99
m[3]=45
m[4]=120
m[5]=110
m[6]=22
m[7]=106
i=max(m)
document.write(“Maximum Value is “+i)
</script>
</body>
</html>
Understanding program:An array is passed to the function and the greatest value is searched in the arrayand returned back, at calling position a provision to keep the returned value is kept in form of a variable, means whatever value the function will return, will be kept in i variable.Click here to view result of this program on browser
Recursive Functions
A function which calls itself, is called a recursive function. When A function calls itself it gets repeated again and again until the desired condition meets. Recursive functions are such type of functions which calls themselves. A provision to escape from indefinite loop is made in the program.
Example:
<html>
<head>
</head>
<body onclick=”recur()”>
<h1 align=center> Click on me please </h1>
<script type=”text/javascript”>
var a,sum a=sum=0 function recur()
{
if(a<101)
{
sum=sum+a a++ recur()
}
else
{
document.write(“Sum of counts from 0-100 is “+sum)
}
}
</script>
</body>
</html>
Syntax:
function functionname(var1, var2,..)
{
lines to be kept under this name return(variablename)
}
Example:
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
function max(m)
{
var x,y
y=m[0];
for(x=0;x<m.length;x++)
{
if(m[x]>y)
{
y=m[x]
}
}
return(y)
}
var m=new Array()
m[0]=50
m[1]=12
m[2]=99
m[3]=45
m[4]=120
m[5]=110
m[6]=22
m[7]=106
i=max(m)
document.write(“Maximum Value is “+i)
</script>
</body>
</html>
Understanding program:In the above given program we have declared two variables named a and sum a function is there name recur which is being called onclick event (discussed in events section), when user clicks on the web page this function will be called this function isadding the incremented value of a to sum variable and calling again the recur function which again adds the new value of a to sum a condition check is there to check the value of a. when it will become 101 the statement typed under else scope will get executed. Output is:Sum of counts from 0-100 is 5050Click here to view result of this program on browser Example:
<html>
<head>
</head>
<body onclick=”recur()”>
<h1 align=center> Click on me please </h1>
<script type=”text/javascript”>
var a=5 fact=1
function recur()
{
if(a>0)
{
fact=fact*a a– recur()
}
else
{
document.write(“<br> Factorial of “+a+” is “+ fact)
}
}
</script>
</body>
</html>
Output is:Factorial of 0 is 120Click here to view result of this prog
| Scope of a variable | |||
| Any variable in a function is local to that function & the variables declared outside the function are called a global variables , the local variables can be accessed within the function only, while global variables can be accessed anywhere in the program. | |||
| Example: | |||
| <html>
<head> </head> <body onclick=”pp()”> <script> var global=75 function pp() { var local=45 document.write(“<br>This is value of a local variable “+local); document.write(“<br>This is value of a global variable being accessed inside the function “+global) } document.write(“<br>This is value of a global variable “+global) document.write(“<br> If we tried to print or access local variable’s value here it will generate an error for non declaration of variable “) document.write(“<br>Click in The white area to view the value of local variable “) </script> </body > </html> |
|||
| Understanding program: | |||
| In the above given program we have declared two variables named global andlocal, global variable is declared outside the function so it is a global variable means could be accessed in the function as well outside the function also, while local variable is declared inside the function pp so it can be accessed within the function in which it is declared , if we tried to access or print it outside the function an error will generate showing the message that the variable is not declared, because the local variable do not have that scope where we are accessing it so it requires a separate declaration. | |||
| Output is: | |||
| This is value of a local variable 45 | |||
| This is value of a global variable being accessed inside the function 75 | |||
| Click here to view result of this program on browser | |||
| Example: | |||
| <html>
<head> </head> <body onclick=”mm()”> <script type=”text/javascript”> var global =75 function mm() { var local local=45 document.write(“<br>local variable’s Value inside mm function “+local); document.write(“<br>Global Variable’s Value inside mm function “+global) pp(); } function pp() { local=12 document.write(“<br> local variable’s Value inside pp function “+local); document.write(“<br>Global Variable’s Value inside pp function”+global) } document.write(“<br>Global Variable’s Value outside function “+global) document.write(“<br><h1 align=center>Click on Me</h1>”); </script> </body> </html> |
|||
| Output is: | |||
| local variable’s Value inside mm function 45
Global Variable’s Value inside mm function 75 local variable’s Value inside pp function 12 Global Variable’s Value inside pp function75 |
|||
| Click here to view result of this program on browser | |||
| Click here to see the animation of Function.(With Voice) | |||
|
|
|||
Events onBlur events
This event occurs when objects loses the focus. When we move to other object and looses one object the first object is called blurred or lost focus. In javascript we can program this loosing focus using the onblur event.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=”white”>
<h3 align=center>
<u>In this example we used Javascript with in inverted quotes </u>
</h3>
<h4 align=center> just type text in text boxes and click on button</h4>
Name :<input type=”t1″ name=”t1″ id=”tt1″
onblur=”document.all.tt1.style.background=’red’;
document.all.tt1.style.color=’white'”><br>
Address : <input type=”text” name=”t2″ id=”tt2″
onblur=”document.all.tt2.style.background=’red’;
document.all.tt2.style.color=’white'”><br>
<input type=”button” value=”Hit me” name=”b1″>
</body>
</html>
Click here to view result of this program on browser Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=”white”>
<h3 align=center>
<u>In this example we used Javascript with in inverted quotes </u>
</h3>
<h4 align=center> just type text in text boxes and click on button</h4>
Name :<input type=”t1″ name=”t1″ id=”tt1″ onblur=”document.bgColor=’red'”><br>
Address : <input type=”text” name=”t2″ id=”tt2″ onblur=”document.bgColor=’blue'”><br>
<input type=”button” value=”Hit me” name=”b1″>
</body>
</html>
Click here to view result of this program on browser
onclick events
This event occurs when the user clicks on an object. When the mouse left button isclicked on an object the onclick event fires to which we can connect with afunctionality and can it programmed accordingly.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=yellow”>
<h4 align =center> Please Click the mouse on Image</h4>
<blockquote> The height & width of Image will get increased</blockquote>
<img id=”img1″ src=”shark.jpg” height=100 width=100 onclick=”ff()”>
<script>
function ff()
{
document.all.img1.width=500 document.all.img1.height=500
}
</script>
</body>
</html>
click here to view this program in browser
ondblclick events
This event occurs when the user double clicks on an object. When the mouse left button is clicked twice quickly on an object the ondblclick event fires to which we can connect with a functionality and can it programmed accordingly.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=yellow”>
<h4 align =center> Please double Click the link</h4>
<a href=”shark.jpg” ondblclick=”ff()”> Double click on me to load image </a>
<script>
function ff()
{
window.open(“shark.jpg”,””)
}
</script>
</body>
</html>
click here to view this program in browser
onFocus events
This event occurs when objects receives the focus. When we start working with an object that object gets focus. Whether we click on that object or type in it the focus remains on that object. We can program this onfocus event when the focus is brought on the object specified with this event.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=”white”>
<h3 align=center> In this example we used Javascript with in inverted quotes </h3>
Name :<input type=”text” name=”t1″ onFocus=”alert(‘It Got Focus ‘)”><br>
Address : <input type=”text” name=”t2″ onFocus=”alert(‘Now focus is on second text box’)”><br>
</body>
</html>
click here to view result of this program on browser Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=”white”>
<h3 align=center><u>In this example we used Javascript with in inverted quotes </u></h3>
<h4 align=center> just click in second text box and type some thing </h4>
Name :<input type=”text” name=”t1″><br>
Address : <input type=”text” name=”t2″ id=”tt2″ onFocus=”document.all.tt2.style.background=’red’;document.all.tt2.style.c olor=’yellow'”><br>
</body>
</html>
click here to view result of this program on browser
Onkeydown event
This event occurs when user presses a key , at the time of pressing the key thisevent gets fired. When user presses a key from keyboard the key goes down and as soon as the key goes down this event gets fired and can be trapped by using onkeydown event. A programmer can get the key pressed by the user before flashingthe character on the screen.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=yellow>
<h4 align =center> Type character in the textbox </h4>
<blockquote> You will notice that the dialogbox appears before the character appears in the textbox </blockquote>
name : <input type=”text” name=”t1″ onkeydown=”ff()”>
<script>
function ff()
{
alert(“you pressed “+ event.keyCode)
}
</script>
</body>
</html>
click here to view the result of this program in browser
Onkeypress event
This event gets fired when the key is pressed from keyboard and the hand from the key gets removed. This event even can sense the shift or alt key pressed whileonkeydown event is unable to sense these special keys. So many key combinations can be made using this event or the menu shortcut keys can be programmed using this key event.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=yellow>
<h4 align =center> Type character in the textbox </h4>
<blockquote>
You will notice that the dialogbox appears before the character appears in the textbox
</blockquote>
name : <input type=”text” name=”t1″ onkeypress=”ff()”>
<script>
function ff()
{
alert(“ASCII Code of the key you pressed :”+ event.keyCode)
}
</script>
</body>
</html>
Onkeyup event
This event occurs when a key is pressed from the keyboard and pressure from the key gets removed. When the key comes up or there is no more pressure is on the key this event gets fired. If a key is pressed for a long and the character got printed onscreen 20 times this event will get fired only once when the finger will be removed from that key.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=yellow>
<h4 align =center> Type character in the textbox </h4>
<blockquote>
You will notice that the dialogbox appears before the character appears in the textbox
</blockquote>
name : <input type=”text” name=”t1″ onkeydown=”ff()”>
<script>
function ff()
{
alert(“ASCII Code of the key you pressed :”+ event.keyCode)
}
</script>
</body>
</html>
click here to view the result of this program in browser
onLoad This event occurs when the web page gets loaded, this event should be typed in body tag of document. Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=”white” onload=”wel()”>
<marquee direction=up behavior=alternate scrollamount=5 size=0>
<h1 align=center> Welcome </h1>
</marquee>
<script>
function wel()
{
document.bgColor=’yellow’
document.fgColor=’blue’
}
</script>
</body>
</html>
click on the link to view the result of this program on web page
Onmousedown events
This event occurs when the mouse left key is pressed on some object. This event generates when the mouse key got pressed in onclick event when it is pressed are released then onclick event fires but onmousedown event gets fired when the key is pressed only before releasing the key this event gets fired.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=”white” onmousedown=”ff()”>
<h4 align =center> Please click on the web page anywhere you want</h4>
<script>
function ff()
{
alert(“You clicked at : X “+event.screenX+ ” Y: “+event.screenY)
}
</script>
</body>
</html>
click here to view this program in browser
onmousemove events
This event occurs when the user moves mouse. The x and y coordinates of themouse pointer are trapped and when the position changes any of x or y this event fires. We can program the change of position of mouse on the web page using this event.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=yellow onmousemove=”ff()”>
<h4 align =center> Please move the mouse </h4>
<blockquote>
The X axis and Y axis position of Cursor on screen will be displayed in textbox
</blockquote>
name : <input type=”text” name=”t1″ onkeydown=”ff()”>
<script>
function ff()
{
t1.value=”” t1.value=”X : “+event.screenX + ” Y :”+event.screenY
}
</script>
</body>
</html>
click here to view this program in browser
Onmouseout events
This event occurs when the cursor is moved out of the specified object. The position of object and position of mouse pointer is noted if the mouse pointer moves out of the object area this event gets fired.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=”white”>
<h4 align =center> Please bring your mouse over the image and remove it</h4>
<img id=”img1″ src=”water.jpg” height=200 width=200 onmouseover=”ff()” onmouseout=”ff1()”>
<script>
function ff()
{
document.all.img1.width=”190″ document.all.img1.height=”190″
}
function ff1()
{
document.all.img1.width=”200″ document.all.img1.height=”200″
}
</script>
</body>
</html>
click here to view this program in browser
Onmouseover events
This event occurs when the cursor is brought over the specified object, thecoordinates of the object are noted and if the position of cursor falls inside those coordinates this event gets fired, to which we can program accordingly.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=”white”>
<h4 align =center> Please bring your mouse over the image</h4>
<img id=”img1″ src=”water.jpg” height=200 width=200 onmouseover=”ff()”>
<script>
function ff()
{
document.all.img1.width=”180″ document.all.img1.height=”180″
}
</script>
</body>
</html>
click here to view this program in browser
Onmouseup events
This event occurs when the user clicks on some specified object and releases themouse key this event gets fired. The time between the clicking and the releasingthe key is the time of fire of this event.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=”white” onmousedown=”ff()” onmouseup=”ff1()”>
<h4 align =center> Please Drag the mouse on the web page anywhere you want</h4>
<script>
var x,y,x1,y1 function ff()
{
x=event.screenX y=event.screenY
}
function ff1()
{
x1=event.screenX y1=event.screenY alert(“You brought mouse down at : X “+x+ ” Y: “+y+ ” and brought it up at X:” +x1+” Y: “+y1)
}
</script>
</body>
</html>
click here to view this program in browser
onreset event
This event gets fired when user clicks on the reset button on a form. A form contains reset button which fires onreset event when it is clicked resulting it vacates all the filled objects like textbox , checkboxes etc.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=red text=”white” >
<form name=”sandeep” onreset=”alert(‘ This form is being reseted’)”>
Name : <input type=”text” name=t1 id=”tt1″ ><br>
Address : <input type=”text” name=t2 ><br>
<input type=”reset” name=”b1″><br>
</form>
</body>
</html>
click here to view results of this program on browser Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=red text=”white” >
<form name=”sandeep” onreset=”pp()”>
Name : <input type=”text” name=t1 id=”tt1″ ><br>
Address : <input type=”text” name=t2 id=”tt2″ ><br>
<input type=”reset” name=”b1″ id=”bb1″><br>
</form>
<script>
function pp()
{
document.all.tt1.style.background=’yellow’ document.all.tt2.style.background=’yellow’ document.all.bb1.style.background=’red’ document.all.bb1.style.color=’white’ document.bgColor=’magenta’
}
</script>
</body>
</html>
click here to view results of this program on browser
onresize event
This event gets fired when resizes the web page window. A web page window can be resized, an onresize event gets fired when a web page window is resized, to which we can program accordingly.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=blue text=”white” onresize=”pp()”>
<marquee direction=up behavior=alternate>
These pages are Developed by Vishwajit Vatsa.
</marquee>
<h1>
<marquee direction=right behavior=alternate>
These pages are Developed by Sandeep Singh Bhandari.
</marquee>
</h1>
<h1>
If you minimize or maximize this page onresize event will be fired.
</h1>
<script>
function pp()
{
var a=confirm(“Really want to resize”) if (a)
{
document.bgColor=’red’
}
else
{
document.bgColor=’green’
}
}
</script>
</body>
</html>
click here to view results of this program on browser
| onselect event | |||
| This event gets fired when user selects text in a textbox or text field. A text field contains text and we can select that text but when we select text of a text fieldonselect event gets fired. | |||
| Example: | |||
| <html>
<head> <title>events </title> </head> <body bgcolor=blue text=”white” > <form name=”sandeep” onselect=”alert(‘hi’)”> Name : <input type=”text” name=t1 id=”tt1″ ><br> Address : <input type=”text” name=t2 ><br> Educational Qualification : <select> <option> 10th <option> 12th <option> Graduate <option> Post Graduate <option> PhD </select><br> Comments :<br> <textarea rows=5 onselect=”alert(‘yes delete this selected text’)”> You can type this text and type your comments here </textarea> </form> <script> function ff() { alert(“The value being set is ” +document.all.tt1.value) } </script> </body> </html> |
|||
| click here to view results of this program on browser | |||
|
|
|||
onsubmit events
This event gets fired when user clicks on the submit button. a form containssubmit button which contains the onsubmit event. When this button is clicked this event gets fired.
Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=red text=”white” >
<form name=”sandeep” onsubmit=”alert(‘got submitted’)”>
Name : <input type=”text” name=t1 id=”tt1″ ><br>
Address : <input type=”text” name=t2 ><br>
<input type=”submit” name=”b1″><br>
</form>
</body>
</html>
click here to view results of this program on browser Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=red text=”white” >
<form name=”sandeep” onsubmit=”ff()”>
Name : <input type=”text” name=t1 id=”tt1″ ><br>
Address : <input type=”text” name=t2 ><br>
<input type=”submit” name=”b1″><br>
</form>
<script>
function ff()
{
alert(“The value being set is ” +document.all.tt1.value)
}
</script>
</body>
</html>
click here to view results of this program on browser
Unload Events This event occurs when the focus from the page gets lost because of some link etc. Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=green text=”white” onload=”wel()” onunload=”thx()”>
<marquee direction=up behavior=alternate scrollamount=5 size=0>
<h1 align=center> Welcome </h1>
</marquee>
<h1> Click on link to unload this page </h1>
<a href=’exeventonload.php’> hit me to unload this page </a>
<script>
function wel()
{
document.bgColor=’yellow’
document.fgColor=’blue’
}
function thx()
{
alert(“Thanx to visit me “)
}
</script>
</body>
</html>click on the link to view the result of this program on web pageClick here to see the animated presentation of Events.(With Voice)
DOM window Window is the top most level object in the JavaScript hierarchy as we saw in DOM topic, window object represents a browser window. Every <body> tag creates an window object. As we know that an object can have properties and methods or functions. Window object have man properties and methods listed below to know about any property click on that property. Properties: document
History
Location
Name
closed
toolbar
scrollbars Methods Open()
print()
alert()
confirm()
close()
moveTo()
prompt() PropertiesName This window property is used to set or get the name of the window in use. When we are working with many windows it becomes very necessary to know the name of the window we are working with. The below given example shows how to get the name of the window in use. Example:
<html>
<head>
<script>
function nm()
{
document.write(“<br> Current Window Name is : “+win.name)
}
</script>
</head>
<body><script>
win=window.open(”,’Sandeep’,’width=150,height=150′)
win.document.write(“This is a new window created by sandeep , it’s name is sandeep, move the window & click on the button “)
</script><input type=”button” value=”Hit me to know name of window” onclick=”nm()”></body>
</html>
Click here to view result of this program on browser Closed This window property is used to know whether the specified window is closed or not many times a processing is to be done but before that it becomes necessary to check whether the page is open or not we can use this window property to know the status of the window. The below given example shows how to get the status of the window in use. Example:
<html>
<head>
<script>
function nm()
{
if (win.closed)
{
document.write(“<br> Sorry.. The window has been closed”)
}
else
{
document.write(“<br> The window is open enjoy.. it”)
}
}
</script>
</head>
<body><script>
win=window.open(”,’Sandeep’,’width=150,height=150′)
win.document.write(“This is a new window created by sandeep , it’s name is sandeep, move the window & click on the button “)
</script><input type=”button” value=”Hit me to know name of window” onclick=”nm()”></body>
</html>
Click here to view result of this program on browser Toolbar This window property is used to add the toolbar to the window at the time of creation of window , Standard toolbar appears which can be used to move forward or back , go or refresh etc. properties of the toolbar could be accessed. The below given example shows how to set the toolbar to the window. Example:
<html>
<head>
</head>
<body>
<script>
win=window.open(”,’Sandeep’,’width=450,height=350,toolbar’)
win.document.write(“This is a new window created by sandeep , it’s name is sandeep, move the window & click on the button “)
</script>
</body>
</html>
Click here to view result of this program on browser Scrollbars This window property is used to add the scrollbars to the window at the time of creation of window , scrollbars are used to move up or down on the page having matter more than the window size. The below given example shows how to set the scrollbars to the window. Example:
<html>
<head>
</head>
<body>
<script>
win=window.open(”,’Sandeep’,’width=450,height=350,toolbar,scrollbars’)
win.document.write(“This is a new window created by sandeep , it’s name is sandeep, move the window & click on the button “)
</script>
</body>
</html>
Click here to view result of this program on browser MethodsOpen() This window method is used to open the specified window. Using this method we can open any window from code as and when required. The below given example shows how to open a window using JavaScript code. Example:
<html>
<head>
</head>
<body>
<script>
var i=0
var winname=”sandeep”
for(i=0;i<5;i++)
{
winname=winname+i
win=window.open(”,”+winname,’width=450,height=350,toolbar,scrollbars’)
win.document.write(“This is a new window created by sandeep , it’s name is sandeep, move the window & click on the button “)
}
</script>
</body>
</html>
Click here to view result of this program on browser print() This window method is used to print the specified window contents on printer. We can activate the printer control panel using this method and set desired print settings. The below given example shows how to print a widow contents. Example:
<html>
<head>
<script>
function ff()
{
window.print()
}
</script>
</head>
<body>
<input type=button name=b1 value= “hit me to print the page ” onclick=”ff()”>
<script>
win=window.open(”,’Sandeep’,’width=450,height=350,toolbar’)
win.document.write(“This is a new window created by sandeep , it’s name is sandeep, move the window & click on the button “)
</script>
</body>
</html>
Click here to view result of this program on browser Alert Box Alert box is a dialog box which displays a message in a small window with an OK button, user have to click on the ok button to proceed. Example:
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
alert(“Hit me to proceed”)
document.write(” Have a nice day “);
</script >
</body>
</html>
Understanding the program:user can type his desired message with the alert box in the quotes like alert(“what ever text user want “). This message will be displayed with the alert window to guide the user. output is:Have a nice dayClick here to view result of this program on browser Confirm Box Confirm box is a dialog box which displays a message in a small window with two buttons. One Ok and other Cancel. This method can be used to get the response of user in positive by clicking on ok and in negative by clicking on cancel. The value returned by the confirm method in case of OK is true and in case of Cancel is false. A programmer can program the code for positive and negative situations depending on the response returned by the user. Example:
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
a=confirm(” Want to Proceed ? “);
document.write(“Your have clicked on : “+a);
</script >
</body>
</html>
understanding the program:If user will clicks on Ok then you have clicked on true will appear
If user will clicks on Cancel then you have clicked on false will appearClick here to view result of this program on browser Close This window method is used to close the specified window. Using this method we can closed any window from code as and when required. The below given example shows how to close a window after clicking on a button. Example:
<html>
<head>
<script>
function ff()
{
win.close()
}
</script>
</head>
<body>
<input type=button name=b1 value= “hit me to Close the window ” onclick=”ff()”>
<script>
win=window.open(”,’Sandeep’,’width=450,height=350,toolbar’)
win.document.write(“This is a new window created by sandeep , it’s name is sandeep, move the window & click on the button “)
</script>
</body>
</html>
Click here to view result of this program on browser moveTo() This window method is used to move the specified window to desired location on screen. The two parameter s are passed with this function one for x coordinate and other for y coordinate. Using this method we can position window to our desired position using code. The below given example shows how to position a window using JavaScript code. Example:
<html>
<head>
</head>
<body>
<script>
var i=0
var winname=”sandeep”
for(i=0;i<5;i++)
{
winname=winname+i
win=window.open(”,”+winname,’width=450,height=350,toolbar,scrollbars’)
win.document.write(“This is a new window created by sandeep , it’s name is sandeep, move the window & click on the button “)
}
</script>
</body>
</html>
Click here to view result of this program on browser Prompt Box Prompt box is a dialog box which displays a message in a small window with a text box along with two buttons . One OK and other Cancel. Prompt method has ability to return the text kept with the prompt method’s text box , this value can be assigned to some variable and can be used as and when require. Example:
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
prompt (“Enter your name”, “”)
</script >
</body>
</html>
understanding the program :A dialog box with a text box and two buttons will appear, the message typed with prompt method will be displayed on the dialog box the text box will appear blank , if any text is typed at the place of blank (“ ”), that text will appear in the text box on dialog box. Click here to view result of this program on browser Example
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
prompt (“Enter your name”, ” enter your name here”)
</script >
</body>
</html>
understanding the program :A dialog box with a text box and two buttons will appear, the message typed with prompt method will be displayed on the dialog box the text box will appear filled with “ enter your name here “ text.Click here to view result of this program on browser Storing value accepted from a prompt box in variables :
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var name,address
name=prompt (“Enter your name”, ” enter your name here”)
address = prompt (“Enter your address”, “Address Please “)
document.write(“Your Name : “+name);
document.write(“<br>Your Address : “+address);
</script >
</body>
</html>
understanding program :As we know that prompt method has the ability to return the text stored in it’s text box, so the name fed by the user will be stored in the name variable and address of user in address variable, which will be displayed on the screen by document.write method. Output is :Your Name : Rhythm
Your Address : A -45, Preet Vihar, Delhi – 110092 Click here to view result of this program on browser
DOM Navigator
Navigator contains information about the client’s browser. A user surfs the internet using a browser program like internet explorer or Netscape navigator. These programs are quite smart programs. Javascript Navigator object contains information about user’s browser program. The properties and methods of navigator object are listed below.
Properties:appName
onLine
platform
appCodeName
appVersion MethodsJavaEnabled() PropertiesappName()
This navigator property returns the current browser’s name. Different users use different browser program many times it becomes very necessary to know the browser name of the user because it is possible that some particular command do not work on some specific browser. To know the name of the browser we can use this method.
Example:
<html>
<head>
</head>
<body bgcolor=red text=yellow>
<script type=”text/javascript”>
document.write(“<br>My current browser is : “+navigator.appName)
</script>
</body>
</html>
Click here to view result of this program on browser onLine () This navigator property returns true if the computer is in offline mode else false. If our computer is online this method returns false else it returns true. Example:
<html>
<head>
</head>
<body bgcolor=red text=yellow>
<script type=”text/javascript”>
document.write(“<br>My current browser is : “+navigator.onLine)
</script>
</body>
</html>
Click here to view result of this program on browser platform () This navigator property returns the operating system platform. Any operating system follows a platform (some basic rules set) , like whether it is 16 bit program or 32 bit program. This method provides facility to know the operating system platform so that with this knowledge the user can put desired condition in his program. Example:
<html>
<head>
</head>
<body bgcolor=red text=yellow>
<script type=”text/javascript”>
document.write(“<br>My current operating system platform is : – “+navigator.platform)
</script>
</body>
</html>
Click here to view result of this program on browser appCodeName () This navigator property returns browser’s code name. Every browser performs certain code. To know the code name of that browser we can use this method. Example:
<html>
<head>
</head>
<body bgcolor=red text=yellow>
<script type=”text/javascript”>
document.write(“<br>My current operating system platform is : – “+navigator.appCodeName)
</script>
</body>
</html>
Click here to view result of this program on browser appVersion () This navigator property returns browser’s platform and version (version is the advancement level). This property is used to know that what platform the user is using what is the version (advancement level) of user’s platform. Example:
<html>
<head>
</head>
<body bgcolor=red text=yellow>
<script type=”text/javascript”>
document.write(“<br>My Browser’s Details : – “+navigator.appVersion)
</script>
</body>
</html>
Click here to view result of this program on browser MethodJavaEnabled() This navigator property returns true if the browser is java enabled else false. Java is a very powerful language, our web page may require connectivity to a Java program but in that case the browser should be java enabled. If the browser will not be java enabled then the functionalities programmed in java will not work properly. To know whether the browser is java enabled or not we can use this method. Example:
<html>
<head>
</head>
<body bgcolor=red text=yellow>
<script type=”text/javascript”>
document.write(“<br>My Browser is Java Enabled ? : – “+navigator.javaEnabled())
</script>
</body>
</html>
Click here to view result of this program on browser
DOM screen
Screen object contains information about the client’s screen . Different users can have different screen sizes and types. In case we want to create something we should keep in mind the screen dimensions will not be same and because the screen sizes will not be same so other properties will also require attention. The properties of screen object are listed below.
Properties: height
width
availHeight
availWidth height This screen property returns the screen height . Example:
<html>
<head>
</head>
<body bgcolor=red text=yellow>
<script type=”text/javascript”>
document.write(“<br> the work area height is “+screen.height + ” px.”)
</script>
</body>
</html>
Click here to view result of this program on browser Width This screen property returns the screen width . Different screens can have different dimensions , width property returns the height of the screen in use. A programmer can program suitably after knowing the height of screen in use. Example
<html>
<head>
</head>
<body bgcolor=red text=yellow>
<script type=”text/javascript”>
document.write(“<br> the screen width is “+screen.width + ” px.”)
</script>
</body>
</html>
Click here to view result of this program on browser availheight This screen property returns the screen height (screen height– taskbar). A web page is displayed on the screen availheight property returns the screen height which can be calculated by total screen height – height of taskbar. Example:
<html>
<head>
</head>
<body bgcolor=red text=yellow>
<script type=”text/javascript”>
document.write(“<br> the work area height is
“+screen.availheight + ” px.”)
</script>
</body>
</html>
Click here to view result of this program on browser availwidth This screen property returns the screen width (screen width– taskbar). Different screens can have different dimensions , availwidth property returns the screen web page available width of the screen in use. A programmer can program suitably after knowing the height of screen in use. Example:
<html>
<head>
</head>
<body bgcolor=red text=yellow>
<script type=”text/javascript”>
document.write(“<br> the work area height is “+screen.availheight + ” px.”)
</script>
</body>
</html>
Click here to view result of this program on browser
DOM History
History object contains information about the URLs user has accessed or visited using browser window. When a user access a web page the details of that web page are stored on computer by browser in form of history. We can access these details using the history object .The properties and methods of history object are listed below.
Properties:Length MethodsBack()
Forward()
Go() Propertieslength length property of history object returns total number of elements in history list. The number of objects in the history list may be different at different times because generally person do not visit same number of pages. Length property returns us the total number of pages available in history collection. Example:
<html>
<head>
</head>
<body>
<blockquote> history length will tell you that how many
elements are in history list </blockquote>
<script type=”text/javascript”>
document.write(history.length)
</script>
</body>
</html>Click here to view result of this program on browser MethodBack() This history object’s method loads the previous URL in the history list. The page we just left after moving to new page is history for current page. We can access the previous page by using back() method. This method will drop us back to the previous page. Example:
<html>
<head>
</head>
<body>
<blockquote>If any page is opened in the browser before
this page the it will call that page back </blockquote>
<script type=”text/javascript”>
function ff()
{
history.back()
}
</script>
<input type =”button” value=”hit me to go back ” name=”b1″
onclick=”ff()”>
</body>
</html>
Click here to view result of this program on browser Forward() This history object’s method loads the next URL in the history list. There is a list page name in history. To go to the page next to current page or url can be accessed by forward () method. It will drop us on the next page to current page. Example:
<html>
<head>
</head>
<body>
<blockquote>If any page is opened in the browser before
this page the it will call next page</blockquote>
<script type=”text/javascript”>
function ff()
{
history.forward()
}
</script>
<input type =”button” value=”hit me to go forward ”
name=”b1″ onclick=”ff()”>
</body>
</html>
Click here to view result of this program on browser go() This history object’s method loads the specified web page number in the history list. To load any page in history we can use go () method. This method calls the specified web page and loads it on browser. Example:
<head>
</head>
<body>
<blockquote>It will call the specified page number inthe
history list</blockquote>
<script type=”text/javascript”>
function ff()
{
history.go(-2)
}
</script>
<input type =”button” value=”hit me to go forward ”
name=”b1″ onclick=”ff()”>
</body>
</html>
Click here to view result of this program on browser
DOM document window is the top most level object in the JavaScript hierarchy as we saw in DOM topic, document object is child object of window object. Object model also contains collections. A collection is an array holding one or more objects. The collection in document object is ‘all’ which represent all the elements in the document. A document object can be used to access all the elements on a page using all collection. The collections, properties, objects are listed below. Collections:anchors[]
forms[]
images[] Properties:cookie
title
URL
lastmodified MethodsgetElementById()
getElementbyTagName()
write() CollectionAnchorsAnchor collection returns details about anchors available on your web page. Anchors are links created in a document to get connected with other documents. Using these links we can call other specified document on the browser. Example:
<html>
<head>
</head>
<body>
<a name=”one”> this is anchor no. 1 </a><br>
<a name=”two”> this is anchor no. 2 </a><br>
<a name=”three”> this is anchor no. 3 </a><br>
<a name=”four”> this is anchor no 4 </a><br>
Total no of anchors in this page are :
<script>
document.write(document.anchors.length);
</script>
</body>
</html>
Output is:this is anchor no. 1
this is anchor no. 2
this is anchor no. 3
this is anchor no 4 Total no of anchors in this page are : 4Click here to view result of this program on browser Example:
<html>
<head>
<title>anchors </title>
</head>
<body>
<a name=”one”> this is anchor no. 1 </a><br>
<a name=”two”> this is anchor no. 2 </a><br>
<a name=”three”> this is anchor no. 3 </a><br>
<a name=”four”> this is anchor no 4 </a><br>
the name of anchor no 2 is:
<script>
document.write(document.anchors[1].name);
</script>
</body>
</html>
Output is: this is anchor no. 1
this is anchor no. 2
this is anchor no. 3
this is anchor no 4
the name of anchor 2 is : twoClick here to view result of this program on browser Example:
<html>
<head>
<title>anchors </title>
</head>
<body>
<a name=”one”> this is anchor no. 1 </a><br>
<a name=”two”> this is anchor no. 2 </a><br>
<a name=”three”> I am anchor no. 3 India is great </a><br>
<a name=”four”> this is anchor no 4 </a><br>
The Text inside anchor no. 3 is :
<script>
document.write(“<br>”+document.anchors[2].innerHTML);
</script>
</body>
</html>
output is:this is anchor no. 1
this is anchor no. 2
I am anchor no. 3 India is great
this is anchor no 4
The Text inside anchor no. 3 is :
I am anchor no. 3 India is greatClick here to view result of this program on browser forms forms collection returns details about form objects available on your web page. All the elements contained by a form can be accessed by form object. Example:
<html>
<head>
<title>forms </title>
</head>
<body bgcolor=red text=”yellow”>
<form name=”f1″>
name <input type=text name=t1>
</form>
<form name=”f2″>
name <input type=text name=tt1>
</form>
<form name=”f3″>
name <input type=text name=ttt1>
</form>
Name of First form is
<script>
document.write(document.forms[0].name);
</script>
</body>
</html>
Output is:name name name Name of First form is f1Click here to view result of this program on browser Example
<html>
<head>
<title>forms </title>
</head>
<body bgcolor=red text=”yellow”>
<form name=”f1″>
name <input type=text name=t1>
</form>
<form name=”f2″>
name <input type=text name=tt1>
</form><form name=”f3″>
name <input type=text name=ttt1>
</form>
Total no of forms on page are :
<script>
document.write(document.forms.length);
</script>
</body>
</html>
Click here to view result of this program on browser Example:
<html>
<head>
<title>forms </title>
</head>
<body bgcolor=red text=”yellow”>
<form name=”f1″>
name <input type=text name=t1>
</form>
<form name=”f2″>
name <input type=text name=tt1 value=”hi user”>
</form>
<form name=”f3″>
name <input type=text name=ttt1>
</form>
Total no of forms on page are :
<script>
document.write(document.forms[1].tt1.value);
document.write(“<br>Total no of elements of form 3 are ” +document.forms[2].elements.length);
</script>
</body>
</html>
Output is:name name name Total no of forms on page are : hi user Total no of elements of form 3 are 1Click here to view result of this program on browser images forms collection returns details about images available on your web page. A web page contains images which forms an array or collection. This collection can return each and every detail about any image present on the web page using different image properties. Example:
<html>
<head>
<title>forms </title>
</head>
<body bgcolor=red text=”yellow”>
<img name=”delhi” src=”dom.gif” width=100 height=100 hscpace=5 vspace=5 border=5>
<img name=”dehradune” src=”dom.gif” width=100 height=100 hscpace=5 vspace=5 border=5>
<img name=”srinagar” src=”dom.gif” width=100 height=100 hscpace=5 vspace=5 border=5>
<img name=”patna” src=”dom.gif” width=100 height=100 hscpace=5 vspace=5 border=5><br><br>
Name of firs image on page is :
<script>
document.write(document.images[0].name);
</script>
</body>
</html>
Output is:Name of first image on page is : delhiClick here to view result of this program on browser Example:
<html>
<head>
<title>forms </title>
</head>
<body bgcolor=red text=”yellow”>
<img name=”delhi” src=”dom.gif” width=100 height=100 hscpace=5 vspace=5 border=5>
<img name=”dehradune” src=”dom.gif” width=100 height=100 hscpace=5 vspace=5 border=5>
<img name=”srinagar” src=”dom.gif” width=100 height=100 hscpace=5 vspace=5 border=5>
<img name=”patna” src=”dom.gif” width=100 height=100 hscpace=5 vspace=5 border=5><br><br>
Total no of images on page are :
<script>
document.write(document.images.length);
</script>
</body>
</html>
Output is:Total no of images on page are : 4Click here to view result of this program on browser Example:
<html>
<head>
<title>forms </title>
</head>
<body bgcolor=red text=”yellow”>
<img name=”delhi” src=”dom.gif” width=100 height=100 hscpace=5 vspace=5 border=5>
<img name=”dehradune” src=”dom.gif” width=100 height=100 hscpace=5 vspace=5 border=5>
<img name=”srinagar” src=”dom.gif” width=100 height=100 hscpace=5 vspace=5 border=5>
<img name=”patna” src=”dom.gif” width=100 height=100 hscpace=5 vspace=5 border=5><br><br>
width and height of third image on page :
<script>
document.write(“<br> Height “+document.images[2].height);
document.write(“<br> Width “+document.images[2].width);
</script>
</body>
</html>
output is:width and height of third image on page : Height 100Width 100Click here to view result of this program on browser PropertiesCookie Cookies property returns or sets the cookies associated with current document. Cookies are the text which helps the server to identify a computer. Server responses the request of a client. Example:
<html>
<head>
</head>
<body>
<h1 align=center> … Cookies with this page … </h1>
<script type=”text/javascript”>
a=”Vishwajit Vatsa ”
document.cookie=a
document.write(document.cookie)
</script >
</body>
</html>
output is:… Cookies with this page …name=Vishwajit VatsaClick here to view result of this program on browser title This property returns the title of the web page. A web page can have a title created using title tag. We can know the title of any web page using title property of document object. Example:
<html>
<head>
<title> This is just trial </title>
</head><body>
<h3 align=center> …Title of this page … </h3>
<script type=”text/javascript”>
document.write(document.title)
document.write(“<br>Total characters in Title are “+document.title.length) a=prompt(“Enter new Title”,””)
document.title=a document.write(“<br> New Title is “+document.title)
</script >
</body>
</html>
output is:…Title of this page …This is just trial
Total characters in Title are 18
New Title is sarlaClick here to view result of this program on browser URL This property returns the URL of the current document. URL stands for uniform resource location. This could be the location on a local machine or on remote machine. Where ever a document is stored is called it’s URL. URL returns the address of the document. Example:
<html>
<head>
<title> This is just trial </title>
</head>
<body>
<h3 align=center> …URL of this page … </h3>
<script type=”text/javascript”>
document.write(document.URL)
document.write(“<br>Total characters in URL are “+document.URL.length) a=prompt(“Enter new URL or address of any html file “,””)
document.URL=a document.write(“<br> New URL is “+document.URL)
</script >
</body>
</html>
Click here to view result of this program on browser lastModified lastModified property returns date & time of a document last modified. The access and modification of every javascript file is maintained by lastModified property. We can know the date and time of any file got modified. Example:
<html>
<head>
</head>
<body>
<h3 align=center> … The last modification with this page was made on … </h3>
<script type=”text/javascript”>
document.write(document.lastModified)
</script >
</body>
</html>
output is:… The last modification with this page was made on …01/01/2000 00:17:40Click here to view result of this program on browser MethodgetElementById() getElementById() method returns a reference to the first object with specified id. An object can have an id with it for it’s recognition we can access that element using getElementById() function. Example:
<html>
<head>
</head>
<body>
<h4 id=”obj3″ > We teach our children how to walk and we also teach them that we can not fly </h4>
<script type=”text/javascript”>
var a=document.getElementById(“obj3”)
document.write(“<br>”+a.innerHTML)
</body>
</html>
output is:We teach our children how to walk and we also teach them that we can not fly.Click here to view result of this program on browser getElementbyTagName() getElementbyTagName method returns a collection of objects with specified tag name. All the objects can have user defined name. We can access that element using the getElementbyTagName() function. Example:
<html>
<head>
</head>
<body>
<a > this is very cold </a><br>
<a > It is true the true never dies </a><br>
<h5> it is heading 5 </h5>
<h5>it is heading 5 </h5>
<script type=”text/javascript”>
var a=document.getElementsByTagName(“h5″)
document.write(” h5 tag is used “+a.length+” Times”)
document.write(“<br> text in first h5 is :- “+a[0].innerHTML);
</script>
</body>
</html>
output is:this is very cold
It is true the true never dies
it is heading 5
it is heading 5
var a=document.getElementsByTagName(“h5″) document.write(” h5 tag is used “+a.length+” Times”) document.write(”
text in first h5 is “+a[0].innerHTML); h5 tag is used 2 Times
text in first h5 is it is heading 5 h5 tag is used 2 Times
text in first h5 is it is heading 5Click here to view result of this program on browser write write method displays the text and/or HTML expressions typed in the brackets on the web page. Write method displays the text and the variable values on the monitor. In javascript a HTML code can also be used inside a write method brackets. Example:
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var a,b,c document.write(“This is a simple text, we used write method
to print this line “);
document.write(“<br>here is a HTML expression
<body bgcolor=red text=yellow> “)
</script >
</body>
</html>
output is:This is a simple text, we used write method to print this linehere is a HTML expressionClick here to view result of this program on browser
Try — Catch It is very difficult to analyze all the situations to arise during runtime of a program because of which some conditions may remain unanswered, these unanswered conditions are called exceptions, JavaScript provides a facility to handle such situations. We can use try and catch statements to handle such situations. The whole code is kept inside the try block an in case any exception arises it is thrown using throw statement which is caught by the catch statement. Example:
<html>
<head>
<title>events </title>
</head>
<body bgcolor=blue text=”white” >
<h4> Enter Either Value as Zero (0)</h4>
Value 1: <input type=”text” id=”t1″><br>
Value 2: <input type=”text” id=”t2″><br>
Answer: <input type=”button” id=”b1″ value=”Hit me ” onclick=”pp()”><br>
<script>
function pp()
{
var c= parseInt(document.all.t1.value)
var d=parseInt(document.all.t2.value)
var e=0
try
{
if(d==0)
{
throw “Divisor is Zero”
}
if (c==0)
{
throw “To be divided is Zero”
}
}
catch(error) {
alert(error)
}
}
</script>
</body>
Click here to view the result of this program on browser
Throw It is very difficult to analyze all the situations to arise during runtime of a program because of which some conditions may remain unanswered, these unanswered conditions are called exceptions, JavaScript provides a facility to handle such situations. We can use try and catch statements to handle such situations. The whole code is kept inside the try block an in case any exception arises it is thrown using throw statement which is caught by the catch statement. Example
<html>
<head>
<title>events </title>
</head>
<body bgcolor=blue text=”white” >
<h4> Enter Week Day Please</h4>
Value 1: <input type=”text” id=”t1″ ><br>
Value 1: <input type=”button” id=”b1″ value=”Hit me ” onclick=”pp()”><br>
<script>
function pp()
{
var c= parseInt(document.all.t1.value)
try
{
switch(c)
{
case 1 :
throw “Sunday”
break
case 2:
throw “Monday”
break
case 3:
throw “Tuesday”
break
case 4:
throw “Wednesday”
break
case 5:
throw “Thrusday”
break
case 6:
throw “Friday”
break
case 7:
throw “Saturday”
break
default:
throw “The real error”
}
}
catch(error) {
alert(error)
}
}
</script>
</body>
</html>Click here to view the result of this program on browser
Objects Properties Properties are variables having values desired for an object and these variables determines the behaviour of that object. The variable can have different types of data .The type of data determines the type of variable. What an object contains is actually it’s properties or variable used for it. The properties of an object can be changed by using a method. Example
<html>
<head>
</head>
<body>
<script>
var car = new Object
car.name=”Ferari”
car.color=”red”
car.no=”DEL1504″
document.write(“<br> Car Name :”+car.name)
document.write(“<br> Car Color :”+car.color)
document.write(“<br> Car Number :”+car.no)
</script>
</body>
</html>
Output is:
Car Name :Ferari
Car Color :red
Car Number :DEL1504
Click here to view result of this program in browser
Methods Methods are set of actions that allow the access to the variables of an object. A Method contains the code to perform some task for an/many object(s). The methods and the variables forms an object. Example
<html>
<head><title> Functions are like Objects </title>
</head>
<body>
<script>
function car()
{
var car = new Object
car.name=”Lancer”
car.color=”Blue”
car.no=”MAH2059″
document.write(“<br> Car Name :”+car.name)
document.write(“<br> Car Color :”+car.color)
document.write(“<br> Car Number :”+car.no)
}
var mycar= car
mycar()
</script>
</body>
</html>
Output is:
Car Name :Lancer
Car Color :Blue
Car Number :MAH2059
Click here to view result of this program in browser
Functions also behaves like objects? In Javascript functions also behave like objects. In JavaScript we can use function like an object. As an object is collection of variables and methods. The function also contains variables. We can access a function variables like object property by usingdot(.) operator, as we access an object property. Example
<html>
<head>
</head>
<body>
<script>
function road()
{
var car = new Object
car.name=”Lancer”
car.color=”Blue”
car.no=”MAH2059″
document.write(“<br> Car Name :”+car.name)
document.write(“<br> Car Color :”+car.color)
document.write(“<br> Car Number :”+car.no)
}
var mycar= new Object
mycar.details=road
mycar.details()
</script>
</body>
<html>
Output is:
Car Name :Lancer
Car Color :Blue
Car Number :MAH2059
Click here to view result of this program in browser
Arrays also behave like objects?
In JavaScript arrays also behave like objects. An array is collection of variables, an object is also collection of variables. In JavaScript we can access anarray subscripts like an object properties by using a dot(.) operator. So in JavaScript we can we have facility to use arrays like object also.
Example
<html>
<head><title> Arrays are like Objects </title>
</head>
<body bgcolor=green text=”yellow”>
<h4 align=center> We are using array elements as Object properties </h4>
<script language=”JavaScript”>
var demo1= new Array()
demo1[0]=”Car”
demo1[1]=”BUS”
demo1[2]=”Truck”
document.write(“<br> Vehicle Type : “+demo1[0]);
document.write(“<br> Vehicle Type : “+demo1[1]);
document.write(“<br> Vehicle Type : “+demo1[2]);
demo1.name=”Sandeep”
demo1.mname=”Singh”
demo1.lname=”Bhandari”
document.write(“<br><br>I am :”+demo1.name+” “+demo1.mname+” “+demo1.lname)
document.write(“<br><br> My Name is : “+demo1[“name”]);
document.write(“<br> My Middle Name is : “+demo1[“name”]);
document.write(“<br> My Last Name is : “+demo1[“name”]);
</script>
</body>
</html>
Output is:We are using array elements as Object properties
Vehicle Type : Car
Vehicle Type : BUS
Vehicle Type : Truck
I am :Sandeep Singh Bhandari
My Name is : Sandeep
My Middle Name is : Sandeep
My Last Name is : Sandeep
Click here to view result of this program in browser
Form Object Text
Text is used to access text field of a form. A text field is created when we use input tag with type as text property, a text field is generated a text field should have a name for it’s easier recognition. This text field can be used to type the textual datalike name, address etc.
Example
<html>
<head><title> Text Element </title>
</head>
<body bgcolor=green text=”yellow”>
<h4 align=center> Click on Desired Button</h4>
<input type =”text” name=”t1″ id=”tt1″ style=”position:absolute;background:white;color:black;width:100;”><br><br>
<input type =”Button” name=”b1″ value=”Color” onclick=”colo()”>
<input type =”Button” name=”b1″ value=”Size” onclick=”sz()”>
<input type =”Button” name=”b1″ value=”Value” onclick=”values()”>
<input type =”Button” name=”b1″ value=”Position” onclick=”pos()”>
<script language=”JavaScript”>
function colo()
{
a=prompt(“Enter Color name , you want “,””)
document.all.tt1.style.background=a;
}
function sz()
{
a=prompt(“Enter size , you want “,””)
if(isNaN(parseInt(a)))
{
alert(“Wrong entry”)
}
else
{
document.all.tt1.style.width=a;
}
}
function values()
{
alert(“Value in Text box is “+document.all.tt1.value);
}
function pos()
{
a=prompt(“Enter X Position , you want “,””)
b=prompt(“Enter Y Position , you want “,””)
document.all.tt1.style.pixelLeft=a;
document.all.tt1.style.pixelTop=b;
}
</script>
</body>
</html>
Click here to view result of this program in browser Button Button is used to access Button of a form which is neither a reset nor a submit button. When we want to create a button on the web page we use input tag with type as button, we can attach an event with this button, like onclick. A button also should have name for it’s recognition and value which will be displayed on the button so that user can understand that for what purpose this button is. We can understand this all by below given example. Example:
<html>
<head><title> Text Element </title>
</head>
<body bgcolor=green text=”yellow”>
<h4 align=center> Click on Desired Button</h4>
<input type =”button” name=”bb1″ id=”tt1″ value=”I am witness”style=”position:absolute;background:gray;color:black;width:150;”><br><br>
<input type =”Button” name=”b1″ value=”ForeColor” onclick=”fcolo()”>
<input type =”Button” name=”b2″ value=”BackColor” onclick=”bcolo()”>
<input type =”Button” name=”b3″ value=”Size” onclick=”sz()”>
<input type =”Button” name=”b4″ value=”Value” onclick=”values()”>
<input type =”Button” name=”b5″ value=”Position” onclick=”pos()”>
<script language=”JavaScript”>
function bcolo()
{
a=prompt(“Enter Color name , you want “,””)
document.all.tt1.style.background=a;
}
function fcolo()
{
a=prompt(“Enter Color name , you want “,””)
document.all.tt1.style.color=a;
}
function sz()
{
a=prompt(“Enter size , you want “,””)
if(isNaN(parseInt(a)))
{
alert(“Wrong entry”)
}
else
{
document.all.tt1.style.width=a;
}
}
function values()
{
alert(“Value in Text box is “+document.all.tt1.value);
a=prompt(“Enter New Message “,””)
document.all.tt1.value=a;
}
function pos()
{
a=prompt(“Enter X Position , you want “,””)
b=prompt(“Enter Y Position , you want “,””)
document.all.tt1.style.pixelLeft=a;
document.all.tt1.style.pixelTop=b;
}
</script>
</body>
</html>Click here to view result of this program in browser Submit Submit is used to access submit element of a form. When user fed data in the form entries like his name, address, qualification etc. this data has no meaning until it is sent to the server where the program to analyze this data is available and where it will be stored in a database program. Submit button send the data to server. Example:
<html>
<head><title> Text Element </title>
</head>
<body bgcolor=green text=”yellow”>
<h4 align=center> Click on Desired Button</h4>
<form name=”f1″>
<input type =”submit” name=”bb1″ id=”tt1″ style=”position:absolute;background:gray;color:black;width:150;”>
<br><br>
<input type =”Button” name=”b1″ value=”ForeColor” onclick=”fcolo(f1)”>
<input type =”Button” name=”b2″ value=”BackColor” onclick=”bcolo(f1)”>
<input type =”Button” name=”b3″ value=”Size” onclick=”sz(f1)”>
<input type =”Button” name=”b4″ value=”Value” onclick=”values(f1)”>
<input type =”Button” name=”b5″ value=”Position” onclick=”pos(f1)”>
</form>
<script language=”JavaScript”>
function bcolo(f1)
{
a=prompt(“Enter Color name , you want “,””)
f1.elements.bb1.style.background=a;
}
function fcolo()
{
a=prompt(“Enter Color name , you want “,””)
f1.elements.bb1.style.color=a;
}
function sz()
{
a=prompt(“Enter size , you want “,””)
if(isNaN(parseInt(a)))
{
alert(“Wrong entry”)
}
else
{
f1.elements.bb1.style.width=a;
}
}
function values()
{
alert(“Value is “+document.all.tt1.value);
a=prompt(“Enter New Message “,””)
f1.elements.bb1.value=a;
}
function pos()
{
a=prompt(“Enter X Position , you want “,””)
b=prompt(“Enter Y Position , you want “,””)
document.all.tt1.style.pixelLeft=a;
document.all.tt1.style.pixelTop=b;
}
</script>
</body>
</html>
Click here to view result of this program in browser Reset reset is used to access reset element of a form. When a form is filled by the user many times it happens that a user want to fill it again or the same form should appear without sending the previous data fed to server then we use reset button, it will remove all the data fed in the different controls and a fresh form will appear. Example:
<html>
<head><title> Text Element </title>
</head>
<body bgcolor=green text=”yellow”>
<h4 align=center> Click on Desired Button</h4>
<form name=”f1″>
<input type =”reset” name=”bb1″ id=”tt1″ style=”position:absolute;background:gray;color:black;width:150;”><br><br>
<input type =”Button” name=”b1″ value=”ForeColor” onclick=”fcolo(f1)”>
<input type =”Button” name=”b2″ value=”BackColor” onclick=”bcolo(f1)”>
<input type =”Button” name=”b3″ value=”Size” onclick=”sz(f1)”>
<input type =”Button” name=”b4″ value=”Value” onclick=”values(f1)”>
<input type =”Button” name=”b5″ value=”Position” onclick=”pos(f1)”>
</form>
<script language=”JavaScript”>
function bcolo(f1)
{
a=prompt(“Enter Color name , you want “,””)
f1.elements.bb1.style.background=a;
}
function fcolo()
{
a=prompt(“Enter Color name , you want “,””)
f1.elements.bb1.style.color=a;
}
function sz()
{
a=prompt(“Enter size , you want “,””)
if(isNaN(parseInt(a)))
{
alert(“Wrong entry”)
}
else
{
f1.elements.bb1.style.width=a;
}
}
function values()
{
alert(“Value in Text box is “+document.all.tt1.value);
a=prompt(“Enter New Message “,””)
f1.elements.bb1.value=a;
}
function pos()
{
a=prompt(“Enter X Position , you want “,””)
b=prompt(“Enter Y Position , you want “,””)
document.all.tt1.style.pixelLeft=a;
document.all.tt1.style.pixelTop=b;
}
</script>
</body>
</html>Click here to view result of this program in browser Checkbox checkbox is used to access checkbox of a form. When we use input tag with type as checkbox a square box appears with a white area , when user click on that box a tick sign appears and on clicking again on the same box the tick sign disappears. We can program this checkbox using the JavaScript code. Example:
<html>
<head><title> Text Element </title>
</head>
<body bgcolor=green text=”yellow”>
<h4 align=center> Click on Desired Button</h4>
<form name=”f1″>
<input type =”checkbox” name=”bb1″ id=”tt1″ checked style=”position:absolute;background:gray;color:black;width:15;”><br><br>
<input type =”Button” name=”b2″ value=”BackColor” onclick=”bcolo(f1)”>
<input type =”Button” name=”b4″ value=”Value” onclick=”values(f1)”>
<input type =”Button” name=”b5″ value=”Position” onclick=”pos(f1)”>
</form>
<script language=”JavaScript”>
function bcolo(f1)
{
a=prompt(“Enter Color name , you want “,””)
f1.elements.bb1.style.background=a;
}
function fcolo()
{
a=prompt(“Enter Color name , you want “,””)
f1.elements.bb1.style.color=a;
}
function sz()
{
a=prompt(“Enter size , you want “,””)
if(isNaN(parseInt(a)))
{
alert(“Wrong entry”)
}
else
{
f1.elements.bb1.style.width=a;
}
}
function values()
{
alert(“Value is “+document.all.tt1.checked);
}
function pos()
{
a=prompt(“Enter X Position , you want “,””)
b=prompt(“Enter Y Position , you want “,””)
document.all.tt1.style.pixelLeft=a;
document.all.tt1.style.pixelTop=b;
}
</script>
</body>
</html>
Click here to view result of this program in browser Radioradio is used to access radio element of a form. When we use input tag with type as radio a circular white area appears , when we click on it a black dot appears in the white area and when we click on other circular white area the black dot gets transferred from previous circular white area to new one. Radio buttons are used to get a single option from multiple options like sex, either a person can be male or female. So we should use radio in that case. All the related radios created should have same name. Example:
<html>
<head><title> Text Element </title>
</head>
<body bgcolor=green text=”yellow”>
<h4 align=center> Click on Desired Button</h4>
d<form name=”f1″>
<input type =”radio” name=”bb1″ id=”tt1″ style=”background:gray;color:black;width:15;”>
<input type =”radio” name=”bb1″ id=”tt1″ style=”background:gray;color:black;width:15;”>
<br><br>
<br><br>
<input type =”Button” name=”b2″ value=”BackColor” onclick=”bcolo(f1)”>
<input type =”Button” name=”b5″ value=”Total” onclick=”tot(f1)”>
<input type =”Button” name=”b6″ value=”Name” onclick=”nam(f1)”>
</form>
<script language=”JavaScript”>
function bcolo(f1)
{
a=prompt(“Enter Color name , you want “,””)
b=prompt(“Which Radio First or Second “,””)
if (parseInt(b)==1)
{
f1.elements.bb1[0].style.background=a;
}
else
{
f1.elements.bb1[1].style.background=a;
}
}
function tot()
{
alert(“Total number of Radios “+f1.elements.bb1.length);
}
function nam()
{
alert(“Name of Radio “+f1.elements[0].name);
}
</script>
</body>
</html>Click here to view result of this program in browser TextareaText is used to access text area of a form. A text area is created when we usetextarea tag , this control can be used to feed notes , suggestions etc. where a large amount of data from user is required. Example:
<html>
<head><title> Text Element </title>
</head>
<body bgcolor=green text=”yellow”>
<h4 align=center> Click on Desired Button</h4>
<form name=”f1″>
<Textarea rows=5 cols=10 name=”bb1″ id=”tt1″ style=”color:black;background:white;position:absolute;”>
This is text area </textarea>
<br><br><br><br><br><br>
<input type =”Button” name=”b2″ value=”BackColor” onclick=”bcolo()”>
<input type =”Button” name=”b3″ value=”ForeColor” onclick=”fcolo(f1)”>
<input type =”Button” name=”b5″ value=”Font Size” onclick=”fs()”>
<input type =”Button” name=”b6″ value=”Name” onclick=”nam(f1)”>
<input type =”Button” name=”b6″ value=”Data Inside” onclick=”data()”>
</form>
<script language=”JavaScript”>
function bcolo()
{
a=prompt(“Enter Color name , you want “,””)
document.all.tt1.style.background=a;
}
function fcolo(f1)
{
a=prompt(“Enter Color name , you want “,””)
document.all.tt1.style.color=a;
}
function fs()
{
a=prompt(“Enter Font Size , you want “,””)
document.all.tt1.style.fontSize=a;
}
function nam()
{
alert(“Name of TextArea “+f1.elements[0].name);
}
function data()
{
alert(document.all.tt1.value)
}
</script>
</body>
</html>
Click here to view result of this program in browser SelectSelect is used to access select element of a form. Example:
<html>
<head><title> Text Element </title>
</head>
<body bgcolor=green text=”yellow”>
<h4 align=center> Click on Desired Button</h4>
<form name=”f1″>
<input type =”reset” name=”bb1″ id=”tt1″ style=”position:absolute;background:gray;color:black;width:150;”><br><br>
<input type =”Button” name=”b1″ value=”ForeColor” onclick=”fcolo(f1)”>
<input type =”Button” name=”b2″ value=”BackColor” onclick=”bcolo(f1)”>
<input type =”Button” name=”b3″ value=”Size” onclick=”sz(f1)”>
<input type =”Button” name=”b4″ value=”Value” onclick=”values(f1)”>
<input type =”Button” name=”b5″ value=”Position” onclick=”pos(f1)”>
</form>
<script language=”JavaScript”>
function bcolo(f1)
{
a=prompt(“Enter Color name , you want “,””)
f1.elements.bb1.style.background=a;
}
function fcolo()
{
a=prompt(“Enter Color name , you want “,””)
f1.elements.bb1.style.color=a;
}
function sz()
{
a=prompt(“Enter size , you want “,””)
if(isNaN(parseInt(a)))
{
alert(“Wrong entry”)
}
else
{
f1.elements.bb1.style.width=a;
}
}
function values()
{
alert(“Value in Text box is “+document.all.tt1.value);
a=prompt(“Enter New Message “,””)
f1.elements.bb1.value=a;
}
function pos()
{
a=prompt(“Enter X Position , you want “,””)
b=prompt(“Enter Y Position , you want “,””)
document.all.tt1.style.pixelLeft=a;
document.all.tt1.style.pixelTop=b;
}
</script>
</body>
</html>
Click here to view result of this program in browser Select optionSelect option is used to access select options of a form. Example:
<html>
<head><title> Select Element </title>
</head>
<body bgcolor=blue text=”yellow”>
<h4 align=center> Click on Desired Button</h4>
<form name=”f1″>
<select name=”bb1″ id=”tt1″ style=”color:black;background:white;” >
<option > Delhi
<option> UP
<option> Bihar
<option selected> Haryana
<option> Punjab
<option> Maharastra
<option> Uttranchal
</select>
<br><br><br><br><br><br>
<input type =”Button” name=”b2″ value=”BackColor” onclick=”bcolo()”>
<input type =”Button” name=”b3″ value=”ForeColor” onclick=”fcolo(f1)”>
<input type =”Button” name=”b5″ value=”Font Size” onclick=”fs()”>
<input type =”Button” name=”b6″ value=”Name” onclick=”nam(f1)”>
<input type =”Button” name=”b7″ value=”Index Selected” onclick=”ind()”>
</form>
<script language=”JavaScript”>
function bcolo()
{
a=prompt(“Enter Color name , you want “,””)
document.all.tt1.style.background=a;
}
function fcolo(f1)
{
a=prompt(“Enter Color name , you want “,””)
document.all.tt1.style.color=a;
}
function fs()
{
a=prompt(“Enter Font Size , you want “,””)
document.all.tt1.style.fontSize=a;
}
function nam()
{
alert(“Name is : “+f1.elements[0].name);
}
function ind()
{
alert(document.all.tt1.selectedIndex)
}
</script>
</body>
</html>
Click here to view result of this program in browser Select listSelect is used to access select element of a form. A list of selection is used when we want user to select the given options rather then feeding it , it saves the user time and server time also in checking and validating the data, like date of birth of a person, we can feed the dates and make the user to select the desired one from the list rather than typing it from keyboard. Example:
<html>
<head><title> Select Element </title>
</head>
<body bgcolor=blue text=”yellow”>
<h4 align=center> Click on Desired Button</h4>
<form name=”f1″>
<select name=”bb1″ id=”tt1″ size=4 multiple style=”color:black;background:white;” >
<option > Delhi
<option> UP
<option> Bihar
<option selected> Haryana
<option> Punjab
<option> Maharastra
<option> Uttranchal
</select>
<br><br><br><br><br><br>
<input type =”Button” name=”b2″ value=”BackColor” onclick=”bcolo()”>
<input type =”Button” name=”b3″ value=”ForeColor” onclick=”fcolo(f1)”>
<input type =”Button” name=”b5″ value=”Font Size” onclick=”fs()”>
<input type =”Button” name=”b6″ value=”Name” onclick=”nam(f1)”>
</form>
<script language=”JavaScript”>
function bcolo()
{
a=prompt(“Enter Color name , you want “,””)
document.all.tt1.style.background=a;
}
function fcolo(f1)
{
a=prompt(“Enter Color name , you want “,””)
document.all.tt1.style.color=a;
}
function fs()
{
a=prompt(“Enter Font Size , you want “,””)
document.all.tt1.style.fontSize=a;
}
function nam()
{
alert(“Name is : “+f1.elements[0].name);
}
</script>
</body>
</html>
Click here to view result of this program in browser
String Objects Introduction A string is a group of Characters .
M -> is a Character
Moral -> is a group of Characters or contains 5
Characters or is a string. A string is an ObjectA string is an object in Javascript , an object have properties and methods or functions, so a string is having property and methods in javascript. String propertyLength – property returns the no of characters present in string. String Methodsbold() – returns the string formatting to bold.
italics() – returns the string formatting italics.
charAt() – returns the character present in string at given position.
substring() – returns the characters present from given start position to given end position.
toLowerCase() – returns the string converted to lowercase letters.
toUpperCase() – returns the string converted to uppercase letters. Length Length is a property of sring object, using which we can know the number of characters in a string. Example 1:
<html>
<head>
<script>
var a=”Hindustan”
document.write(“Length of Variable a is “+a.length);
</script>
</html>
Output will be:Length of Variable a is 9 Example 2:
<html>
<head>
<script>
var name=”Manmohan Singh”
document.write(“Length of Variable a is “+name.length);
</script>
</html>
Output will be:Length of Variable a is 14 String Methods – bold() Example 1:
<html>
<head>
<script>
var a=”Uttar Pradesh”
document.write(“The Value of Variable a is “+a.bold());
</script>
</html> Output will be :The Value of Variable a is Uttar Pradesh Example 2:
<html>
<head>
<script>
var state=”Bihar”
document.write(“State : “+state.bold());
</script>
</html>
Output will be:State : Bihar String Methods – charAt() Example 1:
<html>
<head>
<script>
var state=”Bihar”
document.write(“<br>character at 0th position is : “+state.charAt(0));
document.write(“<br>character at 1st position is : “+state.charAt(1));
document.write(“<br>character at 2nd position is : “+state.charAt(2));
</script>
</html>
Output will be :character at 0th position is : B
character at 1st position is : i
character at 2nd position is : h Exapmple 2:
<html>
<head>
<script>
var state=”Bihar”
state=state.charAt(2).bold().italics()
document.write(“Character at 2nd position is : “+state);
</script>
</html>
Output will be:Character at 2nd position is : h String Methods – italics() Example 1:
<html>
<head>
<script>
var state=”Bihar”
document.write(“State : “+state.italics());
</script>
</html>
Example 2:
<html>
<head>
<script>
var state=”Bihar”
state=state.bold();
state=state.italics();
document.write(“State : “+state);
</script>
</html>
String Methods – toLowerCase() Example 1:
<html>
<head>
<script>
var state=”HIMANCHAL PRADESH”
state=state.toLowerCase()
document.write(“State : “+state);
</script>
</html>
Output will be:State : himanchal pradesh Example 2:
<html>
<head>
<script>
var state=”HIMANCHAL PRADESH”
state=state.substring(0,state.length).toLowerCase().bold().italics()
document.write(“State : “+state);
</script>
</html>
Output will be :State : himanchal Pradesh String Methods – toUpperCase() Example 1:
<html>
<head>
<script>
var state=”uttranchal”
state=state.toUpperCase()
document.write(“State : “+state);
</script>
</html>
Example 2:
<html>
<head>
<script>
var state=”uttranchal”
state=state.substring(0,state.length).toUpperCase().bold().italics()
document.write(“State : “+state);
</script>
</html>
output will be:State : UTTRANCHAL String Methods – substring() Example 1:
<html>
<head>
<script>
var state=”Bihar”
state=state.substring(0,3)
document.write(“Characters from 0th to 2nd position are : “+state);
</script>
</html>
Output will be:Characters from 0th to 2nd position are : Bih Example 2:
<html>
<head>
<script>
var state=”Bihar”
state=state.substring(0,3).bold().italics()
document.write(“Characters from 0th to 2nd position are : “+state);
</script>
</html>
Output will be:Characters from 0th to 2nd position are : Bih
Math Objects Math object provides many properties and functions which allows to perform complex mathematical work. A Math object is a built in object of JavaScript using which a lot of mathematical calculations can be performed. We can use these mathematical functions to create the animation in JavaScript also Math object propertiesE- this property returns Euler’s Constant (rougly 2.718)PI- this property returns the value of PILength – property returns the no of characters present in string. Math object Methods abs() – this function calculates and returns the absolute value.
ceil() – this function returns the next greater or equal integer..
cos() – this function is used to calculate the cosine number..
sin()– this function is used to calculate the sin() of a number.
random () – this function returns a randomly calculated number between 0 and 1. .
sqrt() – this function calculates and returns the square root of a number.
tan() – this function calculates and returns tangent of a number.
floor() – this function returns next integer lesser than or equal to a number..
pow() – this function returns calculated value of one number for given number of powers. bold() – returns the string formatting to bold.
italics() – returns the string formatting italics.
charAt() – returns the character present in string at given position.
substring() – returns the characters present from given start position to given end position.
toLowerCase() – returns the string converted to lowercase letters.
toUpperCase() – returns the string converted to uppercase letters. Math Object’s abs() function This function calculates and returns the absolute value. Suppose the value of any variable is –345 the absolute value of –345 will be 345. if the value of a variable is 345 then the absolute value of variable will be 345. Example:
<html>
<head>
</head>
<body>
<script>
var a=-45
document.write(“<br> Value of a :”+a)
document.write(“<br> Absolute Value of a :”+Math.abs(a))
</script>
</body>
</html>
click here to view the results of this program in browser Math Object’s ceil() function ceil()- this function returns the next greater or equal integer. If any number is having a decimal value then the value is increased with one else it remains as it is. Fox example a variable is having value 45.26 then the ceiling value of this variable will be 45 but if the variable value is 25 the ceil value will be 25 only. Example:
<html>
<head>
</head>
<body>
<script>
document.write(“<br>Ceiling Number is : “+Math.ceil(45.26))
document.write(“<br>Ceiling Number is : “+Math.ceil(3.22))
document.write(“<br>Ceiling Number is : “+Math.ceil(25))
</script>
</body>
</html>
click here to view the results of this program in browser Math Object’s cos() function cos()- this function is used to calculate the cosine number. Math object contains cos() function which can return the cos value of the angle provided with the cos function. Examples:
<html>
<head>
</head>
<body>
<script>
var a=0
document.write(“<br> Cosine of a is : “+Math.cos(a))
document.write(“<br> Cosine of 90 is : “+Math.cos(90))
document.write(“<br> Cosine of 180 is : “+Math.cos(180))
</script>
</body>
</html>
click here to view the results of this program in browser Math Object’s floor() function floor()- this function returns next integer lesser than or equal to a number. If any value is having the decimal values with it floor function provides the decimal truncated value. Fox example a variable is having value 45.26 the floor value of that variable will be 45 but if the value is 32 then the floor value of variable will be 32 only. Example:
<html>
<head>
</head>
<body>
<script>
document.write(“<br>Floor Number is : “+Math.floor(45.26))
document.write(“<br>Floor Number is : “+Math.floor(3.22))
document.write(“<br>Floor Number is : “+Math.floor(26.23))
</script>
</body>
</html>
click here to view the results of this program in browser Math Object’s pow() function pow()- this function returns calculated value of one number for given number of powers. For example if the parameters passed to the function are 2 , 3 then the answer will be 8 , 2*2*2 = 8 , this function requires the base and the power of the value and returns the calculated value. Example:
<html>
<head>
</head>
<body>
<script>
var a=2
var b=3
document.write(“<br> Value of 2’s power 3 is : “+Math.pow(2,3))
document.write(“<br> Value of 3’s power 4 is : “+Math.pow(3,4))
document.write(“<br> Value of 4’s power 3 is : “+Math.pow(4,3))
</script>
</body>
</html>
click here to view the results of this program in browser Math Object’s random() function random ()- this function returns a randomly calculated number between 0 and 1. The Math object contains a random function which can be used to get the randomly generated value between 0 & 1, The code given below will generated a random value but if refreshed every time it will generate a new randomly generated value. Example:
<html>
<head>
</head>
<body>
<h5> On Refresing screen every time new number between 0 & 1 <br> will be generated by random function</h5>
<script>
document.write(“<br>Random Number is : “+Math.random())
</script>
</body>
</html>
click here to view the results of this program in browser Math Object’s sin() function sin()- this function is used to calculate the sin() of a give number. Math object contains sin function which can be used to get the sin value of any angle given to sin function as parameter. In the below given example we are passing different angle values to sin function which will generate different values Example:
<html>
<head>
</head>
<body>
<script>
var a=0
document.write(“<br> sine of a is : “+Math.sin(a))
document.write(“<br> sine of 45 is : “+Math.sin(45))
document.write(“<br> sine of 60 is : “+Math.sin(60))
document.write(“<br> sine of 90 is : “+Math.sin(90))
</script>
</body>
</html>
click here to view the results of this program in browser Math Object’s sqrt() function sqrt()- this function calculates and returns the square root of a number. Math object has a sqrt function use
Date Object
Date is a built-in object of JavaScript used to deal with date in a JavaScript program. A date is composed of day, month, year, hour, minute, seconds. We can access or change any of these attributes using suitable method. These all methods provide great help to access & maintain the date. The different functions of this object are:
| setDate( ) | This function is used to set desire date to date object |
| getDate( ) | This function is used to get date from date object |
| getDay( ) | This function is used to get day of date from date object |
| getMonth ( ) | This function is used to get Month of date from date object |
| getYear( ) | This function is used to get Year of date from date object |
| SetHour() | This function is used to set Hours to a date object |
| SetMinutes() | This function is used to set Minutes to a date object |
| SetSeconds() | This function is used to set Seconds to a date object |
| getHour() | This function is used to get Hours from a date object |
| getMinutes() | This function is used to get minutes from a date object |
| getseconds() | This function is used to get Seconds from a date object |
Date The different date functions are used in the below given program. Like function to set desire date to date object, function get date from date object, function to get day of date from date object, function to get Month of date from date object, function to get Year of date from date object, function to set Hours to a date object , function to set Minutes to a date object, function to set Seconds to a date object, function to get Hours from a date object, function to get minutes from a date object, function to get Seconds from a date object etc. Example:
<html>
<head><title> setDate & getDate </title>
</head>
<body>
<script>
var birthday = new Date(1985,10,5);
var day= birthday.getDate();
document.write(“<br> Birth Date is : “+day)
birthday.setDate(25);
day= birthday.getDate();
document.write(“<br> After Setting Birth Date to 25 date is : “+day)
</script>
</body>
</html>
Click here to view the result of this program in browser Example:
<html>
<head>
</head>
<body>
<script>
var birthday = new Date(1985,10,5);
var day= birthday.getDay();
var month=birthday.getMonth();
var y = birthday.getYear();
document.write(“<br> Birth Date is : “+day)
document.write(“<br> Birth Month is : “+month)
document.write(“<br> Birth Year is : “+y)
</script>
</body>
</html>
Click here to view the result of this program in browser Example:
<html>
<head><title> setHour & getHour </title>
</head>
<body>
<script>
var calltime = new Date(1985,10,25,5,12,30);
var h= calltime.getHours()
var m = calltime.getMinutes()
var s = calltime.getSeconds()
document.write(“<br>Call Time Hour is : “+h)
document.write(“<br>Call Time Minutes are : “+m)
document.write(“<br>Call Time Seconds are : “+s)
calltime.setHours(9)
calltime.setMinutes(29)
calltime.setSeconds(14)
var h= calltime.getHours()
var m = calltime.getMinutes()
var s = calltime.getSeconds()
document.write(“<br>After Setting Call Time Hour is : “+h)
document.write(“<br>After Setting Call Time Minutes are : “+m)
document.write(“<br>After Setting Call Time Seconds are : “+s)
</script>
</body>
</html>
Click here to view the result of this program in browser
Regular Expressions
Regulars expressions are a sort of shorthand , these are used in pattern matching and substitutions. A regular expression is just sequence or a pattern of characters that is matched against a string of text. Regexps are very powerful and useful tool. They contain a lot of meaning in a short space. Every single character in the regular expression has some meaning. Any regular expression should start with a / (slash) sign and end with a slash (/) sign. The below given example can explain the power of regular expressions. In this example 5 digits are to be entered by user, when user clicks on the button function ff is called and the value entered is checked with the regular expression. In the regular expression is /^\d{5}$/
/ – start of regular expression
^ – to start the matching from first character
\ – indicates digit character
{5} – indicates that 5 , because it is preceded by \d which means digit character , so\d{5} means 5 digit characters
$ – indicates end of the string The meaning of the above given expression is starting from beginning of the string there must be nothing other than 5 digits and There must also be nothing following those 5 digits.
<html>
<head>
</head>
<body>
<script>
function ff(f1)
{
var a=f1.t1.value
var re5=/^\d{5}$/
if (a.search(re5)==-1)
{
alert(‘Enter Valid number’)
}
else
{
alert(‘good try’)
}
}
</script>
<form name=f1>
Enter Five digits code :<input type=”text” name=t1><br>
<input type=”button” value=” hit me to check the number ” onclick=”ff(f1)”>
</form>
</body>
</html>
Click here to view the result of this program in browser
Browser Name
Browser is a program used to view the web pages. Web pages are created using any markup language like html , xml etc. The popular Browser programs are Internet Explorer, Netscape Navigator, Fire Fox etc. Navigator object of JavaScript can avail us the details about our browser, like which browser program we are using , what is the version of the browser we are using etc.
Example
<html>
<head>
</head>
<body bgcolor=”yellow” text=red>
<script type=”text/javascript”>
var browse = navigator.appName
document.write(“<br>My Brower’s Name is :”+browse)
</script>
</body>
</html>
Click here to view the result of this program on browser.
Browser Version
Browser is a program used to view the web pages. Web pages are created using any markup language like html , xml etc. The popular Browser programs are Internet Explorer, Netscape Navigator, Fire Fox etc. Navigator object of JavaScript can avail us the details about our browser, like which browser program we are using , what is the version of the browser we are using etc.
Example
<html>
<head>
</head>
<body bgcolor=”yellow” text=red>
<script type=”text/javascript”>
var ver = navigator.appVersion
document.write(“<br>My Brower’s Version is :”+ver)
</script>
</body>
</html>
Click here to view the result of this program on browser.
Cookies Cookies is a method of storing information locally in browser and sending it to server whenever the pages are requested by the user. When a user requests a page, an HTTP request is sent to the server. The request includes a header that defines several pieces of information, including the page being requested. The server returns aHTTP response that also includes a header. The header contains information about the document being returned. These headers all contains one or more fields of information in a basic format like fieldname : information. Example
<html>
<head>
</head>
<body bgcolor=”yellow” text=red>
Type any desired word in the text box it will be kept as cookie for this document.
<form mehtod=”post()”>
<br> Cookie value : <input type = text size=10 onchange=”ck(this.value);”><br>
<input type=”submit”>
</form>
<script type=”text/javascript”>
function ck(ff)
{
document.cookie=ff
}
var cooky =((document.cookie != “”) && (document.cookie != null))
var cname=((cooky)? document.cookie: “Hello”)
document.write(“<br>Cookies : “+document.cookie);
</script>
</body>
</html>
Click here to view result of this program on Browser
