Professional Documents
Culture Documents
Javascript
Javascript
What is JavaScript ?
Where it is used?
It is used to create interactive websites. It is mainly used for:
Client-side validation
Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog
box and prompt dialog box)
Description
onclick
ondblclick
JAVASCRIPT
onfocus
onblur
onsubmit
onmouseover
onmouseout
onmousedown
onmouseup
onload
onunload
onscroll
onresized
onreset
onkeydown
onkeypress
onkeyup
Javascript Example
Javascript is easy to code. Javascript provides you 3 places to have the code:
1. within body tag,
2. within head tag and
3. external javascript file.
JAVASCRIPT
Lets create the first javascript example.
<html>
<body>
<script type="text/javascript">
document.write("JavaScript is a simple language for javatpoint learners");
</script>
</body>
</html>
The script tag specifies that we are using javascript.
The text/javascript is the content type that provides information to the browser about the
data.
3 Place to put javascript code
1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javascript)
1) Javascript code between the body tag of html
In the above example, we have displayed the dynamic content using javascript. Lets see
the simple example of javascript that displays alert dialog box.
<html>
<body>
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
</body>
JAVASCRIPT
</html>
2) Javascript code between the head tag of html
Lets see the same example of displaying alert dialog box of javascript that is contained
inside the head tag.
In this example, we are creating a function msg(). To create function in javascript, you
need to write function with <function-name> as given below.
To call function, you need to work on event. Here we are using onclick event to call
msg() function.
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to Javascript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
External JavaScript file
We can create the external JavaScript file and embed it in many HTML page.
JAVASCRIPT
It provides code reusability because single JavaScript file can be used in several
html pages
message.js
function msg(){
alert("Hello Javatpoint");
}
index.html
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Javascript Comment
It is used to add information about the code, warnings or suggestions so that the
end user can easily interpret the code.
JAVASCRIPT
Advantages of javascript comments
There are mainly two advantages of javascript comments.
1.Easy to understand It can be used to elaborate the code so that it can be
easy to understand.
2.To avoid the unnecessary code It can also be used to avoid the code being
executed. Sometimes, we add the code to perform some action. But after
sometime, there may be need to disable the code. In such case, it is better to use
comments.
Types of Javascript Comments
There are two types of comments in javascipt.
1. Single-line Comment
2. Multi-line Comment
Single-line Comment
It is represented by double forward slashes (//). It can be used before and after the
statement.
Lets see the example of single-line comment i.e. added before the statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>
Lets see the example of single-line comment i.e. added after the statement.
<script>
var a=10;
var b=20;
JAVASCRIPT
var c=a+b;//It adds values of a and b variable
document.write(c);//prints sum of 10 and 20
</script>
Multi-line Comment
It can be used to add single as well as multi line comments. So, it is more convenient.
It is represented by forward slash with asterisk then asterisk with forward slash. For
example:
/* your code here */
It can be used before, after and middle of the statement.
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
Javascript Variable
A variable in javascript is simply a name of storage location.
There are two types of variables in javascript :
local and global.
There are some rules while declaring a variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. Javascript variables are case sensitive, for example x and X are different variables.
JAVASCRIPT
Example of correct javascript variables
var x = 10;
var _value="sonoo";
Example of incorrect javascript variables
var 123=30;
var *aa=320;
Full example of javascript variable
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
Javascript local variable
A variable which is declared inside block or function is called local variable. It is
accessible within the function or block only. For example:
<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
If(10<13){
JAVASCRIPT
var y=20;//javascript local variable
}
</script>
Javascript global variable
A global variable is accessible from any function. A variable i.e. declared outside the
function or declared with window object is known as global variable. For example:
<script>
var data=200;//global variable
function a(){
document.write(data);
}
function b(){
document.write(data);
}
</script>
Javascript Global Variable
A variable that is declared outside the function or declared with window object is known
as global variable. It can be accessed from any function.
Lets see the simple example of global variable in javascript.
<script>
var value=50;//global variable
function a(){
alert(value);
}
function b(){
JAVASCRIPT
alert(value);
}
</script>
Declaring global variable through window object
The best way to declare global variable in javascript is through the window object. For
example:
window.value=90;
Now it can be declared inside any function and can be accessed from any function. For
example:
function m(){
window.value=100;//declaring global variable by window object
}
function n(){
alert(window.value);//accessing global variable from other function
}
Internals of global variable in javascript
When you declare a variable outside the function, it is added in the window object
internally. You can access it through window object also. For example:
var value=50;
function a(){
alert(window.value);//accessing global variable
}
Javascript Data Types
Javascript provides different data types to hold different types of values. There are two
types of data types in javascript.
1. Primitive data type
JAVASCRIPT
2. Non-primitive (reference) data type
Javascript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by javascript engine.
You need to use var here to specify the data type. It can hold any type of values such as
numbers, strings etc. For example:
var a=40;//holding number
var b="Rahul";//holding string
There are five types of primitive data types in javascript. They are as follows:
1. String
2. Number
3. Boolean
4. Undefined
5. Null
The non-primitive data types are as follows:
1. Object
2. Array
3. RegExp
4. etc.
JavaScript Operators
Operator is a symbol only. JavaScript operators are used to perform operations on
operands. For example:
var sum=10+20;
JAVASCRIPT
Here, + is the arithmetic operator and = is the assignment operator.
Description
Example
Addition
10+20 = 30
Subtraction
20-10 = 10
Multiplication
10*20 = 200
Division
20/10 = 2
Modulus (Remainder)
20%10 = 0
++
Increment
--
Decrement
Comparison Operators
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:
JAVASCRIPT
Operator
Description
Example
==
Is equal to
10==20 = false
===
10==20 = false
!=
Not equal to
10!=20 = true
!==
Not Identical
20!==20 = false
>
Greater than
20>10 = true
>=
20>=10 = true
<
Less than
20<10 = false
<=
20<=10 = false
Bitwise Operators
The bitwise operators perform bitwise operations on operands. The bitwise operators are
as follows:
Operator
Description
Example
&
Bitwise AND
Bitwise OR
Bitwise XOR
Bitwise NOT
(~10) = -10
<<
(10<<2) = 40
>>
(10>>2) = 2
>>>
(10>>>2) = 2
JAVASCRIPT
Logical Operators
The following operators are known as JavaScript logical operators.
Operator
Description
Example
&&
Logical AND
||
Logical OR
Logical Not
!(10==20) = true
Assignment Operators
The following operators are known as JavaScript assignment operators.
Operator
Description
Example
Assign
10+10 = 20
+=
-=
Subtract and
assign
*=
/=
%=
Modulus and
assign
Special Operators
The following operators are known as JavaScript special operators.
Operator
(?:)
Description
Conditional Operator returns value based on the condition. It is like
if-else.
Comma Operator allows multiple expressions to be evaluated as single
statement.
JAVASCRIPT
delete
in
instanceof
new
typeof
void
yield
JavaScript If
The if statement is used in JavaScript to execute the code if condition is true or false.
There are three forms of if statement.
1. If Statement
2. If else statement
3. if else if statement
If statement
It evaluates the content only if expression is true. The signature of JavaScript if statement
is given below.
if(expression){
//content to be evaluated
}
Lets see the simple example of if statement in javascript.
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
JAVASCRIPT
}
</script>
Output of the above example
value of a is greater than 10
If else Statement
It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Lets see the example of if-else statement in JavaScript to find out the even or odd
number.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
JAVASCRIPT
Output of the above example
a is even number
If else if statement
It evaluates the content only if expression is true from several expressions. The signature
of JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
JAVASCRIPT
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
Output of the above example
a is equal to 20
JavaScript Switch
The switch statement is used in JavaScript to execute one code from multiple
expressions.
The signature of JavaScript switch statement is given below.
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
JAVASCRIPT
}
Lets see the simple example of switch statement in javascript.
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Output of the above example
B Grade
Lets understand the behavior of switch statement in JavaScript.
<script>
var grade='B';
JAVASCRIPT
var result;
switch(grade){
case 'A':
result+=" A Grade";
case 'B':
result+=" B Grade";
case 'C':
result+=" C Grade";
default:
result+=" No Grade";
}
document.write(result);
</script>
Output of the above example
B Grade B Grade C Grade No Grade
JavaScript Loop
The loops are used to iterate the piece of code. They makes the code compact. It is
mostly used in array.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
JAVASCRIPT
For loop
The JavaScript for loop iterates the elements for the fixed number of times mostly. The
syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}
Lets see the simple example of for loop in javascript.
<script>
for (i=1; i<=5; i++)
{
document.write(i + "
")
}
</script>
Output of the above example
1
2
3
4
5
while loop
The JavaScript while loop iterates the elements for the infinite number of times mostly.
The syntax of while loop is given below.
while (condition)
{
code to be executed
JAVASCRIPT
}
Lets see the simple example of while loop in javascript.
<script>
var i=11;
while (i<=15)
{
document.write(i + "
");
i++;
}
</script>
Output of the above example
11
12
13
14
15
do while loop
The JavaScript do while loop iterates the elements for the infinite number of times mostly
like while loop.
But, code is executed once always whether condition is true or false. The syntax of do
while loop is given below.
do{
code to be executed
}while (condition);
Lets see the simple example of do while loop in javascript.
<script>
JAVASCRIPT
var i=21;
do{
document.write(i + "
");
i++;
}while (i<=25);
</script>
Output of the above example
21
22
23
24
25
for..in loop
The JavaScript for...in statement loops through the properties of an object.
Syntax
for (variable in object)
{
code to be executed
}
Note: The block of code inside of the for...in loop will be executed once for each
property.
Example
Looping through the properties of an object:
<!DOCTYPE html>
<html>
<body>
JAVASCRIPT
<p>Click the button to loop through the properties of an object named "person".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var txt="";
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
document.getElementById("demo").innerHTML=txt;
}
</script></body></html>
Output :
JohnDoe25
JavaScript Function
The functions in JavaScript are used to perform operations. We can call function many
times to reuse the code.
Advantage of function
There are mainly two advantages of functions.
1. Code Reusability We can call a function several times so it save coding.
2. Less Coding It makes our program compact. We dont need to write many
lines of code each time to perform a common task.
JAVASCRIPT
Function Arguments
We can call function by passing arguments. Lets see the example of function that has
one argument.
<script>
function getcube(number){
alert(number*number*number);
}
</script>
JAVASCRIPT
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
Output of the above example
hello javatpoint! How r u?
JavaScript Objects
An object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create class to get
the object. But, we direct create objects.
Everything is an Object
In JavaScript almost everything is an object. Even primitive datatypes (except null and
undefined) can be treated as objects.
1. Booleans can be objects or primitive data treated as objects
2. Numbers can be objects or primitive data treated as objects
3. Strings are also objects or primitive data treated as objects
4. Dates are always objects
5. Maths and Regular Expressions are always objects
6. Arrays are always objects
JAVASCRIPT
7. Even functions are always objects
Creating Objects in JavaScript
There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1) Creating Object by object literal
The syntax of creating object using object literal is given below:
object = {property1:value1,property2:value2..... propertyN : valueN}
As you can see, property and value is separated by : (colon).
Lets see the simple example of creating object in JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output of the above example
102 Shyam Kumar 40000
2) By creating instance of Object directly
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Lets see the example of creating object directly.
<script>
JAVASCRIPT
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output of the above example
101 Ravi 50000
3) By using an object constructor
Here, you need to create function with arguments. Each argument value can be assigned
in the current object by using this keyword.
The this keyword refers to the current object.
The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
Output of the above example
103 Vimal Jaiswal 30000
JAVASCRIPT
Defining method in JavaScript Object
We can define method in JavaScript object. But before defining method, we need to add
property in the function with same name as method.
The example of defining method in object is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=change;
function change(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
Output of the above example
103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000
JavaScript Number Object
JAVASCRIPT
JavaScript Numbers
JavaScript numbers can be written with, or without decimals:
Example
var pi=3.14;
var x=34;
Extra large or extra small numbers can be written with scientific (exponent) notation:
Example
var y=123e5;
// 12300000
var z=123e-5;
// 0.00123
JAVASCRIPT
Example
var x = 123;
var y = new Number(123);
(x === y) // is false because x is a number and y is an object.
Number Methods
toExponential()
toFixed()
toPrecision()
toString()
valueOf()
The indexOf() method returns the position (as a number) of the first found
occurrence of a specified text inside a string:
Example
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome"); result is 14
The lastIndexOf() method starts searching at the end of the string instead of at the
beginning.
Example
var str="Hello world, welcome to the welcome universe.";
var n=str.lastIndexOf("welcome"); result is 29
Matching Content
The match() method can be used to search for a matching content in a string:
JAVASCRIPT
Example
var str="Hello world!";
document.write(str.match("world") + "<br>"); -> world
document.write(str.match("World") + "<br>"); null
document.write(str.match("world!")); world!
Replacing Content
The replace() method replaces a specified value with another value in a string.
Example
str="Please visit Microsoft!"
var n=str.replace("Microsoft","W3Schools"); Please visit W3Schools
Convert a String to an Array
A string is converted to an array with the built in method string.split():
Example
txt="a,b,c,d,e"
// String
txt.split(",");
// Split on commas
txt.split(" ");
// Split on spaces
txt.split("|");
// Split on pipe
<script>
function myFunction()
{
var str="a,b,c,d,e,f";
var n=str.split(",");
for (index in n) {
document.writeln(n[index]); output a b c d e f
}
}
</script>
JAVASCRIPT
Strings Can be Strings or Objects
JavaScript strings can be primitive values created from literals, like var x = "John";
JavaScript strings can also be objects created with the new keyword, like var y = new
String("John");
Example
var x = "John";
var y = new String("John");
typeof(x) // returns String
typeof(y) // returns Object
Example
var x = "John";
var y = new String("John");
(x === y) // is false because x is a string and y is an object.
String Properties and Methods
Properties:
1. length
2. prototype
3. constructor
Methods:
1. charAt()
2. charCodeAt()
3. concat()
4. fromCharCode()
5. indexOf()
6. lastIndexOf()
7. localeCompare()
8. match()
9. replace()
10.search()
11.slice()
JAVASCRIPT
12.split()
13.substr()
14.substring()
15.toLowerCase()
16.toUpperCase()
17.toString()
18.trim()
19.valueOf()
JavaScript Date Object
JAVASCRIPT
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
Note: If adding five days to a date shifts the month or year, the changes are handled
automatically by the Date object itself!
Compare Two Dates
The following example compares today's date with the 14th January 2100:
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();
if (x>today)
{
alert("Today is before 14th January 2100");
}
else
{
alert("Today is after 14th January 2100");
}
JavaScript Boolean Object
-0
null
""
JAVASCRIPT
false
undefined
NaN
the object is set to false. For any other value it is set to true (even with the string "false")!
JavaScript Math Object
When you search in a text, you can use a pattern to describe what you are
searching for.
A more complicated pattern can consist of more characters, and can be used for
parsing, format checking, substitution and more.
Syntax
var patt=new RegExp(pattern,modifiers);
or more simply:
var patt=/pattern/modifiers;
JAVASCRIPT
RegExp Modifiers
Modifiers are used to perform case-insensitive and global searches.
The g modifier is used to perform a global match (find all matches rather than
stopping after the first match).
Example 1
Do a case-insensitive search for "w3schools" in a string:
var str="Visit W3Schools";
var patt1=/w3schools/i;
Example 3
Do a global, case-insensitive search for "is":
var str="Is this all there is?";
var patt1=/is/gi;
The marked text below shows where the expression gets a match:
Is this all there is?
test()
The test() method searches a string for a specified value, and returns true or false,
depending on the result.
The following example searches a string for the character "e":
Example
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be:
true
exec()
The exec() method searches a string for a specified value, and returns the text of the
found value. If no match is found, it returns null.
JAVASCRIPT
The following example searches a string for the character "e":
Example 1
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be:
e
JavaScript Array
In JavaScript, array is an object that represents a collection of similar types of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) By array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Lets see the simple example of creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
The .length property returns the length of an array.
JAVASCRIPT
Output of the above example
Sonoo
Vimal
Ratan
2) By creating instance of Array directly (using new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Lets see the example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output of the above example
Arun
Varun
John
JAVASCRIPT
3) By using an Array constructor (using new keyword)
Here, you need to create instance of array by passing arguments in constructor so that
we don't have to provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output of the above example
Jai
Vijay
Smith
You Can Have Different Objects in One Array
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have
arrays in an Array:
myArray[0]=Date.now;
myArray[1]=myFunction;
myArray[2]=myCars;
Array Methods and Properties
The Array object has predefined properties and methods:
var x=myCars.length
JAVASCRIPT
var y=myCars.indexOf("Volvo")
JAVASCRIPT
</body>
</html>
Output :
BANANA,ORANGE,APPLE,MANGO
Browser Object Model - BOM
The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of
window by specifying window or directly.
Even the document object (of the HTML DOM) is a property of the window object
For example:
window.alert("hello javatpoint");
is same as:
alert("hello javatpoint");
You can use a lot of properties (other objects) defined underneath the window object
like document, history, screen, navigator, location, innerHeight, innerWidth,
Window Object
Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.
JAVASCRIPT
Methods of window object
The important methods of window object are as follows:
Method
alert()
confirm()
Description
displays the alert box containing message with ok button.
displays the confirm dialog box containing message with ok and cancel
button.
prompt()
open()
close()
setTimeout()
performs action after specified time like calling function, evaluating expressions
etc.
moveTo()
resizeTo()
JAVASCRIPT
<input type="button" value="click" onclick="msg()"/>
</body>
</html>
Example of confirm() in javascript
It displays the confirm dialog box. It has message with ok and cancel buttons.
<html>
<head>
<script type="text/javascript">
function msg(){
var v= confirm("Are u sure?");
if(v==true){
alert("ok");
}
else{
alert("cancel");
}}
</script></head><body>
<input type="button" value="delete record" onclick="msg()"/>
</body></html>
Example of prompt() in javascript
It displays prompt dialog box for input. It has message and textfield.
<html><head>
<script type="text/javascript">
function msg(){
var v= prompt("Who are you?");
JAVASCRIPT
alert("I am "+v);
}
</script></head><body>
<input type="button" value="click" onclick="msg()"/>
</body></html>
Example of open() in javascript
It displays the content in a new window.
<html><head>
<script type="text/javascript">
function msg(){
open("http://www.javatpoint.com");
}
</script></head><body>
<input type="button" value="javatpoint" onclick="msg()"/>
</body></html>
Example of setTimeout() in javascript
It performs its task after the given milliseconds.
<html><head>
<script type="text/javascript">
function msg(){
setTimeout(
function(){
alert("Welcome to Javatpoint after 2 seconds")
},2000);
JAVASCRIPT
}
</script></head><body>
<input type="button" value="click" onclick="msg()"/>
</body></html>
Window Size
Three different properties can be used to determine the size of the browser window (the
browser viewport, NOT including toolbars and scrollbars).
For Internet Explorer, Chrome, Firefox, Opera, and Safari:
document.documentElement.clientHeight
document.documentElement.clientWidth
document.body.clientHeight
document.body.clientWidth
or
Window Screen
JAVASCRIPT
Some properties:
JAVASCRIPT
JAVASCRIPT
window.location ="http://www.w3schools.com"
}
</script></head><body>
<input type="button" value="Load new document" onclick="newDoc()">
</body></html>
Window History
Window History
To protect the privacy of the users, there are limitations to how JavaScript can
access this object.
Some methods:
JAVASCRIPT
Window History Forward
The history forward() method loads the next URL in the history list.
This is the same as clicking the Forward button in the browser.
Example
Create a forward button on a page:
<html><head><script>
function goForward()
{
window.history.forward()
}
</script></head><body>
<input type="button" value="Forward" onclick="goForward()">
</body></html>
Window Navigator
Popup Boxes
JavaScript has three kind of popup boxes:
Alert box,
Prompt box.
Timing Events
With JavaScript, it is possible to execute some code at specified time-intervals. This is
called timing events.
It's very easy to time events in JavaScript. The two key methods that are used are:
setInterval() - executes a function, over and over again, at specified time intervals
Note: The setInterval() and setTimeout() are both methods of the HTML DOM Window
object.
JAVASCRIPT
The setInterval() Method
The setInterval() method will wait a specified number of milliseconds, and then execute a
specified function, and it will continue to execute the function, once at every given
time-interval.
Syntax
window.setInterval("javascript function",milliseconds);
The window.setInterval() method can be written without the window prefix.
The first parameter of setInterval() should be a function.
The second parameter indicates the length of the time-intervals between each execution.
Note: There are 1000 milliseconds in one second.
Example
Alert "hello" every 3 seconds:
setInterval(function(){alert("Hello")},3000);
The setTimeout() Method
Syntax
window.setTimeout("javascript function",milliseconds);
The setTimeout() method will wait the specified number of milliseconds, and then
execute the specified function.
The second parameter indicates how many milliseconds, from now, you want to
execute the first parameter.
Example
Wait 3 seconds, then alert "Hello":
setTimeout(function(){alert("Hello")},3000);
JAVASCRIPT
How to Stop the Execution?
The clearTimeout() method is used to stop the execution of the function specified
in the setTimeout() method.
Syntax
window.clearTimeout(timeoutVariable)
To be able to use the clearTimeout() method, you must use a global variable when
creating the timeout method:
myVar=setTimeout("javascript function",milliseconds);
Then, if the function has not already been executed, you will be able to stop the
execution by calling the clearTimeout() method.
Example
Same example as above, but we have added a "Stop the alert" button:
var myVar;
function myFunction()
{
myVar=setTimeout(function(){alert("Hello")},3000);
}
function myStopFunction()
{
clearTimeout(myVar);
}
Cookies
What is a Cookie?
Each time the same computer requests a page with a browser, it will send the
cookie too. With JavaScript, you can both create and retrieve cookie values.
JAVASCRIPT
Examples of cookies:
Name cookie - The first time a visitor arrives to your web page, he or she must fill
in her/his name. The name is then stored in a cookie. Next time the visitor arrives
at your page, he or she could get a welcome message like "Welcome John Doe!"
The name is retrieved from the stored cookie
Date cookie - The first time a visitor arrives to your web page, the current date is
stored in a cookie. Next time the visitor arrives at your page, he or she could get
a message like "Your last visit was on Tuesday August 11, 2005!" The date is
retrieved from the stored cookie
JAVASCRIPT
The important methods of document object are as follows:
Method
write("string")
writeln("string")
getElementById()
getElementsByName()
getElementsByTagName()
getElementsByClassName()
Description
writes the given string on the document.
writes the given string on the document with
newline character at the end.
returns the element having the given id value.
returns all the elements having the given name
value.
returns all the elements having the given tag name.
returns all the elements having the given class
name.
Here, document is the root element that represents the html document.
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with welcome
message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
JAVASCRIPT
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
Javascript - document.getElementById() method
Let's see the simple example of document.getElementById() method that prints cube of
the given number.
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script> <form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Javascript - document.getElementsByName() method
The document.getElementsByName() method returns all the element of specified name.
The syntax of the getElementsByName() method is given below:
document.getElementsByName("name")
Here, name is required.
JAVASCRIPT
Example of document.getElementsByName() method
In this example, we going to count total number of genders. Here, we are using
getElementsByName() method to get all the genders.
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script><form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Genders">
</form>
Javascript - document.getElementsByTagName() method
JAVASCRIPT
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by getElementByTagName()
method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
Output of the above example
This is a pragraph
Here we are going to count total number of paragraphs by getElementByTagName()
method.
Let's see the simple example
Another example of document.getElementsByTagName() method
In this example, we going to count total number of h2 and h3 tags used in the document.
<script type="text/javascript">
function counth2(){
var totalh2=document.getElementsByTagName("h2");
alert("total h2 tags are: "+totalh2.length);
}
function counth3(){
var totalh3=document.getElementsByTagName("h3");
alert("total h3 tags are: "+totalh3.length);
}
</script>
JAVASCRIPT
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>
Output of the above example
This is h2 tag
This is h2 tag
This is h3 tag
This is h3 tag
This is h3 tag
Javascript - innerHTML
The innerHTML property can be used to write the dynamic html on the html
document.
It is used mostly in the web pages to generate the dynamic html such as
registration form, comment form, links etc.
JAVASCRIPT
cols='80'></textarea><br><input type='submit' value='comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
Javascript - innerText
The innerText property can be used to write the dynamic text on the html
document. Here, text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as writing
the validation message, password strength etc.
JAVASCRIPT
document.getElementById('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
Javascript Form Validation
It is important to validate the form submitted by the user because it can have
inappropriate values. So validation is must.
The javascript provides you the facility the validate the form on the client side so
processing will be fast than server-side validation. So, most of the web
developers prefer javascript validation.
Through javascript, we can validate name, password, email, date, mobile number etc
fields.
Example of javascript form validation
In this example, we are going to validate the name and password. The name cant be
empty and password cant be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to the
next page until given values are correct.
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
JAVASCRIPT
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
Javascript email validation
We can validate the email by the help of javascript.
There are many criteria that need to be follow to validate the email id such as:
JAVASCRIPT
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script><body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>