Java Script
Java Script
What is JavaScript?
• JavaScript was designed to add interactivity to HTML pages
• JavaScript is a scripting language(a scripting language is a lightweight
programming language)
• A JavaScript consists of lines of executable computer code
• A JavaScript is usually embedded directly into HTML pages
• JavaScript is an interpreted language (means that scripts execute without
preliminary compilation)
• Everyone can use JavaScript without purchasing a license
</script>
• The word document, write is a standard JavaScript command for writing output to
a page
• By entering the document, write command between the <script type=”javascript
“> and </script> tags, the browser will recognize it as a JavaScript command and
execute the code line.
For E.g.:
<html>
<body>
<script type=”javascript”>
document.write (”Hello world!”);
</script>
</body>
</html>
Note: If we had not entered the <script> tag, the browser would have treated the
document.write (”Hello world!”) as a pure text, and just write the entire line on the
page
JavaScript in a page will be executed immediately while the page loads into
the browser. This is not always what we want. Sometimes we want to execute a
script when a page loads, other times when a user triggers an event.
<html>
<head>
<script type=”JavaScript “>
………
</script>
</head>
</html>
Variables:
• A variable is a “container” for information you want to store.
• A variable’s script value can change during the script. You can refer to a
variable by name to see its value or to change its value.
• Declare a variable:
You can create a variable with var statement:
var strname = some value
You can also create a variable without the var statement:
strname = some value
• Lifetime of Variables
When you declare a variable within a function, the variable can
only be access within that function. When you exit the function,
the variable is destroyed. The variables are called local variables.
You can have local variables with the same name in different
functions, because each is recognized only by the function in
which it is declared
If you declare a variable outside a function, all the functions on
your page can access it. The lifetime of these variables starts when
they are declared, and ends when the page is closed
JavaScript Operators
• Arithmetic operators
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x–y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
• Logical operators
Operator Description EXAMPLE
• Conditional operator
Java Script also contains a conditional operator that assigns a value to a
variable based on a some condition
SYNTAX:
variablename=(condition)?value1 value2
EXAMPLE
greeting=(visitor= =“PRES”)?”Dear President” “Dear”
If the variable visitor is equal to PRES, then put the string “Dear
President” in the variable named greeting.
If the variable visitor is equal to PRES, then put the string “Dear” in the
variable named greeting.
Conditional Statements
Very often when you write code, you want to perform different actions for
different. You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
• if statement – use this statement if you want to execute some code only
if a specified condition is true.
• if…else statement – use this statement if you want to execute some
code if the condition is true and another code if the condition is false.
• if…else if…else statement – use this statement if you want to select
one of many blocks of code to be executed.
• switch statement – use this statement if you want to select one of many
blocks of code to be executed.
• If Statement
• You should use the if statement if you want to execute some code only
if a specified condition is true.
• Code is executed only if specified condition is true.
SYNTAX:
if (condition)
{
Code to be executed if condition is true
}
EXAMPLE:
<script type = “text / javascript”>
var a=10
var c=20
if a>b
{
document.write(“<b> A is greater </b>”)
}
Note: if is written in lower case letters. Using uppercase letters will
generate a Javascript error.
• If…else Statement:
• If you want to execute some code if the condition is true and another
code if the condition is false, use the if…else statement.
SYNTAX:
if (condition)
{
Code to be executed if condition is true
}
else
{
Code to be executed if condition is not true
}
EXAMPLE:
<script type = “javascript”>
var a=10;
var b=20;
if (a>b)
{
document.write(“ A is greater than B”);
}
else
{
document.write(“ B is greater than A”);
}
</script>
SYNTAX:
If(condition1)
{
code to be executed if condition1 is true
}
else if(condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true
}
EXAMPLE
<script type=”text/javascript”>
var d = new Date()
var time = d.grtHours();
if(time<10)
{
document.write(“<b>GoodMorning</b>”);
}
else if(time>10&&time<16)
{
document.write(“<b>Good Day</b>”);
}
else
{
document.write(“<b>Hello World </b>”)
}
</script>
Switch Statement:
• You should use the switch statement if you want to select one of many
blocks of code to be executed.
• First we have a single expression and (most often a variable) that is
evaluated once.
• The value of the expression is then compared with the values for each case
in the structure. If there is a match, the block of the code associated with
that case is executed.
• Use break to prevent the code from running into the next case
automatically.
• If expression is not matched with any case then default block is executed.
Switch Statement
SYNTAX:
Switch(n)
{
case1:
execute code block1
break;
case2:
execute code block2
break;
default:
code is to be executed is n is different from case1 and case2
}
EXAMPLE
<script type=”text/javascript”>
//you will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date()
the Day=d.getDay()
switch(theDay)
{
case5:
document.write(“Finally Friday”);
case6:
document.write(“Super Sunday”);
case0:
document.write(“Sleepy Sunday”);
default:
document.write(“I am looking forward to this weekend”);
}
</script>
JavaScript Loops:
Very often when you write code, you want the same block of code to run
over and over again in a row. Instead of adding several almost equal lines in a script
we can use loop to perform a task like this.
In a JavaScript there are two different kinds of loops:
• for - loops through a block of code a specified number of times
• while – loops through a block of code while a specified condition
is true.
• The for loop has three section initialize, condition & expression.
• Initialize section executed first and that is evaluated once.
• Condition section check the condition if condition is true then code to be
executed else executed the next statement after for loop.
• Expression section has any type of expression that change the conditional
variable value.
EXAMPLE:
<html>
<body>
<script type=”text/javascript”>
var i=0;
for(i=0;i<=5;i++)
{
document.write(“The number is” + i);
document.write(“<br>”);
}
</script>
</body>
</html>
OUTPUT:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
EXPLANATION:
The EXAMPLE below defines a loop that starts with i=0.The loop will continue
to run as long as i is less than or equal to 5 i will increase by 1 each time the loop
runs.
SYNTAX:
While(condition)
{
code to be executed
}
EXAMPLE:
<html>
<body>
<script type=”text/javascript”>
var i=0;
while(i<=5)
{
document.write(“The number is” + i)
document.write(“<br>”)
i=i+1
}
</script>
</body>
RESULT:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
EXPLANATION:
The EXAMPLE below defines a loop that starts with i=0.The loop will continue
to run as long as i is less than or equal to 5.i will increase by 1 each time the loop
runs.
EXAMPLE:
<html>
<body>
<script type=”text/javascript”>
var i=5
do
{
document.write(“The number is “ +i)
document.write(“<br>”)
i=i+1
}
While(i<0)
</script>
</body>
</html>
RESULT:
The number is 5
EXAMPLE:
<html>
<body>
<script type=”text/javascript”>
var i=0
for(i=0;i<=10;i++)
{
if(i= =3){break}
document.write(“The number is” +i)
document.write(“<br>”)
}
</script>
</body>
</html>
RESULT:
The number is 0
The number is 1
The number is 2
• Continue
The continue command will break the current loop and continue with the
next value.
EXAMPLE:
<html>
<body>
<script type=”text/javascript”>
var i=0
for(i=0;i<=5;i++)
{
if( i= =3){continue}
document.write(“The number is” +i)
document.write(“<br>”)
}
</script>
</body>
</html>
RESULT:
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
Assignment-3 To study about different dialog boxes in Java-script and
User-defined functions.
Dialog Boxes
JavaScript provides the ability to pickup user input or display small
amount of text to the user by using dialog boxes appear as separate
windows and their content depends on the information provided by the
user.
There are three types of dialog boxes provided by JavaScript
Alert dialog box, Prompt dialog box,Confirm dialog box
SYNTAX:
alert( “messege”)
The alert dialog box display the string passed to the alert( )
method,as well as ok button.
The JavaScript and the HTML program,in which this code snippet
is
held ,will not continue processing until the OK button press.
The alert dialog box can be used to display a messege or display
some
some information
For instance
• A messege is display when user input invalid information.
• An invalid RESULT: is the OUTPUT: of a calculation.
• A warning that a service is not available.
EXAMPLE:
<html>
<body>
<script language=javascript>
alert( “Welcome to RPBC”);
document.write(“<IMG src= piot.jpg>”);
</script>
</body>
</html>
• Confirm Box
A confirm box is often used if you want the user to verify or accept
something
A confirm box display the predefine messege And OK & Cancle Button
When a confirm box pops up, the user will have to click either “OK” or
“Cancel”,the box returns false.
SYNTAX:
Confirm(“sometext”);
EXAMPLE:
<html>
<body>
< script language =javascript >
If(confirm(“Are You Ready?”))
{ document.write(“Ok Button Press”); }
else
{ document.write(“Cancle Button Press”); }
</script>
</body>
</html>
• Prompt Box
• A prompt box is often used if you want the user to input a value
before
• entering a page.
• A prompt box display a predefine messege, a textbox for user input
and
• display OK & Cancel Button.
• When a prompt box pops up,the user will have to click either
“OK” or
• “Cancel”to proceed after entering an input value.
• If the user clicks “OK” the box returns the input value.If the user
clicks
• “Cancle” the box return null.
SYNTAX:
prompt(“sometext”,defaultvalue”);
EXAMPLE:
<html>
<body>
<script language=”javascript>
document.write(“Welcome to RPBC <br>”);
document.write(prompt(“Enter Name”,”Anil”));
</script>
</body>
</html>
SYNTAX:
Function function_name([parameter list])
{
Block of JavaScript code
{ return expression}
}
EXAMPLE:
<html>
<head>
<script type=”text/javascript”>
function display message( )
{
alert( “Hello World!”)
}
</script>
</head>
<body>
<form>
<input type=”button” value=”Click me!”
onclick=”display message( )”>
</form>
</body>
</html>
EXPLANATION:
If the line alert (“Hello World!”),in the EXAMPLE above had not been
written within a function, it would have been executed as soon as the line was
loaded. Now, the script is not executed before the user hits the button. We have
added an ON click at will execute the function display message( )when the button
is checked.
Assignment-4 To study about object and its properties and methods and
study java-script arrays.
JavaScript Objects:
• An OOP language allows you to define your own objects and make
your own variable types.
• Properties
<script type=”text/javascript”>
document.write(txt.length)
</script>
OUTPUT:
12
• Methods
<script type=”text/javascript”>
document.write(str.toUpperCase())
</script>
OUTPUT:
HELLO WORLD!
JavaScript Arrays
The Array object is used to store a set of values in a single variable name.
We define an Array object with the new keyword.
The code lines defines an Array object called my Array
var my Array=new Array( )
There are two ways of adding values to an array(you can add as many
value as you need to define as many variables you require)
1:
var mycars=new Array( )
mycars[0]=”City Honda”
mycars[1]=”Volvo”
mycars[2]=”BMW”
you could also pass an integer argument to control the array’s size:
2:
var mycars=new Array(“City Honda”,”Volvo”,”BMW”)
• Accessing Arrays
You can refer to particular element in an array of returning to
the name of the array and the index number.
The index number starts at 0.
The following code line:
Document.write(mycars[2])
RESULT:
BMW
RESULT:
Opel
Array object
SYNTAX:
arrayObject.concat(arrayX,arrayX,…..,arrayX)
Parameter Description
arrayX Required. One or more array objects to be
joined to an arrays.
EXAMPLE:
<script type=”text/javascript”>
Var arr = Array(3)
arr[0] = “Jani”;
arr[1] = “Tove”;
arr[2] = “hege”;
var arr2 = new Array(3)
arr[0] = ”john”;
arr[1] = “Andy”;
arr[2] = “Wendy”;
document.write(arr.concat(arr2));
</script>
OUTPUT:
Jani,Tove,hege,John,Andy,Wendy
• join()
• The join() method is used to put all the elements of an array into a string.
• The elements will be separated by a specified separator.
• Comma is the default separator for the join() method.
SYNTAX:
arrayObject.join(seperator)
Parameter Description
separator Optional. Specified the separator to be used.
EXAMPLE:
<script type=”text/javascript”>
var arr = new Arry(3)
arr[0] = “Jani”;
arr[1] = “Hege”;
arr[2] = “Stabe”;
document.write(arr.join() + “<br/>”);
document.write(arr.join(“.”));
</script>
OUTPUT:
Jani,Hege,Stale
Jani,Hege,Stale
• Pop()
• The pop() method is used to remove and return the last element of an array.
• This method changes the length of the array.
• To remove and return the first element of an array, use the shift() method.
SYNTAX:
arrayObject.pop()
EXAMPLE:
<script type=”text/JavaScript”>
var arr=new array[3];
arr[0]=”jani”;
arr[1]=”Hege”;
arr[2]=”Stale”;
document.write(arr + “<br/>”);
document.write(arr.pop()+ “<br/>”);
document.write(arr);
</script>
OUTPUT:
Jani,Hege,Stale
Stale
Jani,Hege
• Push ()
SYNTAX:
AraayObject.push(newelement1, newelement2,……, newelementX)
Parameter Description
newelement1 Required,The first element to add to the array.
newelement2 Optional,The second element to add to the array.
newelement1X Optional,Several elements may be added
EXAMPLE:
<script type=”text/javascript”>
var arr=new array[3];
arr[0]=”jani”;
arr[1]=”Hege”;
arr[2]=”Stale”;
document.write(arr + “<br/>”);
document.write(arr.push(“Kai Jim”)+ “<br/>”);
document.write(arr);
</script>
OUTPUT:
Jani,Hege,Stale
4
Jani,Hege,Stale,Kai Jim
• reverse()
• The reverse() method is used to reverse the order of the elements in an array.
• The reverse() method changes the original array.
SYNTAX:
arrayObject.reverse()
EXAMPLE:
<script type=”text/Javascript”>
var arr=new array[3];
arr[0]=”jani”;
arr[1]=”Hege”;
arr[2]=”Stale”;
document.write(arr + “<br/>”);
document.write(arr.reverse);
</script>
OUTPUT:
Jani,Hege,Stale
Stale,Hege,Jani
• Shift()
The shift() method is used to remove and return the first element of
an array.
This method changes the length of the array.
To remove and retrn the last element of an array, use the pop()
method.
SYNTAX:
arrayObject.shift()
EXAMPLE:
<script type=”text/Javascript”>
var arr=new array[3];
arr[0]=”jani”;
arr[1]=”Hege”;
arr[2]=”Stale”;
document.write(arr + “<br/>”);
document.write(arr.shift()+ “<br/>”);
document.write(arr);
</script>
OUTPUT:
Jani,Hege,Stale
Jani
Hege,Stale
• Sort()
The sort() method is used the element of an array.
The sort() method will sort the element alphabetically by
default.However,this means that numbers will not be sorted correctly(40 comes
before 5).To sort numbers,you must create a function that compare numbers.
After using the sort() method,the array is changed.
SYNTAX:
arrayObject.sort(sortby)
Parameter Description
Sortby Optional,specifiesthe sort order.Must be a function.
EXAMPLE:
<script type=”text/Javascript”>
var arr=new array[6];
arr[0]=”Jani”;
arr[1]=”Hege”;
arr[2]=”Stale”;
arr[3]=”Kai Jim”;
arr[4]=”Borge”;
arr[5]=”Tove”;
document.write(arr + “<br/>”);
document.write(arr sort());
</script>
OUTPUT:
Jani,Hege,Stale,Kai Jim,Borge,Tove
,Borge,Hege,Jani,Kai Jim,Stale,Tove
SYNTAX:
arrayObject.length
EXAMPLE:
<script type=”text/Javascript”>
var arr=new array(3);
arr[0]=”John”;
arr[1]=”Andy”;
arr[2]=”Wendy”;
document.write(“Original length:” + arr.length);
document.write(“<br/>”);
arr.length=5;
document.write(“New length:” + arr.length);
</script>
OUTPUT:
Original.length:3
New length:5
• big ( )
SYNTAX:
stringObject.big( )
• small ( )
SYNTAX:
stringObject.small( )
• blink ( )
• The blink( ) method is used to display a blinking
string.
SYNTAX:
stringObject.blink( )
• bold ( )
• The bold( ) method is used to display a string in a
bold.
SYNTAX:
stringObject.bold( )
• italics ( )
SYNTAX:
stringObject.italics( )
• strike ( )
SYNTAX:
stringObject.strike( )
• sub ( )
SYNTAX:
stringObject.sub( )
• sup ( )
SYNTAX:
stringObject.sup( )
EXAMPLE:
<script type=”text/javascript”>
document.write(str.big() + “<br>”) ;
document.write(str.small() + “<br>”);
document.write(str.bold() + “<br>”);
document.write(str.italics() + “<br>”);
document.write(str.strike() + “<br>”);
document.write(str.blink() + “<br>”);
document.write(str.sup() + “<br>”);
document.write(str.sub() + “<br>”);
</script>
• fontcolor ( )
SYNTAX:
stringObject.fontcolor( color)
Parameter Description
Color Required. Specifies a font-color for
the string. The value can be a color
name(red), an RGB value
(rgb(255,0,0)),or a hex number
(#FF0000)
• fontsize ( )
• The fontsize( ) method is used to display a string in a specified size.
SYNTAX:
stringObject.fontsize( size)
Parameter Description
Size Required. A number that specifies
the font size Range 1 to 7.
Link ( )
The link () method is used to display a string as a hyperlink.
SYNTAX:
stringObject.link(stringURL)
EXAMPLE:
<script language= “JavaScript”>
var str= “link”;
document.write(str.fontcolor (“yellow”) +“<br>”);
document.write(str.fontsize(5) +“<br>”);
document.write(str.link(“http://www.xyz.com”) +“<br>”);
</script>
• CharAt ( )
o The charAt() method returns the character at a specified position.
o The first character in the string is at 0.
SYNTAX:
o stringObject.charAt(index)
Parameter Description
Index Required,A number representing a position in the string.
EXAMPLE:
<script type= “text/JavaScript”>
var str = “hello world!”;
document.write (str.charAt (1));
</script>
OUTPUT:
Hello world!
• Concat( )
o The concat() method is used to join two or more strings.
SYNTAX:
o stingObject(stringX,stringX,…,stringX)
Parameter Description
stringX Required,One or more string objects to be joined to a string.
EXAMPLE:
<script type= “text/javascript”>
var str1 = “hello”;
var str2= “world!”;
document.write(str1.concat(str2));
</script>
OUTPUT:
Hello world!
• indexOf ( )
o The indexOf() method returns the position of the first occurrence of a
specified string value in a string.
o The indexOf() methods is case sensitive.
o This method returns -1 if the string value to search for never occurs.
SYNTAX:
o StringObject. indexOf(searchvalue fromindex)
Parameter Description
Searchvalue Required,specifies a strring value to search for
Fromindex Optional,specifies where to strat the search
EXAMPLE:
OUTPUT:
0
-1
6
• lastndexOf ( )
SYNTAX:
o stringObject.lastindexOf(searchvalue, fromindex)
Parameter Description
Searchvalue Required,specifies a strring value to search for
Fromindex Optional,specifies where to strat the search
EXAMPLE:
<script type=”text/JavaScript”>
var str = “hello world!”;
Document.write (str.lastindexOf (“Hello”) + “<br/>”);
Document.write (str.lastindexOf (“world”) + “<br/>”);
Document.write (str.lastindexOf (“world”));
</script>
OUTPUT:
0
-1
6
• match( )
SYNTAX:
o stringObject. match(searchvalue)
Parameter Description
Searchvalue Required,specifies a strring value to search for
EXAMPLE:
<script type= “text/JavaScript”>
var str = “hello world!”;
Document.write (str.match (“Hello”) + “<br/>”);
Document.write (str.match (“world”) + “<br/>”);
Document.write (str.match (“worlld”) + “<br/>”);
Document.write (str.match (“world”));
</script>
OUTPUT:
World
Null
Null
World!
• Replace ( )
o The replace () method is used to replace some character with some other
character in a string.
o The replace () methods is case sensitive.
SYNTAX:
o stringObject.replace (find string ,new string)
Parameter Description
Find string Required, specifies a strring value to find, to perform a global
search add a ‘g’ flag to this parameter and to perform a case-
insensitive Search add an ‘i’ flag.
New string required, specifies the string to replace the Found value from
find string.
EXAMPLE:
<script type= “text/javascript”>
var str1 = “Visit Microsoft!”;
var str2 = “Visit Microsoft!”;
var str3 = “Visit Microsoft!”;
var str4 = “Welcome to Microsoft!”;
var str5 = “Welcome to Microsoft!”;
Document.write (str1.replace(/Microsoft/, “W3schools”)+ “<br/>”);
Document.write (str2.replace(/Microsoft/, “W3schools”)+ “<br/>”);
Document.write (str3.replace(/Microsoft/i,“W3schools”)+ “<br/>”);
Str4= str4+ “we are proud to announce that Microsoft have”;
Str5= str5+ “on of the largest Web Developers site in the world.”;
Document.write (str5.replace(/Microsoft/gi “W3school”)+ “<br/>”);
</script>
OUTPUT:
Visit W3schools!
Visit Microsoft!
Visit W3schools!
Welcome to W3schools! We are proud to announce that W3school have one of
the largest Web Developers site in the world.
Welcome to W3schools! We are proud to announce that W3school have one of
the largest Web Developers site in the world.
• search ( )
o The search () method is used to search a string for specified value.
o The search () methods is case sensitive.
o This method returns the position of the specified value in the string, if a
match found it returns -1.
SYNTAX:
o String Object. Search (search string)
Parameter Description
Searchstring Required, the value to search for in string. To perform the
case .insensitive search add an ‘I’ flag.
EXAMPLE:
<script type= “text/JavaScript”>
var str = “visit W3schools!”;
Document.write (str.search (“/W3schools/”));
Document.write (str.search (“/w3schools/”));
Document.write (str.search (“/w3schools/i”));
</script>
OUTPUT:
6
-1
6
• slice ( )
o The slice () method extract a part of a string and returns the extracted part in
a new string.
o U can use negative index numbers to select from the end of the string.
o If end is not specified, slice () selects all characters from the specified stat
position and to the end of the string.
SYNTAX:
o String Object. Slice (start, end)
Parameter Description
Start Required, specify where to start the selection. Must be a number.
End Optional, specify where end to the selection. Must be a number.
EXAMPLE:
<script type= “text/JavaScript”>
var str = “Hello Happy World!”;
Document.write (str .slice (6));
Document.write (str .slice (6, 11));
</script>
OUTPUT:
Happy World!
Happy
• substr ( )
o The substr () method is extracts specifies number of characters in string
from a start index.
o To extract characters from the end of string, use a negative start number.
o The start index at 0.
o If the length of the parameter is omitted this method is extracts to the end of
the string.
SYNTAX:
o String Object. substr(start ,length)
Parameter Description
Start Required, where to start the extraction. Must be a numeric value.
Length Optional, how many character to extract. Must be a numeric
value.
EXAMPLE:
<script type= “text/JavaScript”>
var str = “Hello World!”;
Document.write (str.substr (3));
Document.write (str.substr (3, 7));
</script>
OUTPUT:
Lo world!
Lo worl
• Substring ()
• The substring() method extracts the characters in a string between two specified
indices.
• To extract charactersvfrom the end of the string,use a negative start number.
• The start index starts at 0.
• If the stop parameter is omitted,this method extracts to the end of the string.
SYNTAX:
String Object.substring(start,stop)
Parameter Description
start Required,where to start the extraction,Must be a numerical
value
Stop optional,where to start the extraction,Must be a numerical
value
EXAMPLE:
<script type=”text/javascript”>
var str =”Hello world!”;
document.write(str substring(3));
document.write(str substring(3,7));
</script>
OUTPUT:
lo world
lo w
• toLowerCase
• The toLowerCase() methods is used to display a string in lowercase letters.
SYNTAX:
stringObject. toLowerCase()
EXAMPLE:
<script type=”text/javascript”>
var str =”Hello world!”;
document.write(str.toLowerCase());
</script>
OUTPUT:
hello world!
• toUpperCase()
• The toUpperCase() methods is used to display a string in Uppercase letters.
SYNTAX:
stringObject. toUpperCase()
EXAMPLE:
<script type=”text/javascript”>
var str =”Hello world!”;
document.write(str.toUpperCase());
</script>
OUTPUT:
HELLO WORLD!
• length
• The length property returns the number of characters in string.
SYNTAX:
stringObject.length
EXAMPLE:
<script type=”text/javascript”>
var str =”Hello world!”;
document.write(text.length);
</script>
OUTPUT: 12
Math Object
The main objects provides methods and property to move beyond simple arithmetic
manipulations offered by arithmetic operators.
Math Object Methods
• Abs
SYNTAX:
Math.abs(X)
Parameter Description
X Required,Must be a numeric value
EXAMPLE
<script type=”text/javascript”>
document.write(Maths.abs(7.25) + “<br/>”);
document.write(Maths.abs(-7.25) + “<br/>”);
document.write(Maths.abs(7.25-10));
</script>
OUTPUT:
7.25
7.25
2.75
• Cell
• The cell() methods returns the value of a number rounded UPWARDS to the
nearest integer..
SYNTAX:
Math.cell(X)
Parameter Description
X Required,A number
EXAMPLE:
<script type=”text/javascript”>
document.write(Maths.cell(0.60) + “<br/>”);
document.write(Maths.cell(0.40) + “<br/>”);
document.write(Maths.cell(5) + “<br/>”);
document.write(Maths.cell(5.1) + “<br/>”);
document.write(Maths.cell(-5.1) + “<br/>”);
document.write(Maths.cell(-5.9));
</script>
OUTPUT:
1
1
5
5
6
• floor()
SYNTAX:
Math.floor(X)
Parameter Description
X Required,A number
EXAMPLE:
<script type=”text/javascript”>
document.write(Maths.floor(0.60) + “<br/>”);
document.write(Maths.cell(5.1) + “<br/>”);
document.write(Maths.cell(-5.6));
</script>
OUTPUT:
0
5
-6
• exp()
• The exp() returns the value of Ex,where E is Euler’s constant(approximately 2.7183)
and x is the number passed to it.
• E is the Euler’s constant,which is the base of natural logarithms(approximately
2.7183).
SYNTAX:
Math.exp(X)
Parameter Description
X Required,A number
EXAMPLE:
<script type=”text/javascript”>
document.write(Maths.exp(1) + “<br/>”);
document.write(Maths.exp(-1) + “<br/>”);
</script>
OUTPUT:
2.718281828459045
0.36787944117144233
• cos()
• The cos() method returns the cosine of a number.
• The cos() method returns a numeric value between -1 and 1,which represents the
cosine of the angle.
SYNTAX:
Math.cos(X)
Parameter Description
X Required,A number
EXAMPLE:
<script language=”javascript”>
document.write(Maths.cos(3) + “<br/>”);
document.write(Maths.cos(-3) + “<br/>”);
document.write(Maths.cos(0) + “<br/>”);
</script>
OUTPUT:
-0.9899924966004454
-0.9899924966004454
1
• sin()
• The sin() method returns the sine of a number.
• The sin() method returns a numeric value between -1 and 1,which represents the
sine of the arguments.
SYNTAX:
Math.sin(X)
Parameter Description
X Required,A number
EXAMPLE:
<script type=”text/javascript”>
document.write(Maths.sin(3) + “<br/>”);
document.write(Maths.sin(-3) + “<br/>”);
document.write(Maths.sin(0) + “<br/>”);
</script>
OUTPUT:
0.1411200080598672
-0.1411200080598672
0
• tan()
• The tan() method returns a number that represents the tangent of an angle.
SYNTAX:
Math.tan(X)
Parameter Description
X Required,A number
EXAMPLE:
<script type=”text/javascript”>
document.write(Maths.tan(0.50) + “<br/>”);
document.write(Maths.tan(-0.50) + “<br/>”);
document.write(Maths.tan(5) + “<br/>”);
</script>
OUTPUT:
0.5463024898437905
- 0.5463024898437905
- 3.380515006246586
• log()
• The log() methodsreturns the natural logarithm(base E) of a number.
• If the parameter X is negative,NaN is returned.
SYNTAX:
Math.log(X)
Parameter Description
X Required,A number
EXAMPLE:
<script type=”text/javascript”>
document.write(Maths.log(2.7183) + “<br/>”);
document.write(Maths.log(1) + “<br/>”);
document.write(Maths.log(0) + “<br/>”);
document.write(Maths.log(-1));
</script>
OUTPUT:
1.0000066849139877
0
-Infinity
NaN
• pow ( ) : - The pow () method returns the value of x to the the power of y (xy).
SYNTAX: -
Math.pow(x, y)
Parameter Description
X Required A number
Y Required A number
EXAMPLE: -
<script language=”javascript”>
document.write (Math.pow (1, 10) +”<br>”);
document.write (Math.pow (2, 3) +”<br>”);
document.write (Math.pow (-2, 3) +”<br>”);
</script>
OUTPUT: 1
8
-8
SYNTAX: -
Math.random(x, y)
EXAMPLE
<script language=”javascript”>
document.write (Math.random ());
</script>
OUTPUT: 0.8582012591003447
• max ( ): - The max ( ) method returns the number with the highest value of two
specified numbers.
SYNTAX: -
Math.max(x,y)
Parameter Description
X Required A number
Y Required A number
EXAMPLE:
< script type “text / java script ” >
document.write (Math.max(5,7)+”<br>”);
document.write (Math.max(5,-7)+”<br>”);
< / script >
OUTPUT : 7
5
• min ( ):- The min( ) method returns the number with the lowest value of two
specified numbers.
SYNTAX: -
Math.min(x,y)
Parameter Description
X Required A number
Y Required A number
EXAMPLE: -
< script type = “text/javascript” >
document.write (Math.max(5,7)+”<br>”);
document.write (Math.max(-3,5)+”<br>”);
< / script >
OUTPUT: 5
-3
EXAMPLE: -
<script language=”javascript”>
document.write(Math.round(0.60)+”<br/>”);
document.write(Math.round(0.49)+”<br/>”);
document.write(Math.round(-4.60));
</script>
OUTPUT: - 1
0
-5
Date object
Date object Methods
• Date ( ): -
SYNTAX : - Date( )
• getDate( ) : -
o The getDate( ) method returns the day of the month.
o The value returned by getDate( ) is a number between 1 to 31.
o This method is always used in conjuction with a Date object.
SYNTAX: - dateObject.getDate( )
• getDay( ): -
o The getDay( ) method returns a number that represents the day of the week.
o The value returned by getDay( ) is a number between 0 to 6,Sunday is 0,
Monday is 1 and so on.
o The method is always used in conjunction with a Date object.
SYNTAX: - dateObject.getDay( )
• getMonth(): -
o getMonth( ) methd retuns the month, as a number.
o The value returned by getDay( ) is a number between 0 to 11,January is 0,
February is 1 and so on.
o The method is always used in conjunction with a Date object.
SYNTAX: - dateObject.getMonth( )
• getYear(): -
SYNTAX: - dateObject.getMonth( )
• getFullYear( ): -
SYNTAX: - dateObject.getFullYear( )
EXAMPLE: -
< script type = “text/javascript” >
var d = new Date(“December 03,2005 01:15:26”);
var born = new Date(“July 21, 1983 01:15:00”);
OUTPUT:
Sat Dec 03 01:15:26 2005
3
11
6
2005
I was born in 1983
83
2005
• getHours(): -
SYNTAX: - dateObject.getHours( )
• getMinutes(): -
o The getMinutes( ) methd retuns the minutes of a time.
o The value returned by getMinutes( ) is a 2 digit number. However, the return
value is not always two digits, if the value is less than 10 it only returns one
digit.
o The method is always used in conjunction with a Date object.
SYNTAX: - dateObject.getMinutes( )
• getSeconds(): -
SYNTAX: - dateObject.getSeconds( )
• getMilliseonds(): -
SYNTAX: - dateObject.getMilliseconds( )
• getTime()
The getTime() method returns the number of milliseconds since midnight of
January 1, 1970
SYNTAX:
dataObject.getTime()
EXAMPLE:
<script type=”text/javascript”>
Var d=new Date(“December 03,2005 01:15:26”);
Document.write(“Hour:=” +d.getHours() +’<br>’);
Document.write(“Miniuts:=” +d.getMiniuts() +’<br>’);
Document.write(“Seconds:= ”+d.getSeconds() +’<br>’);
Document.write(“Milliseconds:=” +d.getMilliseconds() +’<br>’);
Document.write(d.getTime()+ ”milliseconds since 1970/01/01”);
</script>
OUTPUT:
Hour:=1
Miniuts:=15
Seconds:=26
Milliseconds:=0
1133590526000 milliseconds since 1970/01/01
• setDate()
The setDate() method is used to set the day of the month.
SYNTAX:
dateObject.setDate(day)
Parameter Description
• setMonth()
SYNTAX
dataObject.setMonth(month,day)
Parameter Description
Month Required. A numeric value
between 0 and 11 representing
the month
Day Optional. A numeric value
between 1 and 31 representing
the day.
• setFullYear()
SYNTAX:
DateObject setFullYear(year,month,day)
Parameter Description
• setYear()
SYNTAX:
dataObject.setYear(year)
Parameter Description
EXAMPLE:
<script language=”javascript”>
Var d=new Date(“December 03,2005 01:15:26”);
Document.write(“Month Day:=” + d.getDate() +’<br>’);
d.setDate(15);
document.write(“Month Day After setDate(15):= ” +d.getDate() +’<br>’);
d.setMonth(8);
document.write(“Month:=” +d.getMonth() +’<br>’);
d.setYear(2004);
document.write(“Year:=” + d.getYear() +’<br>’);
d.setFullYear(90);
document.write(“Year:=” +d.getFullYear() +’<br>’);
</script>
OUTPUT:
Month Day:=3
Month Day After setDate(15):= 15
Month:=8
Year:=2004
Year:=90
• setHours()
• The setHours() method is used to the hour of a specified time.
• If one of the parameters above is specified with a one-digit number, Javascript
adds one or two leading zeroes in the result.
SYNTAX:
dateObject.setHours(hour,min,sec,millisec)
Parameter Description
• setMinutes()
SYNTAX
dataObject.setMinutes(min,sec,millisec)
Parameter Description
• setSeconds()
• The setSecond metod is used to set the second of a specific time.
• If one of the parameter above is specified with a one-digit number.
JavaScript adds one or two leading zero in the result.
SYNTAX
dataObject.setSeconds(sec,millisec)
Parameter Description
personObj=new Object();
personObj.firstname=”Anil”;
personObj.lastname=”Patel”;
personObj.age=25;
personObj.eyecolor=”blue”;
Adding a method to the personObj is also simple. The
following code adds a method called eat() to the personObj.
Function newlastname()
{
code
}
Form Object element/Sub Objects
JavaScript Event
• Onabort:
The Onabort event occurs when loading of an image is aborted.
SYNTAX:
Onabort=”SomeJavaScriptCode”;
Parameter Description
Somejavascriptcode Required,specifies a javascript to be executed when
the event occurs.
• In this EXAMPLE we will call a function if the loading of the image is aborted:
<html>
<head>
<script type=”text/Javascript”>
function abortImage()
{
alert(“Error:Loading of the image was aborted”)
}
</script>
</head>
<body>
<img src=”image_w3default.gif”onabort=”abortImage()”>
</body>
</html>
• Onblur
• The onchange event occurs when the content of a field changes.
SYNTAX:
onblur=”SomeJavaScriptCode”;
Parameter Description
SomeJavaScript Code Required ,Specifies a Javascript to be executed
when the event occurs.
Supported by the following Javascript Objects:
Button, checkbox, frame, password, radio, reset, reset, submit, text, textarea,
window
EXAMPLE:
• In this EXAMPLE we will execute some Javascript code when a user
leaves an input field:
<html>
<head>
<script type=”text/javascript”>
function uppercase()
{
var x=document.getElementByld(“fname”).value;
document.getElementBylt(“fname”).value=x.toupperCase();
}
</script>
</head>
<body>
Enter your name:
<input type=”text” id=”frame” onblur=”uppercase()”>
</body>
</html>
• Onchange
• The onchange event occurs when the content of a field changes.
SYNTAX:
onchange=”SomeJavaScriptCode”;
Parameter Description
Somejavascriptcode Required,specifies a javascript to be executed
when the event occurs.
• Onclick
• The onclick event occurs when an object gets clicked.
SYNTAX:
onclick=”SomeJavaScriptCode”;
Parameter Description
Somejavascriptcode Required,specifies a javascript to be executed
when the event occurs.
Supported by the following JavaScript objects:
Button, document, checkbox, link, radio, reset, submit
EXAMPLE:
• In this EXAMPLE the text in the first input field will be copied to the second
input field when a button is clicked:
<html>
<body>
Field1:<input type=”text” id=“field” value=”hello World!”>
<br>
Field2: <input type=”text” id=“field2”>
<br><br>
Click the button below to copy the content of Field1 to Field2.
<br>
<input type=”Submit” value=”Copy Text”
onclick=”document.getElementByld(“field2”);
value=document.getElementByld(“field1”)value”>;
</body>
</html>
• Ondblclick
• The ondblclick event occurs when an object gets double-clicked.
SYNTAX:
ondblclick=”SomeJavaScriptCode”;
Parameter Description
Somejavascriptcode Required,specifies a javascript to be executed
when the event occurs.
Supported by the following Javascript objects:
document, link
EXAMPLE:
• In this EXAMPLE the second field changes according to the forst field when
you double-click on the button:
<html>
<body>
Field1: <input type=”text” id=“field1” value=”Hello World!”>
<br>
Field2: <input type=”text” id=“field2”>
<br><br>
Click the button below to copy the content of Field1 to Field2.
<br>
<input type=”Submit” value=”Copy Text”
onclick=”document.getElementByld(“field2”).value=
document.getElementByld(“field1”)value”>
</body>
</html>
• onerror
• The onerror event is triggered when an error occurs loading a document or an
image.
SYNTAX:
onerror=”SomeJavaScriptCode”;
EXAMPLE:
• In this EXAMPLE an alert box will be displayed if an error occurs when
loading an image.
<img src=”image.gif”
onerror=”alert(“the aimage could not be loaded”)”>
• onfocus
• The onfocus event occurs when an object gets focus.
SYNTAX:
onfocus=”SomeJavaScriptCode”;
EXAMPLE:
• In this EXAMPLE the background color of the input fields change when they
get focus:
<html>
<head>
<script type=”text/javascript”>
function setStyle(x)
{
document.getElementBylt(x).style.backgroud=”yellow”;
}
</script>
</head>
<body>
First name:<input type=”text” id=“fname”
onfocus=”setStyle(this.id)”>
<br>
Last name: <input type=”text” id=“lname”
onfocus=”setStyle(this.id)”>
</body> </html>
• onkeydown
• The onkeydown event occurs when a keyboard key is pressed.
• Browser differences: Internet Explorer uses event.keyCode to retrieve the
character that was pressed and Netscape/Firefox/Opera uses event.which.
SYNTAX:
onkeydown=”SomeJavaScrptCode”;
EXAMPLE:
<html>
<body>
<script type=”text/javascript”>
function noNumbers(e)
{
var keynum
if(window..event) // IE
{
keynum=e.keyCode;
}
• onkeypress
• The onkeypress event occurs when a keyboard key is pressed or held down.
• Browser differences: Internet Explorer uses event.keyCode to retrieve the
character that was pressed and Netscape/Firefox/Opera uses event.which.
SYNTAX:
onkeypress=”SomeJavaScrptCode”;
EXAMPLE:
<html>
<body>
<script type=”text/javascript”>
function noNumbers(e)
{
var keynum
if(window..event) // IE
{
keynum=e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum=e.which;
}
alert(keynum)
}
</script>
<form>
<input type=”text” onkeypress=noNumbers(event)>
</form>
</html>
• Onkeyup
SYNTAX:
onkeydown=”SomeJavaScrptCode”;
EXAMPLE:
<html>
<body>
<script type=”text/javascript”>
function noNumbers(e)
{
var keynum
if(window..event) // IE
{
keynum=e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum=e.which;
}
alert(keynum)
}
</script>
<form>
<input type=”text” onkeyup=noNumbers(event)>
</form>
</html>
• Onmousedown
SYNTAX:
onmousedown=”SomeJavaScrptCode”;
EXAMPLE:
<img src=”image_w3default.gif”
onmousedown=”alert(“You clicked the picture”)>
• Onmouseup
SYNTAX:
onmouseup=”SomeJavaScrptCode”;
EXAMPLE:
<img src=”image_w3default.gif”
onmouseup=”alert(“release the mouse button”)>
• Onmousover
• The onmouseover event occurs when a mouse pointer moves over a specified
object.
SYNTAX:
onmouseover=”SomeJavaScrptCode”;
EXAMPLE:
<img src=”image_w3default.gif”
onmouseover=”alert(“mouse pointer over”);
• Onmousemove
SYNTAX:
onmousemove=”SomeJavaScrptCode”;
EXAMPLE:
<img src=”image_w3default.gif”
onmousemove=”alert(“mouse pointer move”)>
• Onmouseout
• The onmouseout event occurs when a mouse pointer moves away from a
specified object.
SYNTAX:
onmouseout=”SomeJavaScrptCode”;
Supported by the following JavaScript objects:
button, document, link
EXAMPLE:
<img src=”image_w3default.gif”
onmouseout=”alert(“mouse pointer out”)>
• Onselect
• The onselect event occurs when text is selected in a text or textarea field.
SYNTAX:
onselect=”SomeJavaScrptCode”;
EXAMPLE:
<form>
Select text: <input type=”text” value=”Hello World!”
onselect=”alert(‘You have selected some of the text.’)”>
<br><br>
Select text: ><textarea cols=”20” rows=”5”
Onselect=”alert(‘You have selected some of the text.’)”>
Hello World!</textarea>
</form>
• Onsubmit
• The onsubmit event occurs when the submit button in a form is clicked.
SYNTAX:
onsubmit=”SomeJavaScrptCode”;
EXAMPLE:
<form name=”tyestform” action=”jsref_onsubmit.asp”
onsubmit=”alert(‘Hello’+ testform.frame.value +’!’”>
What is your name?<br>
<input type=”text” name=”fname”>
<input type=”submit” value=”Submit”>
</form>
• Onreset
• The onreset event occurs when the reset button in a form is clicked.
SYNTAX:
onreset=”SomeJavaScrptCode”;
EXAMPLE:
<form onreset=”alert(‘The form will be reset’)”
Firstname:<input type=”text” name=”fname” value=”John”>
<br>
Lastname:<input type=”submit” value=”lname”>
<br><br>
<input type=”reset” value=”Reset”>
</form>
• Onresize
SYNTAX:
onresize=”SomeJavaScrptCode”;
EXAMPLE:
• Onload
EXAMPLE:
<html>
<head>
<script type=”text/javascript”>
function load()
{
window.status=”Page is loaded”;
}
</script>
</head>
<body onload=”load()”>
</body>
</html>
• Onunload
SYNTAX:
onunload=”SomeJavaScrptCode”;
EXAMPLE:
<body onunload=”alert(‘The onunload event was triggered’)”>
</body>
Cookies:
• A cookie is a variable that is stored on the visitor’s computer.
• When user requests a page, on HTTP request is sent to the server. The request
includes a header that defines several information, including the page being
requested.
• The server returns the HTTP response that also include header. The contains
information about the document being return & also contain some information.
• Cookies information is shared between the client browser and server using field in
the HTTP header.
• When a user requests a page for the first time, a cookies can be stored in the
browser by a set-cookie entry in the header of the response from the server.
• The set-cookie field include information to be stored in the cookie along with
several optional piece of information including expire date, path and server
information and if the cookies required security.
• In future a user request a page then the browser send the stored cookies
information to the server in a request header.
• Set-cookie SYNTAX:
Set-cookie: Name=value : EXPIRES=date : PATH=path : DOMAIN=domain:
SECURE
• The NAME=value is required piece of information & all other are optional.
Name Description
NAME=value Specifies the name of the cookies.
EXPIRES=date Specifies the expiry date of the cookies. After this date the
cookies will no longer to stored by the client.
The form of the date is DD-MON-YY HH:MM:SS
PATH=path Specifies the path portion of the URL for which the cookie
is valid. If the URL matches both the PATH and
DOMAIN then the cookie is sent to the server.
The default value is the current web page.
DOMAIN=domain Specifies the domain portion of the URL for which the
cookie is valid.
The default value is the current domain.
SECURE Specifies that the cookie should only be transmitted over a
secure link.
EXAMPLE:
<html>
<head>
<script type=”text/javascript”>
function newcookie()
{
document.cookie=”name=Anil”;
document cookie=”age=18”;
}
</script>
<body onload=”newcookie()”>
<script>
var str=document.cookie;
document.write(“Cookie String: <b>” + str + “</b>”>);
document.write(“<br>Total Char in cookie:<b> “+ str.lentgh +
”</b>” );
</script>
</body>
</html>