You are on page 1of 41

Unit - I 1 JavaScript

JavaScript Tutorial

JavaScript is the scripting language of the Web!

In our JavaScript tutorial you will learn how to write JavaScripts and
insert them into your HTML documents, and how to make your pages more
dynamic and interactive.
JavaScript is used in millions of Web pages to improve the design,
validate forms, and much more. JavaScript was developed by Netscape and
is the most popular scripting language on the internet.
JavaScript works in all major browsers that are version 3.0 or higher.

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 is lines of executable computer code
 A JavaScript is usually embedded directly in HTML pages
 JavaScript is an interpreted language (means that scripts execute
without preliminary compilation)
 Everyone can use JavaScript without purchasing a license
 All major browsers, like Netscape and Internet Explorer, support
JavaScript.

Are Java and JavaScript the same?


NO !
Java and JavaScript are two completely different languages!
Java (developed by Sun Microsystems) is a powerful and very complex
programming language - in the same category as C and C++.
What can a JavaScript Do?
• JavaScript gives HTML designers a programming tool - HTML
authors are normally not programmers, but JavaScript is a scripting
language with a very simple syntax! Almost anyone can put small
"snippets" of code into their HTML pages.
• JavaScript can put dynamic text into an HTML page - A JavaScript
statement like this: document.write("<h1>" + name + "</h1>") can
write a variable text into an HTML page
• JavaScript can react to events - A JavaScript can be set to execute when
something happens, like when a page has finished loading or when a user
clicks on an HTML element
• JavaScript can read and write HTML elements - A JavaScript can read
and change the content of an HTML element
• JavaScript can be used to validate data - A JavaScript can be used to
validate form data before it is submitted to a server, this will save the
server from extra processing
Unit - I 2 JavaScript

Enable JavaScript and detect disable setting of client browser:

Are you using a browser that doesn't support JavaScript?

If your browser does not support JavaScript, you can upgrade to a newer
browser, such as Microsoft® Internet Explorer 6 or Netscape 6.

Have you disabled JavaScript?


If you have disabled JavaScript, you must re-enable JavaScript to use
this page. To enable JavaScript:
Using Internet Explorer 6

1. On the Tools menu, click Internet Options.


2. Click the Security tab.
3. Click Custom Level.
4. Scroll to Scripting. Under Active scripting, click Enable. Click OK
twice.
Using Netscape 6

1. On the Edit menu, click Preferences.


2. Click Advanced.
3. Select the Enable JavaScript for Navigator check box. Click OK.
JavaScript How To ...
The HTML <script> tag is used to insert a JavaScript into an HTML page.
How to Put a JavaScript Into an HTML Page

<html>
<body>
<script type="text/javascript">
// <script language=”JavaScript”>
document.write("Hello World!")
</script>
</body>
</html>

The code above will produce this output on an HTML page:

Hello World!

Example Explained
To insert a script in an HTML page, we use the <script> tag. Use the type
attribute to define the scripting language

<script type="text/javascript">

Then the JavaScript starts: The JavaScript command for writing some
output to a page is document.write
Unit - I 3 JavaScript

document.write("Hello World!")

Then the <script> tag has to be closed

</script>

Ending Statements With a Semicolon?


With traditional programming languages, like C++ and Java, each
code statement has to end with a semicolon. Many programmers continue
this habit when writing JavaScript, but in general, semicolons are optional!
However, semicolons are required if you want to put more than one
statement on a single line.
How to Handle Older Browsers
Browsers that do not support scripts will display the script as page
content. To prevent them from doing this, we may use the HTML comment
tag:

<script type="text/javascript">
<!--
some statements
//-->
</script>

The two forward slashes at the end of comment line (//) are a JavaScript
comment symbol. This prevents the JavaScript compiler from compiling the
line.
Note: You cannot put // in front of the first comment line (like //<!--), because
older browsers will display it. Strange? Yes! But that's the way it is.
JavaScript Where To ...
Scripts in the body section will be executed WHILE the page loads.
Scripts in the head section will be executed when CALLED.
Where to Put the JavaScript
Scripts 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.

Scripts in the head section: Scripts to be executed when they are called, or
when an event is triggered, go in the head section. When you place a script
in the head section, you will ensure that the script is loaded before anyone
uses it.

<html>
<head>
<script type="text/javascript">
doucument.write(“Hai”);
</script>
</head>
Unit - I 4 JavaScript

Scripts in the body section: Scripts to be executed when the page loads go in
the body section. When you place a script in the body section it generates
the content of the page.

<html>
<head>
</head>
<body>
<script type="text/javascript">
some statements
</script>
</body>

Scripts in both the body and the head section: You can place an unlimited
number of scripts in your document, so you can have scripts in both the
body and the head section.
<html>
<head>
<script type="text/javascript">
some statements
</script>
</head>
<body>
<script type="text/javascript">
some statements
</script>
</body>

How to Run an External JavaScript


Sometimes you might want to run the same script on several pages,
without writing the script on each and every page.
To simplify this you can write a script in an external file, and save it with
a .js file extension, like this:

document.write("This script is external")

Save the external file as xxx.js.


Note: The external script cannot contain the <script> tag now you can call this
script, using the "src" attribute, from any of your pages:

<html>
<head>
</head>
<body>
<script src="xxx.js"></script>
</body>
</html>
Remember to place the script exactly where you normally would write the
script
Unit - I 5 JavaScript

JavaScript Variables
Variable:A variable is a "container" for information you want to store. A variable's
value can change during the script. You can refer to a variable by name
to see its value or to change its value.
Rules for Variable names: (1) Variable names are case sensitive.
(2) They must begin with a letter or the underscore character.

Declare a Variable
You can create a variable with the var statement:
var strname = some value

You can also create a variable without the var statement:

strname = some value

Assign a Value to a Variable


You assign a value to a variable like this:
var strname = "PVPSIT"

Or like this:

strname = "PVPSIT"
The variable name is on the left side of the expression and the value
you want to assign to the variable is on the right. Now the variable
"strname" has the value "PVPSIT".
JavaScript Operators
Operators are used to operate on values.
Arithmetic Operators

Operator Description Example Result


+ Addition x=2 4
x+2
- Subtraction x=2 3
5-x
* Multiplication x=4 20
x*5
/ Division 15/5 3
5/2 2.5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
Unit - I 6 JavaScript

Strings are concatenated together using the "+" operator.


Assignment Operators

Operator Example Is The Same As


= 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
Comparison Operators

Operator Description Example


== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true

Logical Operators

Operator Description Example


&& and x=6
y=3
(x < 10 && y > 1) returns true
|| or x=6
y=3
(x==5 || y==5) returns false
! not x=6
y=3
!(x==y) returns true
? Conditional ----
, Comma ----

String Operator
A string is most often text, for example "Hello World!". To stick two or more
string variables together, use the + operator.

txt1="What a very"
txt2="nice day!"
txt3=txt1+txt2

The variable txt3 now contains "What a verynice day!".


Unit - I 7 JavaScript

To add a space between two string variables, insert a space into the
expression, OR in one of the strings.

txt1="What a very"
txt2="nice day!"
txt3=txt1+" "+txt2
or
txt1="What a very "
txt2="nice day!"
txt3=txt1+txt2

The variable txt3 now contains "What a very nice day!".

Bitwise Operators
These operators work at the bit level performing the operator function
on a bit per bit basis. The operation must be thought of as binary, octal, or
hexadecimal values (depending on preference) to consider how it works.
Consider the decimal number 15.

15 & 3 = 3 - Equivalent binary: 1111 & 0011 = 0011


15 | 3 = 15 - Equivalent binary: 1111 | 0011 = 1111
15 | 16 = 31 - Equivalent binary: 1111 | 10000 = 11111
15 | 30 = 31 - Equivalent binary: 1111 | 11110 = 11111

Operator Meaning
& AND
~ NOT
| OR
^ exclusive OR
<< Left shift
>> Right shift
>>> Right shift, fill with zeros

JavaScript Functions
Functions
A function contains some code that will be executed by an event or a
call to that function. A function is a set of statements. You can reuse
functions within the same script, or in other documents. You define
functions at the beginning of a file (in the head section), and call them later
in the document. It is now time to take a lesson about the alert-box:
This is JavaScript's method to alert the user.

alert("This is a message")
Unit - I 8 JavaScript

How to Define a Function


To create a function you define its name, any values ("arguments"),
and some statements:
function myfunction(argument1,argument2,etc)
{
some statements
}

A function with no arguments must include the parentheses:

function myfunction()
{
some statements
}

Arguments are variables used in the function. The variable values are
values passed by the function call. By placing functions in the head section
of the document, you make sure that all the code in the function has been
loaded before the function is called. Some functions return a value to the
calling expressions.
function result(a,b)
{
c=a+b
return c
}

How to Call a Function


A function is not executed before it is called. You can call a function
containing arguments:
myfunction(argument1,argument2,etc)
or without arguments:

myfunction()

The return Statement:Functions that will return a result must use the "return"
statement. This statement specifies the value which will be returned to
where the function was called from. Say you have a function that returns
the sum of two numbers:

function total(a,b)
{
result=a+b
return result
}

When you call this function you must send two arguments with it:

sum=total(2,3)
Unit - I 9 JavaScript

The returned value from the function (5) will be stored in the variable
called sum.
JavaScript Conditional Statements
Conditional Statements
Very often when you write code, you want to perform different actions for
different decisions. You can use conditional statements in your code to do
this. In JavaScript we have three conditional statements:
if statement - use this statement if you want to execute a set of code when a
condition is true.
if...else statement - use this statement if you want to select one of two sets of
lines to execute
switch statement - use this statement if you want to select one of many sets
of lines to execute
If and If...else Statement
You should use the if statement if you want to execute some code if a
condition is true.
Syntax:
if (condition)
{
code to be executed if condition is true
}

Example

<script type="text/javascript">
//If the time on your browser is less than 10,
//you will get a "Good morning" greeting.
var d=new Date()
var time=d.getHours()

if (time<10)
{
document.write("<b>Good morning</b>")
}
</script>
Notice that there is no ..else.. in this syntax. You just tell the code to
execute some code if the condition is true.If you want to execute some
code if a condition is true and another code if a 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 false
}
Unit - I 10 JavaScript

Example
<script type="text/javascript">
//If the time on your browser is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date()
var time = d.getHours()
if (time < 10)
{
document.write("Good morning!")
}
else
{
document.write("Good day!")
}
</script>

Switch Statement
You should use the Switch statement if you want to select one of
many blocks of code to be executed.
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1
break
case label2:
code to be executed if expression = label2
break
default:
code to be executed
if expression is different
from both label1 and label2
}
This is how it works: First we have a single expression (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 code associated with that case is executed. Use break
to prevent the code from running into the next case automatically.
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()
theDay=d.getDay()
switch (theDay)
{
case 5:
document.write("Finally Friday")
Unit - I 11 JavaScript

break
case 6:
document.write("Super Saturday")
break
case 0:
document.write("Sleepy Sunday")
break
default:
document.write("I'm looking forward to this weekend!")
}
</script>

Break
The break statement may be used to break out of a while, if, switch,
dowhile, or for statement. The break causes program control to fall to the
statement following the iterative statement. The break statement now
supports a label which allows the specification of a location for the program
control to jump to. The following code will print "Wednesday is day 4 in the
week".

days = new
Array("Sunday","Monday","Tuesday","Wednesday","Thursday",\
"Friday","Saturday")
var day = "Wednesday"
var place
for (i = 0;i < days.length;i++)
{
if (day == days[i]) break;
}
place = i + 1
document.write(day + " is day " + place + " in the
week.<BR>\n")

Continue: The continue statement does not terminate the loop statement,
but allows statements below the continue statement to be skipped,
while the control remains with the looping statement. The loop is not
exited. The example below does not include any ratings values below
5.
ratings = new Array(6,9,8,4,5,7,8,10)
var sum = 0;
var reviews = 0
for (i=0; i < ratings.length; i++)
{
if (ratings[i] < 5) continue
sum += ratings[i];
reviews++;
}
var average = sum/reviews
Unit - I 12 JavaScript

Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a
variable based on 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 not
equal to PRES, then put the string "Dear " into the variable named
greeting.

JavaScript Looping
Looping
Very often when you write code, you want the same block of code to
run a number of times. You can use looping statements in your code to do
this. In JavaScript we have the following looping statements:

while - loops through a block of code while a condition is true

do...while - loops through a block of code once, and then repeats the loop
while a condition is true
for - run statements a specified number of times

while: The while statement will execute a block of code while a condition
is true..
while (condition)
{
code to be executed}
do...while: The do...while statement will execute a block of code once,
and then it will repeat the loop while a condition is true
Do
{
code to be executed
}
while (condition)
for
The for statement will execute a block of code a specified number of times
for (initialization; condition; increment)
{
code to be executed }

With Statement: Eliminates references to the object within the statement by


identifying the default object to be used inside the braces. This
example prints out the document properties and values without
referencing the document object to perform the function.
Unit - I 13 JavaScript

with (document)
{
for (i in this)
{
write("Property = " + i + " Value = " +
document[i] + "<BR>\n")
}
}

JavaScript Guidelines

Some things to know about JavaScript.


JavaScript is Case Sensitive
A function named "myfunction" is not the same as "myFunction".
Therefore watch your capitalization when you create or call variables,
objects and functions.
Symbols
Open symbols, like ( { [ " ', must have a matching closing symbol, like ' " ]
} ).
White Space
JavaScript ignores extra spaces. You can add white space to your
script to make it more readable. These lines are equivalent:
name="Hege"
name = "Hege"
Break up a Code Line
You can break up a code line within a text string with a backslash. The
example below will be displayed properly:
document.write("Hello \
World!")

Note: You can not break up a code line like this:


document.write \
("Hello World!")

The example above will cause an error.


Insert Special Characters
You can insert special characters (like " ' ; &) with the backslash:
document.write ("You \& I sing \"Happy Birthday\".")

The example above will produce this output:

You & I sing "Happy Birthday".

Comments
You can add a comment to your JavaScript code starting the comment with
two slashes "//":
sum=a + b //calculating the sum
Unit - I 14 JavaScript

You can also add a comment to the JavaScript code, starting the comment
with "/*" and ending it with "*/"

sum=a + b /*calculating the sum*/

Using "/*" and "*/" is the only way to create a multi-line comment:

/* This is a comment block. It contains several lines*/

JavaScript Object Hierarchy


Many JavaScript objects are contained within each other. JavaScript
objects have a container to contained object relationship rather than a
class and subclass relationship. Properties are not inherited from one type
of object to another. There are two main types of JavaScript objects.
• Language Objects - Objects provided by the language and are not
dependent on other objects.
• Navigator - Objects provided by the client browser. These objects are
all sub objects to the navigator object.
Beyond that, objects are those created by the programmer.

The JavaScript Hierarchy


Unit - I 15 JavaScript

The "Language" box shown in the drawing is a little misleading. It is not


an object, but is used in the drawing to illustrate the grouping of the
objects supported by the JavaScript language. Other references to objects
include:

• Parent
• Self
• Top

JavaScript Array Object


Array Object
The Array object is used to store a set of values in a single variable
name. Each value is an element of the array and has an associated index
number. You create an instance of the Array object with the "new"
keyword. The following example creates two arrays, both of three
elements:
var family_names=new Array(3)
var family_names=new Array("Tove","Jani","Stale")
Unit - I 16 JavaScript

You can refer to a particular element in the array by using the name
of the array and the index number. The index number starts at 0. If you
create an array with a single numeric parameter, you can assign data to
each of the elements in the array like this:

family_names[0]="Tove"
family_names[1]="Jani"
family_names[2]="Stale"
And the data can be retrieved by using the index number of the
particular array element you want, like this:

mother=family_names[0]
father=family_names[1]
The Array object's properties and methods are described below: NN:
Netscape, IE: Internet Explorer
Properties
Syntax: object.property_name
Property Description NN IE
constructor Contains the function that created an 4 4
object's prototype
Length Returns the number of elements in 3 4
the array
prototype Allows you to add properties to an 3 4
array

Methods
Syntax: object.method_name()
Method Description NN IE
concat() Joins two or more arrays and returns 4 4
a new array
join(delimiter) Puts all the elements of an array into 3 4
a string separated by a specified
delimiter (comma is default)
pop() Removes and returns the last 4 5.5
element of an array
push("element1","element2") Adds one or more elements to the 4 5.5
end of an array and returns the new
length
reverse() Reverses the order of the elements in 3 4
an array
shift() Removes and returns the first 4 5.5
element of an array
slice(begin[,end]) Creates a new array from a selected 4 4
section of an existing array
sort() Sorts the elements of an array 3 4
splice(index,howmany[,el1,el Adds and/or removes elements of an 4 5.5
Unit - I 17 JavaScript

2]) array
toSource() Returns a string that represents the 4.0 4
source code of the array 6
toString() Returns a string that represents the 3 4
specified array and its elements
unshift("element1","element2 Adds one or more elements to the 4 5.5
") beginning of an array and returns the
new length
valueOf() Returns the primitive value of an 4 3
array

Methods
• chop() - Used to truncate the last character of a all strings that are
part of an array. This method is not defined so it must be written and
included in your code.
var exclamations = new Array("Look out!", "Duck!" )
exclamations.chop()
output: It causes the values of exclamations to become:
Look out
Duck
• grep(searchstring) - Takes an array and returns those array
element strings that contain matching strings. This method is not
defined so it must be written and included in your code.
words = new Array("limit","lines","finish","complete","In","Out")
inwords = words.grep("in")
output: of the array, inwords, will be:
lines, finish
• join(delimiter) - Puts all elements in the array into a string,
separating each element with the specified delimiter.
words = new
Array("limit","lines","finish","complete","In","Out")
var jwords = words.join(";")
output: The value of the string jwords is:
limit;lines;finish;complete;In;Out
• pop() - Pops the last string off the array and returns it. This method
is not defined so it must be written and included in your code.
words = new Array("limit","lines","finish","complete","In","Out")
var lastword = words.pop()
output: The value of the string lastword is:
Out

• push(strings) - Strings are placed at the end of the array. This


method is not defined so it must be written and included in your
code.
words = new Array("limit","lines","finish")
words.push("complete","In","Out")
output: The array, words, will be:
Unit - I 18 JavaScript

limit, lines, finish, complete, In, Out


• reverse() - Puts array elements in reverse order.
words = new
Array("limit","lines","finish","complete","In","Out")
words.reverse()
output: The array, words, will be:
Out, In, complete, finish, lines, limit
• shift() - Decreases array element size by one by shifting the first
element off the array and returning it. This method is not defined so
it must be written and included in your code.
words = new Array("limit","lines","finish","complete","In","Out")
word = words.shift()
The array, words, will be:
In, complete, finish, lines, limit
The string word will be:
Out
• sort() - Sorts the array elements in dictionary order or using a
compare function passed to the method.
words = new
Array("limit","lines","finish","complete","In","Out")
word = words.sort()
output: The value of words becomes:
In,Out,complete,finish,limit,lines
• splice() - It is used to take elements out of an array and replace
them with those specified. In the below example the element starting
at element 3 is removed, two of them are removed and replaced with
the specified strings. The value returned are those values that are
replaced. This method is not defined so it must be written and
included in your code.
words = new Array("limit","lines","finish","complete","In","Out")
words1 = words.splice(3, 2, "done", "On")
output:The value of words becomes:
limit, lines, finish, done, On, Out
The value of words1 is set to:
complete, In

• split(deliimiter) - Splits a string using the delimiter and returns an


array.
words = new String("limit;lines;finish;complete;In;Out")
var swords = words.split(";")
output: The values in the array swords is:
limit, lines, finish, complete, In, Out
• unshift() - Places elementa at the start of an array
words = new Array("finish","complete","In","Out")
word = words.shift("limit","lines")
Unit - I 19 JavaScript

output: The array, words, will be:


limit, lines,finish, complete, In, Out

JavaScript Boolean Object


The Boolean object is an object wrapper for a Boolean value and it is used
to convert a non-Boolean value to a Boolean value.

Boolean Object
The Boolean object is an object wrapper for a Boolean value and it is
used to convert a non-Boolean value to a Boolean value, either true or
false. If the Boolean object has no initial value or if it is 0, null, "", false, or
NaN, the initial value is false. Otherwise it is true (even with the string
"false"). All the following lines of code create Boolean objects with an initial
value of false:

var b1=new Boolean()


var b2=new Boolean(0)
var b3=new Boolean(null)
var b4=new Boolean("")
var b5=new Boolean(false)
var b6=new Boolean(NaN)
All the following lines of code create Boolean objects with an initial value of
true:
var b1=new Boolean(true)
var b2=new Boolean("true")
var b3=new Boolean("false")
var b4=new Boolean("Richard")
The Boolean object's properties and methods are described below:
NN: Netscape, IE: Internet Explorer
Properties
Syntax: object.property_name

Property Description NN IE
Constructor Contains the function that created an 4 4
object's prototype
Prototype Allows addition of properties and methods to 3 4
the object
Methods
Syntax: object.method_name()
Method Description NN IE
toString() Converts a Boolean value to a string. This 4 4
method is called by JavaScript automatically
whenever a Boolean object is used in a
situation requiring a string
valueOf() Returns a primitive value ("true" or "false") 4 4
for the Boolean object
Unit - I 20 JavaScript

JavaScript Date Object


The Date object is used to work with dates and times.

Date Object
The Date object is used to work with dates and times. To create an
instance of the Date object and assign it to a variable called "d", you do the
following:
var d=new Date()

After creating an instance of the Date object, you can access all the
methods of the Date object from the "d" variable. To return the current day
in a month (from 1-31) of a Date object, write the following:

d.getDate()

The Date object can also have the following parameters:

new Date(milliseconds)
new Date(dateString)
new Date(yr_num, mo_num, day_num [, hr_num, min_num, sec_num,
ms_num])

• milliseconds - the number of milliseconds since 01 January, 1970


00:00:00
• dateString - the date in a format that is recognized by the Date.parse
method
• yr_num, mo_num, day_num - the year, month or day of the date
• hr_num, min_num, sec_num, ms_num - the hours, minutes, seconds
and milliseconds
If you only use Date(), JavaScript creates an object for today's date
according to the time on the local machine. Here are some examples on
how to create Date objects:

Var d=new Date(“October 12, 1988 13:14:00")


var d=new Date("October 12, 1988")
var d=new Date(88,09,12,13,14,00)
var d=new Date(88,09,12)
var d=new Date(500)
The Date object's properties and methods are described below: NN:
Netscape, IE: Internet Explorer

Properties
Syntax: object.property_name
Property Description NN IE
constructor Contains the function that created an 4 4
object's prototype
prototype Allows addition of properties to a date 3 4

Methods
Unit - I 21 JavaScript

Syntax: object.method_name()

Method Description NN IE
Date() Returns a Date object 2 3
getDate() Returns the date of a Date object (from 1-31) 2 3
getDay() Returns the day of a Date object (from 0-6. 2 3
0=Sunday, 1=Monday, etc.)
getMonth() Returns the month of a Date object (from 0- 2 3
11. 0=January, 1=February, etc.)
getFullYear() Returns the year of a Date object (four digits) 4 4
getYear() Returns the year of a Date object (from 0- 2 3
99). Use getFullYear instead !!
getHours() Returns the hour of a Date object (from 0-23) 2 3
getMinutes() Returns the minute of a Date object (from 0- 2 3
59)
getSeconds() Returns the second of a Date object (from 0- 2 3
59)
getMilliseconds() Returns the millisecond of a Date object 4 4
(from 0-999)
getTime() Returns the number of milliseconds since 2 3
midnight 1/1-1970
getTimezoneOffset() Returns the time difference between the 2 3
user's computer and GMT
getUTCDate() Returns the date of a Date object in universal 4 4
(UTC) time
getUTCDay() Returns the day of a Date object in universal 4 4
time
getUTCMonth() Returns the month of a Date object in 4 4
universal time
getUTCFullYear() Returns the four-digit year of a Date object in 4 4
universal time
getUTCHours() Returns the hour of a Date object in universal 4 4
time
getUTCMinutes() Returns the minutes of a Date object in 4 4
universal time
getUTCSeconds() Returns the seconds of a Date object in 4 4
universal time
getUTCMilliseconds() Returns the milliseconds of a Date object in 4 4
universal time
parse() Returns a string date value that holds the 2 3
number of milliseconds since January 01
1970 00:00:00
setDate() Sets the date of the month in the Date object 2 3
(from 1-31)
Unit - I 22 JavaScript

setFullYear() Sets the year in the Date object (four digits) 4 4


setHours() Sets the hour in the Date object (from 0-23) 2 3
setMilliseconds() Sets the millisecond in the Date object (from 4 4
0-999)
setMinutes() Set the minute in the Date object (from 0-59) 2 3
setMonth() Sets the month in the Date object (from 0- 2 3
11. 0=January, 1=February)
setSeconds() Sets the second in the Date object (from 0- 2 3
59)
setTime() Sets the milliseconds after 1/1-1970 2 3
setYear() Sets the year in the Date object (00-99) 2 3
setUTCDate() Sets the date in the Date object, in universal 4 4
time (from 1-31)
setUTCDay() Sets the day in the Date object, in universal 4 4
time (from 0-6. Sunday=0, Monday=1, etc.)
setUTCMonth() Sets the month in the Date object, in 4 4
universal time (from 0-11. 0=January,
1=February)
setUTCFullYear() Sets the year in the Date object, in universal 4 4
time (four digits)
setUTCHours() Sets the hour in the Date object, in universal 4 4
time (from 0-23)
setUTCMinutes() Sets the minutes in the Date object, in 4 4
universal time (from 0-59)
setUTCSeconds() Sets the seconds in the Date object, in 4 4
universal time (from 0-59)
setUTCMilliseconds() Sets the milliseconds in the Date object, in 4 4
universal time (from 0-999)
toGMTString() Converts the Date object to a string, set to 2 3
GMT time zone
toLocaleString() Converts the Date object to a string, set to 2 3
the current time zone
toString() Converts the Date object to a string 2 4

Methods explanation:
• getDate() - Get the day of the month. It is returned as a value
between 1 and 31.
var curdate = new Date()
var mday = curdate.getDate()
document.write(mday + "<BR>")

The above code prints the day of the month.

• getDay() - Get the day of the week as a value from 0 to 6


Unit - I 23 JavaScript

var curdate = new Date()


var wday = curdate.getDate()
document.write(wday + "<BR>")
The above code prints the day of the week.
• getHours() - The value returned is 0 through 23.
var curdate = new Date()
var hours = curdate.getHours()
document.write(hours + "<BR>")
The above code prints the hours since midnight.

• getMinutes() - The value returned is 0 through 59.


var curdate = new Date()
var minutes = curdate.getMinutes()
document.write(minutes + "<BR>")
The above code prints the minutes past the hour.

• getMonth() - Returns the month from the date object as a value


from 0 through 11.
var curdate = new Date()
var month = curdate.getMonth()
document.write(month + "<BR>")
The above code prints the numeric value of the month.
• getSeconds() - The value returned is 0 through 59.
var curdate = new Date()
var seconds = curdate.getSeconds()
document.write(seconds + "<BR>")
The above code prints the seconds since the last minute.
• getTime() - The number of milliseconds since January 1, 1970. this
function allows you to manipulate the date object based on a
millisecond value then convert it back to the form you want. In the
example below, it is used to set a future expiration time of a cookie.
var futdate = new Date()
var expdate = futdate.getTime()
expdate += 3600*1000 //expires in 1
hour(milliseconds)
futdate.setTime(expdate)
• getTimeZoneOffset() - Time zone offset in hours which is the
difference between GMT and local time.
var curdate = new Date()
var offset = curdate.getTimeZoneOffset()
document.write(offset + "<BR>")
The above code prints the number of hours different between
your timezone and GMT. This value may change with daylight
savings time..
• getYear() - Returns the numeric four digit value of the year.
var curdate = new Date()
var year = curdate.getYear()
document.write(year + "<BR>")
Unit - I 24 JavaScript

The above code prints the numeric value of the year, which is
currently 2000.
• parse() - The number of milliseconds after midnight January 1, 1970
till the given date espressed as a string in the example which is IETF
format.
var curdate = "Wed, 18 Oct 2000 13:00:00 EST"
var dt = Date.parse(curdate)
document.write(dt + "<BR>")
• setTime(value) - Sets time on the basis of number of milliseconds
since January 1, 1970. The below example sets the date object to one
hour in the future.
var futdate = new Date()
var expdate = futdate.getTime()
expdate += 3600*1000 //expires in 1 hour(milliseconds)
futdate.setTime(expdate)
• toGMTString() - Convert date to GMT format in a form similar to
"Fri, 29 Sep 2000 06:23:54 GMT".
var curdate = new Date()
dstring = curdate.toGMTString()
document.write(dstring + "<BR>" + curdate.toLocaleString() +
"<BR>")
The above example produces:
Wed, 18 Oct 2000 18:08:11 UTC
10/18/2000 14:08:11
• UTC() - Based on a comma delimited string, the number of
milliseconds after midnight January 1, 1970 GMT is returned. The
syntax of the string is "year, month, day [, hrs] [, min] [, sec]". An
example is "2000, 9, 29, 5, 43, 0" for Sept 29, 2000 at 5:43:0. The
string is considered to be GMT. The hours, minutes, and seconds are
optional.
document.write(Date.UTC(2000, 9, 29, 5, 43, 0) + " ")
The above example produces:
972798180000

JavaScript Math Object

The built-in Math object includes mathematical constants and


functions.

Math Object
The built-in Math object includes mathematical constants and
functions. You do not need to create the Math object before using it. To
store a random number between 0 and 1 in a variable called "r_number":
Unit - I 25 JavaScript

r_number=Math.random()

To store the rounded number of 8.6 in a variable called "r_number":

r_number=Math.round(8.6)
The Math object's properties and methods are described below: NN:
Netscape, IE: Internet Explorer
Properties
Syntax: object.property_name
Property Description NN IE
E Returns the base of a natural logarithm 2 3
LN2 Returns the natural logarithm of 2 2 3
LN10 Returns the natural logarithm of 10 2 3
LOG2E Returns the base-2 logarithm of E 2 3
LOG10E Returns the base-10 logarithm of E 2 3
PI Returns PI 2 3
SQRT1_2 Returns 1 divided by the square root of 2 2 3
SQRT2 Returns the square root of 2 2 3
Methods
Syntax: object.method_name()

Method Description NN IE
abs(x) Returns the absolute value of x 2 3
acos(x) Returns the arccosine of x 2 3
asin(x) Returns the arcsine of x 2 3
atan(x) Returns the arctangent of x 2 3
atan2(y,x) Returns the angle from the x axis to a point 2 3
ceil(x) Returns the nearest integer greater than or 2 3
equal to x
cos(x) Returns the cosine of x 2 3
exp(x) Returns the value of E raised to the power of x 2 3
floor(x) Returns the nearest integer less than or equal to 2 3
x
log(x) Returns the natural log of x 2 3
max(x,y) Returns the number with the highest value of x 2 3
and y
min(x,y) Returns the number with the lowest value of x 2 3
and y
pow(x,y) Returns the value of the number x raised to the 2 3
power of y
random() Returns a random number between 0 and 1 2 3
Unit - I 26 JavaScript

round(x) Rounds x to the nearest integer 2 3


sin(x) Returns the sine of x 2 3
sqrt(x) Returns the square root of x 2 3
tan(x) Returns the tangent of x 2 3

Methods explanation:
Methods are invoked by lines like "Math.sin(1)".
• abs(a) - Returns the absolute value of a. The result value is 23 in the
example below.
resultval = Math.abs(-23)
• acos(a) - Returns the angle in radians that has a cosine of the
passed value. The value of "resultval" is 90 degrees.
resultval = (180/Math.PI) * Math.cos(0)
• asin(a) - Returns the angle in radians that has a sine of the passed
value. The value of "resultval" is 90 degrees.
resultval = (180/Math.PI) * Math.sin(1)
• atan(a) - Returns the angle in radians that has a tangent of the
passed value. The "resultval" will be almost 90 degrees.
resultval = (180/Math.PI) * Math.atan(100)
• atan2(x,y) - Returns the polar coordinate angle based on cartesion
x and y coordinates. The value is returned in radians. The "resultval"
will be 45.
resultval = (180/Math.PI) * Math.atan2(1,1)
• ceil(x) - Rounds up the value of "a" to the next integer. If the value
is a already whole number, the return value will be the same as the
passed value. The example returns 13.
resultval = Math.ceil(12.01)
• cos(a) - Returns the cosine of "a" specified in radians. To convert
radians to degrees, divide by 2*PI and multiply by 360. The example
below returns the cosine of 90 degrees which is 0.
resultval = Math.cos(90 * Math.PI/180)
• exp(a) - Returns Euler's constant to the power of the passed argument. This is the
exponential power. The example below will return a number between 9 and 10.
resultval = Math.exp(3)

• floor(a) - Rounds the passed value down to the next lowest integer.
If the passed value is already an integer the returned value is the
same as the passed value. The value returned in the example is 8.
resultval = Math.floor(8.78)
• log(a) - This function is the opposite of "exp()" returning the natural
log of the passed value. In the below example, 3 is the result.
resultval = Math.log(Math.exp(3))
• max(a,b) - Returns the larger value of a or b. The variable
"resultval" below becomes 5.
resultval = Math.max(5, 3)
Unit - I 27 JavaScript

• min(a,b) - Returns the lower value of a or b. The variable "resultval"


below becomes 3.
resultval = Math.min(5, 3)
• pow(a,b) - Takes the value of a to the power b. In the example
below the value 5 is multiplied times itself three times for a result of
125 which is placed in the variable "resultval".
resultval = Math.pow(5, 3)
• random() - Returns a random number between 0 and 1. To generate
a number from 0 to 9:
i1 = Math.round(Math.random() * 3)
• round(a) - Returns the value of a to the nearest integer. If the
values decimal value is .5 or greater the next highest integer value is
returned otherwise the next lowest integer is returned. In the
example below, 5 is returned.
resultval = Math.round(5.3)

• sin(a) - Returns the sine of "a" specified in radians. To convert


radians to degrees, divide by 2*PI and multiply by 360. The example
below returns the sine of 90 degrees which is 1.
resultval = Math.sin(90 * Math.PI/180)
• sqrt(a) - Returns the square root of a. the value of "resultval" is 5.
resultval = Math.sqrt(25)
• tan(a) - Returns the tangent of a value in radians which is the value
of the sine divided by the cosine.
resultval = Math.tan(0)

JavaScript String Object

The String object is used to work with text.

String object
The String object is used to work with text. The String object's
properties and methods are described below: NN: Netscape, IE: Internet
Explorer

Properties
Syntax: object.property_name
Property Description NN IE
constructor 4 4
length Returns the number of characters in a string 2 3

Methods
Unit - I 28 JavaScript

Syntax: object.method_name()

Method Description NN IE
anchor("anchornam Returns a string as an anchor 2 3
e")
big() Returns a string in big text 2 3
blink() Returns a string blinking 2
bold() Returns a string in bold 2 3
charAt(index) Returns the character at a specified position 2 3
charCodeAt(i) Returns the Unicode of the character at a 4 4
specified position
concat() Returns two concatenated strings 4 4
fixed() Returns a string as teletype 2 3
fontcolor() Returns a string in a specified color 2 3
fontsize() Returns a string in a specified size 2 3
fromCharCode() Returns the character value of a Unicode 4 4
indexOf() Returns the position of the first occurrence of a 2 3
specified string inside another string. Returns -1
if it never occurs
italics() Returns a string in italic 2 3
lastIndexOf() Returns the position of the first occurrence of a 2 3
specified string inside another string. Returns -1
if it never occurs. Note: This method starts from
the right and moves left!
link() Returns a string as a hyperlink 2 3
match() Similar to indexOf and lastIndexOf, but this 4 4
method returns the specified string, or "null",
instead of a numeric value
replace() Replaces some specified characters with some 4 4
new specified characters
search() Returns an integer if the string contains some 4 4
specified characters, if not it returns -1
slice() Returns a string containing a specified character 4 4
index
small() Returns a string as small text 2 3
split() Splits a string into an array of strings 4 4
strike() Returns a string strikethrough 2 3
sub() Returns a string as subscript 2 3
substr() Returns the specified characters. 14,7 returns 7 4 4
characters, from the 14th character (starts at 0)
substring() Returns the specified characters. 7,14 returns all 2 3
characters from the 7th up to but not including
the 14th (starts at 0)
Unit - I 29 JavaScript

sup() Returns a string as superscript 2 3


toLowerCase() Converts a string to lower case 2 3
toUpperCase() Converts a string to upper case 2 3

Methods
• big() - String is displayed in large format. (big tags)
document.write("This is BIG text".big())
Is the same as:
<BIG>This is BIG text</BIG>
Producing the following output:
This is BIG text
• blink() - String is displayed blinking. (blink tags)
document.write("This is BLINKING text".blink())
Is the same as:
<BLINK>This is BLINKING text</BLINK>
output:
This is BLINKING text
• bold() - String is displayed in bold characters. (bold tags)
document.write("This is BOLD text".bold())
Is the same as:
<B>This is BOLD text</B>
output:
This is BOLD text

• charAt(index) - Returns a string containing the character at the


specified location. The example returns the character "r".
myname = "George"
myname.charAt(3)

• fixed() - A string is displayed in Teletype format (teletype tags).


document.write("This is TT text".fixed())
Is the same as:
<TT>This is TT text</TT>
outptut:
This is TT text
• fontcolor(color) - String is displayed in the specified color.
document.write("This is RED text".fontcolor("red"))
Is the same as:
<FONT color="red">This is RED text</FONT>
output:
This is RED text
• fontsize(size) - String is displayed in the specified font from a value
of 1 to 7.
document.write("This is SIZE 5 text".fontsize(5))
Is the same as:
<FONT size="5">This is SIZE 5 text</FONT>
Unit - I 30 JavaScript

output:
This is SIZE 5 text
• indexOf(pattern) - Returns -1 if the value is not found and returns
the index of the first character of the first string matching the pattern
in the string. The example will return a value of 3.
myname = "George"
myname.indexOf("r")

• indexOf(pattern, index) - Returns -1 if the value is not found and


returns the index of the first character of the first string matching the
pattern in the string. Searching begins at the index value in the
string.

• italics() - String is displayed using the italics tags.


document.write("This is ITALICS text".italics())
Is the same as:
<I>This is ITALICS text</I>
output:
This is ITALICS text

• lastIndexOf(pattern) - Returns -1 if the value is not found and


returns the index of the first character of the last string matching the
pattern in the string.

• lastIndexOf(pattern, index) - Returns -1 if the value is not found


and returns the index of the first character of the last string matching
the pattern in the string. Searching begins at the index value in the
string. The example will return a value of 5.
myname = "George"
myname.lastIndexOf("e")
• link(href) - A string is displayed as a hypertext link.
document.write("Computer Technology Documentation
Project".link("http://ctdp.tripod.com/"))
Is the same as:
<A HREF="http://ctdp.tripod.com/">Computer Technology
Documentation Project</A>
output:
Computer Technology Documentation Project

• split(separator) - Splits a string into substrings based on the


separator character. In the below example an array called splitValues
is created. The splitValues[0] string will be "Day" and the
splitValues[0] string will be "Monday".
nvpair = new String("Day=Monday")
splitValues=nvpair.split("=")
strike() - String is displayed using the strikeout tags.
document.write("This is STRIKEOUT text".strike())
Is the same as:
Unit - I 31 JavaScript

<STRIKE>This is STRIKEOUT text</STRIKE>


output:
This is STRIKEOUT text
• sub() - String is displayed using the subscript tags.
document.write("This is SUBSCRIPT text".sub())
Is the same as:
<SUB>This is SUBSCRIPT text</SUB>
output:
This is SUBSCRIPT text

• substr(start, length) - Returns the string starting at the "start"


index of the string Continuing for the specified length of characters
unless the end of the string is found first. The example will return
"org".
mysite = "Comptechdoc.org"
myname.substring(12, 3)

• substring(start, end) - Returns the string starting at the "start"


index of the string and ending at "end" index location, less one. The
example will return "org".
mysite = "Comptechdoc.org"
myname.substring(12,15)

• sup() - String is displayed using the superscript tags.


document.write("This is SUPERSCRIPT text".sup())
Is the same as:
<SUP>This is SUPERSCRIPT text</SUP>
Producing:
This is SUPERSCRIPT text

• toLowerCase() - Returns a copy of the string with all characters in


lower case.
• toUpperCase() - Returns a copy of the string with all characters in
upper case.

JavaScript RegExp Object


The RegExp object is used to specify what to search for in a text

What is RegExp

• RegExp, is short for regular expression. When you search in a text,


you can use a pattern to describe what you are searching for. RegExp
IS this pattern. A simple pattern can be a single character. A more
complicated pattern consists of more characters, and can be used for
parsing, format checking, substitution and more.
• You can specify where in the string to search, what type of
characters to search for, and more.
Defining RegExp
Unit - I 32 JavaScript

• The RegExp object is used to store the search pattern.


• We define a RegExp object with the new keyword. The following code
line defines a RegExp object called patt1 with the pattern "e":

Var patt1=new RegExp("e");

When you use this RegExp object to search in a string, you will find the
letter "e".

Methods of the RegExp Object


The RegExp Object has 3 methods: test(), exec(), and compile().

test() : The test() method searches a string for a specified value. Returns
true or false
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.


Returns the text of the found value. If no match is found, it
returns null
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

Example 2:
You can add a second parameter to the RegExp object, to specify your
search. For example; if you want to find all occurrences of a character, you
can use the "g" parameter ("global").
.
When using the "g" parameter, the exec() method works like this:
• Finds the first occurence of "e", and stores its position
• If you run exec() again, it starts at the stored position, and finds the
next occurence of "e", and stores its position
var patt1=new RegExp("e","g");
do
{
result=patt1.exec("The best things in life are free");
document.write(result);
}
while (result!=null)
Unit - I 33 JavaScript

Since there is six "e" letters in the string, the output of the code above will
be:
Eeeeeenull

compile() : The compile() method is used to change the RegExp.


compile() can change both the search pattern, and add or remove the
second parameter.

Example:
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
patt1.compile("d");
document.write(patt1.test("The best things in life are free"));
Since there is an "e" in the string, but not a "d", the output of the code
above will be:
truefalse

Methods that belong to all objects


• toString() - Converts an object to a string. The syntax is shown below.
Radix is the base value for the conversion, which may be 10 for
decimal conversion. The value 1 is used for binary conversion, and 8
is used for octal conversion.
object.tostring(radix)

Dialog Boxes

• alert(message) - Displays an alert box with a message defined by the


string message. Example:
alert("An error occurred!")

• confirm(message) - When called, it will display the message and two boxes. One
box is "OK" and the other is "Cancel". If OK is selected, a value of true is returned,
otherwise a value of false is returned. An example:
if (confirm("Select OK to continue, Cancel to
abort"))
{
document.write("Continuing")
}
else
{
document.write("Operation Canceled")}

• prompt(message) - Displays a box with the message passed to the


function displayed. The user can then enter text in the prompt field,
and choose OK or Cancel. If the user chooses Cancel, a NULL value is
returned. If the user chooses OK, the string value entered in the field
is returned. An example:
Unit - I 34 JavaScript

var response=prompt("Enter your name")


if (response != null)
{
document.write(response)
}

Events & Event handlers


Events are actions that occur as a result of something of the
user do. For your script to react to an event you need to define an
event handler.

JavaScript defines five types of events, which are form, image,


image map, link, and window events. Events are associated with HTML
tags. The definitions of the events described below are as follows:

Form Events
• blur - The input focus was lost.
• change - An element lost the focus since it was changed.
• focus - The input focus was obtained.
• reset - The user reset the object, usually a form.
• select - Some text is selected
• submit - The user submitted an object, usually a form.

Image Events
• abort - A user action caused an abort.
• error - An error occurred.
• load - The object was loaded.

Image Map Events


• mouseOut - The mouse is moved from on top a link.
• mouseOver - The mouse is moved over a link.

Link Events
• click - An object was clicked.
• mouseOut - The mouse is moved from on top a link.
• mouseOver - The mouse is moved over a link.

Window Events
• blur - The input focus was lost.
• error - An error occurred.
• focus - The input focus was obtained.
• load - The object was loaded.
• unload - The object was exited.
Unit - I 35 JavaScript

Event Association
Events are associated with HTML tags. The definitions of the events
described below are as follows:
• onAbort - A user action caused an abort of an image or document
load.
Sy: onAbort=”handlertext”

• onBlur - A frame set, document, or form object such as a text field


loses the focus for input.
Sy: onBlur=”handlertext”

• onChange - Happens when a form field is changed by the user and


it loses the focus.
Sy: onChanget=”handlertext”

• onClick - Executes JavaScript code when a click event occurs. That


is when an object on a form is clicked (It is the combination of the
MouseDown and MouseUp events.)
Sy: onClick=”handlertext”

onFocus - A frame set, document, or form object such as a text field


gets the focus for input.
Sy: onFocus=”handlertext”

• onLoad - The event happens when an image or HTML page has


completed the load process in the browser.
Sy: onLoad=”handlertext”

A simple example to validate the user name size, which is


having minimum 6 characters.

<html>
<script>
function f2()
{
name=document.f1.t1.value;
alert(""+name);
if(name.length < 6)
{
alert("User name should have minimum 6 characters");
document.f1.t1.focus();//to move the control back to text box.
}
}

</script>
<body>
Unit - I 36 JavaScript

<form name=f1>
User name : <input type="text" size=20 name="t1" onblur="f2( )">
</form>
</body>
</html>

Mouse Events:

• onMouseDown- When the user depresses a mouse button.


Sy: onMouseDown=”handlertext”

• onMouseOut - The event happens when the mouse is moved from on top of a link or
image map

• onMouseOver - The event happens when the mouse is placed on a link or image map.

• OnMouseUp: When the user releases a mouse button.

Other Events

• onReset - The user reset the object which is usually a form.


• onSubmit - The user submitted an object which is usually a form.
• onMove- When the user or script moves a window or frame.
• onResize: When the user or script resizes a window or frame.
• onSelect: When a user selects some of the text within a text or textarea field.

Ex: <input type=”text” “value=” “name=” “valuefield” onSelect=”selectstate()”>

A simple example for onblur


<html>
<script>
function f2()
{
name=document.f1.t1.value;
alert(""+name);
if(name.length < 6)
{ alert("User name should have minimum 6 characters");
document.f1.t1.focus();//to move the control back to text box.
}
}
function f3()
{
alert("hai");
}
</script>
<body>
<form name=f1>
User name : <input type="text" size=20 name="t1" onblur="f2( )">
password : <input type="text" size=20 name="t1">
<img src="C.gif" width=100 height=100 onAbort=alert("hai")>
Unit - I 37 JavaScript

</form>
</body>
</html>

A simple example on mouse movements.

<html>
<script>
function f2()
{
name=document.f1.t1.value;
alert(""+name);
if(name.length < 6)
{ alert("User name should have minimum 6 characters");
document.f1.t1.focus();//to move the control back to text box.
}
}

function fun()
{
alert("u moved the pointer out of the image");
}

</script>
<body>
<form name=f1>
User name : <input type="text" size=20 name="t1" onblur="f2( )">
password : <input type="text" size=20 name="t1" onKeyUp="fun()">
<img src="c.gif" onMouseOver="fun()">
<br>
<img src="glorious.gif" onMouseOut="fun()">
<input type=button value="onclick" onDblclick="fun()">
</form>
</body>
</html>

Examples for Advanced JavaScript Programs

1. Write a program to detect the visitor’s browser and version of it?

<html>
<body>

<script type="text/javascript">
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
document.write("Browser name: "+ browser);
document.write("<br />");
Unit - I 38 JavaScript

document.write("Browser version: "+ version);


</script>

</body>
</html>

2. Write a program for more details about the visitors browser?

<html>
<body>
<script type="text/javascript">
document.write("<p>Browser: ");
document.write(navigator.appName + "</p>");

document.write("<p>Browserversion: ");
document.write(navigator.appVersion + "</p>");

document.write("<p>Code: ");
document.write(navigator.appCodeName + "</p>");

document.write("<p>Platform: ");
document.write(navigator.platform + "</p>");

document.write("<p>Cookies enabled: ");


document.write(navigator.cookieEnabled + "</p>");

document.write("<p>Browser's user agent header: ");


document.write(navigator.userAgent + "</p>");
</script>
</body>
</html>

3. Write all the details about the visitor’s browser?

<html>
<body>

<script type="text/javascript">
var x = navigator;
document.write("CodeName=" + x.appCodeName);
document.write("<br />");
document.write("MinorVersion=" + x.appMinorVersion);
document.write("<br />");
document.write("Name=" + x.appName);
document.write("<br />");
document.write("Version=" + x.appVersion);
document.write("<br />");
Unit - I 39 JavaScript

document.write("CookieEnabled=" + x.cookieEnabled);
document.write("<br />");
document.write("CPUClass=" + x.cpuClass);
document.write("<br />");
document.write("OnLine=" + x.onLine);
document.write("<br />");
document.write("Platform=" + x.platform);
document.write("<br />");
document.write("UA=" + x.userAgent);
document.write("<br />");
document.write("BrowserLanguage=" + x.browserLanguage);
document.write("<br />");
document.write("SystemLanguage=" + x.systemLanguage);
document.write("<br />");
document.write("UserLanguage=" + x.userLanguage);
</script>
</body>
</html>

4. Write a program for creation of animation button?

<html>
<head>
<script type="text/javascript">
function mouseOver()
{
document.b1.src ="b_blue.gif";
}
function mouseOut()
{
document.b1.src ="b_pink.gif";
}
</script>
</head>

<body>
<a href="http://www.pvpsiddhartha.ac.in” target="_blank">
<img border="0" alt="Visit PVPSIT!" src="b_pink.gif" name="b1" width="26" height="26"
onmouseover="mouseOver()" onmouseout="mouseOut()" /></a>
</body>
</html>

5. Write a program for simple times ?


Unit - I 40 JavaScript

<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('5 seconds!')",5000);
}
</script>
</head>
<body>
<form>
<input type="button" value="Display timed alertbox!" onClick = "timedMsg()">
</form>
<p>Click on the button above. An alert box will be displayed after 5 seconds.</p>
</body>

</html>

6. Write a program for Timing event in an infinite loop – with a stop button?

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function stopCount()
{
clearTimeout(t);
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onClick="timedCount()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form>
<p>Click on the "Start count!" button above to start the timer. The input field will count
forever, starting at 0. Click on the "Stop count!" button to stop the counting.
Unit - I 41 JavaScript

</p> </body>
</html>

8. Write a program for creating a digital clock?

<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}

function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
</head>

<body onload="startTime()">
<div id="txt"></div>
</body>
</html>

You might also like