dom
dom
JavaScript-II 459
460
an other windows. every a in
after button
the
on and
all parameter. buttons. function
windo open user parameter. field functionstop
behind other
that are the history. entry clicking
window. Cancel history. or
windows to all
from window. frame. it
message places Id ld of
coordinates. text expression
coordinates. or
page by attributes. amounts. amounts. expression
by andfontPage line coordinates. to
visited
current the referenced
referenced amounts. Similar
current several object the and OK in object
within one
a
presents
DESCRIPTION in window it the
and places pixel
window.
pixel pixelpixel
the
URLS window. in specified a invokes the milliseconds.
the if Window backward message,
buttons. window. Window
the is action message forward pixel
page. pixelspecified
within window
window counter specified specified specified invokes
and of and the
details browser that current homespecified specified continuously
looping window the for clickable milliseconds. the
details
nested of box step a step a that of
browser delaywindow. with with
process the the the in in
if Properties with the the Methods
URL window the
object. dialog one the one by by to timer timedownloading
any)
contain from interval timeoutboxspecified to by to window box to
of window current window
window windovw
window OKwindow window window
window specified
containing positioned printing that
(if window. bar
screen alert dialog dialog
and in time of
parent focus interval
thatframes of the the new timer one List
status List an OK
button. the Cancel the the
object
the off off thea
windows. the the thethe a the
theDisplays the anyToolbar.-
the Displays Removes Display a Scrolls a a of
of object window. the
current
thetopmost frame. -
18.1 Brings TurnsTurns Closes FocusesBrings Moves
Moves
Brings Opens Starts Resize
Resize Scrolls
Starts Stops 18.2
Startsdelay
delay
number to to and
history of
reference Table
locationthe reference textthe window or Table SetTimeout
("ExprORFunc",|
the Setinterval
("ExprORFunc'",
of
the the of creator the to
a name a a Specifies Reference argN]) delay
delay
[,argl,..,[,argl,..,
argN)
Specifies
Contains Returns Returns Returns desktop. Current confirm
("message") ","name'",prompt
open
("url ("message",
The The METHOD
alert
("message"") clearinterval(Id)
clearTimeout
(Id) "defaultReply'")
resizeBy
(x,y)
(x,y)scrollBy
(x,y)
resizeToscrollTo
(x,y)
(x,y) "attributes'")
moveBy
(x,y)moveTo JavaScript-
forward
()
location back
() blur
() () focus
close () home
() ()
print Stop
()
history
length opener
parent
Sereen
status window
name
top
object
name,
property ).Here
argN]
, 461
Internet.
Ox Go
open
window
a ]D:\Bak\Colel-1O\LPP/nternet-2k7chapter20% Address#]el-10\LPP\lnternet-2k7\chapter20\1081_b.html
and objects
javascript Computer
My browser
to browser
Computer
eMy
thename Microsoft
Help Explorer
Iools
Help thelinks
specifying Iools
Knowledge
of a
ina
object use bar
in
viewed
Internet
of yiewed
the bar statusFavortes
([argl,
object Favorites
Microsoft anyfollowing
status window.
ankurWhen When
the in
data View
window
by between by
object methodthe Displaying
Edit designed
View
Window- Click Microsoft
"Welcome
JavaScript"
to Address new Edit
File Google
Yahoo
window.property_name
in Eile Done
in of
window the the
message
l
a
eNew it
window. in
used link
property optional.
are
theis </title
bar </hl>
the www.microsoft.com')">
period by
". Onclick
"display('http:/Iwww.google.com')>
= )>
of methods ankur open
properties
A
status
argdisplays
arg2,....a.rgN
arg1,
uments status
objects
will
Open
"display(http://www.yahoo.com"
the
<script bywindow.status=*designed
javascript">
language= javascript
window.open(url
,url,
"height=600, to
links
as that in that
HTMLCode
theproperty
itacceSs
set
occess order
to
accessScript
status
window. PROGRAM:1ctitle>Displaying
| data
display0
function >
onload="display0
cbody
of
Script
language=javascript"> following
<Script
</title>
<h3
onclick HTML
Code
=display(http:/
the youInexample.
Windowfunction
display(url) width=800,scrollbars=yes");
<u>
Google
</u><{h3>
<usMicrosoft</u></h3
Knowledge <u>
Yaho0
</u></h3>
can the
fol owed
by.
So,name.
can
Siyoumilary,
Help
Not1081-epadSearch
<iscript>
<hl>
2:
PROGRAM
1081
b-
Help New
Notepad
Search <head><title>
of
any
Click
<{script>
=
onclick JavaScript-II
Edt <ht<head>
ml> </html>
</head> </body> Sn> k/hl>
For Fie
}
Edit <html>
} --> <{head>
<body> <h3 <h3
body>
Kihtml>
Fie
the
When the user clicks on any of the links (say Google),objectdithatsplay( )function is
Anew window is opened using open( )
method of window
parameters. The
that link. The open( ) specifies method contains three parameter firstdisplays the invoked
the url whose contents are to be displayed. The second
window and the third parameter is a string that specifies the attributes specifies
attributes include WIDTH, HEIGHT, TOOLBAR,
MENUBAR.
of
STATUS,
thhe para met
the er conteisS
new name Specif egi he
Window
RESIZEABLE etc. The firsttwo specifies width and height in pixels and
the
can be set to either Yes or No. If Yes the attributes will be displaved else
rememberthat the various attributes must be separated by commas and
must be separated by = sign.
PROGRAM 3: Script that prompts you to enter two number
each
remaiSCROL BARS
not.ninOne
g:
attribute atrbes
Thes
and alert
according to specified operation. the resu
<html>
<head<title> Alert </title>
<script language = "JavaScript">
<!-
var fnum, Snum ;
£unction calculate (num)
{
fnum = prompt ("enter first number ".0);
Snum = prompt ("enter second number .0).
switch (nun)
{
case 1! : S = parseInt (fnum) +parseInt
alert ("sum is " + s); (snum);
break i
case 2! : alert ("multiplication is "+ (fnum*
break; *gnum) )
default : alert ("subtraction is "+ (fnum- snum)).
</script>
</head>
<body>
<hl> Operations </hl>
<h3 onclick = "calculate ("1') "> <u>Sum</u> </h3>
<h3 onclick = "calculate( '2)"><u> Multiply</u> </h3>
<h3 onclick = "calculate('3')"> <u> Subtract </u></h3>
</body>
</html>
On viewing the script in aweb browser, you will get the desired output. When the uscr
clicks on any one of theoperations, the calculate( ) function is called and required value (n cs
of sum = 1) is passed to variable num. The user is then prompted to enter the two numbers a
appropriate calculations is performed based on the value of the num. This result is displayeo
dialog box. 462
JavaScript-ll
is
parselnt(Ofunction used to
The
NOTE:willbe concatenatedinsteadconvert a sting into
of addition.
PROGRAM4.Script to transit integer. If it is not used then
the images aiter a the
contents
head><title>Transit images </title>
chtmls
specified time interval.
<Script
<!-
var
lpic=new
anguage="UavaScri
Array
pt"
var j = 0;
Function rotate( ) ("picl.jpg", "pic2.jpg",
{
aewindow. document .banner:
"pic3.jpg"):
s.src=pic[j];
if (j>1)
j=0;
else
j++;
4Ä=getTimeout ("rotate()", 1000):
function stop()
{
clearTimeout (id) ;
</8cript>
</head>
cbody>
img src = "picl.jPg" name =
<hr>
"banner" ,
<input
<input type
type="button"
= "button "
value = start" onclick= "rotate() y
value = "stop" onclick = "stop ( )">
</body>
</html>
NAME
set
to
Yellow backgroundfor the document object we write
order
in document.bgColor "yellow";
So
methods of the document object
access the
youcan
Similarly
J ocument. . method( [argl1, argN])
[window..
accessthe clear( )
method of the document object document . clear().
to the
Soin
order
HTML contents of
current document.
clearthe
will
It
5: Script that changes the text color of the document after aspecific
PROGRAM
interval.
Color Change -Miciosoft Internet Exploter
F1009-
Notepad Fle Edit View Favontes Ioola Help
Hep
Search
fe
f
Change
</titlex Addre ) el101LPPNntenet-2k71chaplei2011089_ahiml Go
l<html> Color
language=javas
<title> cript">
Lhead> "blup.
cscript (black", "red',
<l- ne Array
Var color=
"green).
function0,change_color ()
var i =
window.document. fgColor=colorft):
Color of text changes
if (0>3)
after 1000 milliseconds.
else
("change_color ()", 1000).
serTimeout
-->
</script>
<body
</head>onload="change_color0*>
changes after
<hr>
'center'> Color of text
align=milliseconds. </hl>
chl 1000
MyComputer
<hr 1Done
<jbody>
</html> onload eventhandleris executed
browser, the
document is loaded in a web
color ofthe HTML document after
After the HTML function. It changes thetext
that invokes the change_color
)
linkclicked.
1000 milliseconds automatically. window onthe basis of
write the contents into a new
PROGRAM 6: Script to
<html> Contentg </title>
<head><title> Display
<sCript language="JavaScript">
<!-
JavaScript-II
width = 800
colordepth =32
pixeldepth = undefined
e] Done
My Computer
JavaScript-I 471
used properties and methods, associated with
Some of the commonly
PROPERTYNAME
DESCRIPTION
String object are:
Returns the length of string in characters.
length methods to
Used to assign new properties and
document. future instances of
prototype created in the current a
Table 18.12 List of properties of String object sting va
PROPERTYNAME DESCRIPTION
Returns acopy of a string embedded within <a> tag set
anchor'name")
Displays text as if embedded in a <big> element.
big ) Display text as if embedded in a <blink> element.
blink()
bold( )
Display text as if embedded in a <bold> element.
charAt(Index) Returns a character at the specified position which is passed as a parameter.
charCodeAt(Index) Returns a number of decimal unicode value at the specified
passed as parameter.
Appends the strings to the current string object.
position whichi
concat(string2)
fixed() Display text as if embedded in <tt element.
indexOf
Returns the position of the first Occurrence of one string inside
another.
(searchstring [Index])| However, if you want to begin search at a particular index
specify Index parameter. If there is no match, -1 is returned. then you have to
lastIndexOf It is similar to indexOf ) method but begins all searches from the end of string
(searchstring [Index) or some index position.
match (regexp) Searches the string for the regular expressi0n passed as a parameter and rat
any matches.
replace(regexp, Same as above except that instead of returning any matches it replaces any
newstring) matches with newstring.
search (regexp) Searches the string for the regular expression passed as parameter and retuny
the index of first match.
split(delimiter[,limit]) Splits a string into an array of substrings based on delimiter or regular expressian
The optional parameter Iimit is an integer that restricts the number of iens
converted into array elements.
substring(start,end) Returns a part of a string that is extracted from the start position and ends jus
before end position specified using end parameter.
toLowerCase ) Converts the string as a string of lowercase characters.
toUpper Case( ) Converts the string as a string of uppercase characters.
toString() Returns the string value of object.
valueOf( ) Same as tostring (0.
112:
PROGRAM
Script to show the manipulation of various methods of the string object.
String
FI06 - Notepad
Heb Fle E Operation-Micsooft
Vew Fgtes
Intesnet Eploe
Sesrch
</title></head> Ise
Fe
E Operations
chtml>
cheadctitle
String
Javas cript"
cbody> language= str length=21
str=Welcome to Javascript
script length) str charAt (4) =o
display('str.length =+ str. charAt (4)):
('str.charAt (4) = + str. str. charCodeAt (4) = 111
("str.charCodeAt (4) = + str. charCodeAt (4):
display ="+ str. IindexOf (c", 5): str indezOE (c', 5) = 16
display ("str.indexof (c', 5) str.indexOf (c):
display ((str.indexof (c):=*+ str indezOf (c) =3
display (('str.lastindexOf ('e)
= + str.lastindexOf (c);
display ("str.substrina (2, 7) ="
+str.substring(2,7): str lastindezOf ('c) = 16
display ('str.toLOWerCase
( ) = +str.toLOWerCase ( )): str substrng (2, T) = lcome
display
str.split (" ): str toLowerCase
i++)
s = (i=0; i<s.length; "]---"+ s[D): ()=#icome to jar2scnpt
split [0]---Welcome
for ("split ["+i+
display (d) split [1]---to
function display
document.write (d+"<br) split [2]---Javascnpt
</script>
</body> TDone
</html> 9My Conputer
JavaScript Code When viewed in a browser
PROGRAM 13: Seript to display a message in a status bar such that one character is
displayed at a time.
</script>
</head>
<body onload = "scroll(0">
<hl> See the status bar for effect <{hl>
</body>
</html>
e]Welcone to Javasc eMy Computet
On viewing the HTML document in a Web browser, you will get the desired output. The
message Welcome to JavaScript will be displayed in the status bar such that one character is
displayed at atime.
JavaScript-II 473
o i l tinobjcct that is used to work with date andI i
l n i N W lates is as follows. time in
Nane new Date ([parameters]) ; soripts.The
AMNYNCt tO aspecific date or time using one of the
w
\iti ewate (milliseconds) ; Milliseconds shouldibe a number fol owing ways:
iEilliseonds relative to zero hours on January 1, 1970.
AT
YA
new Date (yY, m, dd) ;
new Date (yy, mm, dd, hh, mm, s8);
representing
vRN neN Date ("month d, yYYY");
vAr new Date ("month dd, yyyY hh:mm: ss");
object áre:
S r rthe commonly used methods associated with Date
DESCRIPTION
METHOD
getate,setDate( ) gets/sets the day of the month. (1 to 31)
getDayt ), setDay( ) gets/sets the corresponding day of the week. Value returned is
between 0 to 6. (0-Sunday, 6-Saturday) Integer
getHours( ), setHours() gets/sets the hour of the day. Value returned is Integer between 0to 23.
gets/sets the minute of the day. Value returned is Integer between 0to 59.
getMinutes( ), setMinutes( )
gets/sets the month of year. Value returned is Integer between0 to 11 (0.
getMonth(),setMonth()
January, 11-December).
getSeconds(), setSeconds() gets/sets the seconds past the nearest full minute. Value returned :.
integer between 0 to 59.
getTime( ), setTime() gets/sets the time in milliseconds.
getFull Year( ),setFull Year() gets/sets all digits of the year.
returned is
getYear(),set Year() gets/sets the number corresponding to a year. Value
Integer between 0to 99 for yearsbetween 1900 to 1999; 4-digit integer
starting from 2000 for years>>2000.
offset from the Universal
getTimezoneOffset ( ) Gets the number of hours the current time is
Time (GMT).
conventions.
toGMTString( ) Converts date to astring, using the GMT
locale's conventions.
toLocaleString( ) Converts date to a string, using the current
time as date, zone and time.
toString( ) Gets a string representing the specified
number of milliseconds since zero
parse() Gets a string date value that holds the
hours on January 1, 1970.
JavaScript-lI
Year(). setUTCHours( ), setUTCMilliseconds(
setUTCFull
setUTCSeconds() are same
as their
counter parts but they ),works with
setUTCMiunivers¡l
nutes (),(UTC)
takes
theformat
Day Month Date, hh, mm, ss UTC year.
of Date object by
mmethods
setUTCMont h (),
time which
accessthe
Youcan thenthe method name. So it is
(.) and generally specifyingwrittenthe as,object name Date followed
period
bya ate.method ([arg1, argN] )
14:)Scriptto
display current time in the title bar of the
Program
A Time browser's window.
1111_a-Notepad
Help
20:52:44- Mictosoft Inteinet Explores
File Edil
Seach Vew Favcites gcs
Fle Edk Function </title> Address ) Hep
ehead><title> Date
chtml>
cscript language=javascript">
function disp_time)
0
Watch
18ak\Colel10LPPJrier et-Z7chasis ,d
d= new
Date ():
time in title bar
d.getHours ():
hr = d.getMinutes ():
=
mi d.getSeconds ():
sec =
document.title = Time + hr + ".
+ mi+ ,+ sec;
setTimeout (disp_time0", 1000):
</script>
</head>
"disp_time0>
cbody onload =
chl> Watch time in title bar </h
</body>
</html>
Done
9 My Computer
On viewing th HTML
document in a web browser, you
the title bar of the browser's window. will get the current time listed in
18.1MATH OBJECT
a The Math object is a built-in
object that is generally used to perform
trignometric) operations. Unlike, the String and Date object there is no mathematical (mostly
object. This is because all the need tÕ
of commonly used methods and properties are static members of Math create Math
properties and methods associated with Math object are : class. Some
ero
PROPERTY NAME PURPOSE
E
LN2 Returns Euler's Constant e =
LN10 Returns natural logarithm of2.71828182
2
ars( ). LOG2E Returns natural logarithm of 10
Date( ). LOGI0E Returns the log base-2 of Euler's
Returns the log base-10 of Euler'sconstano
Returns the value of t constant
414
JavaScript-I 475
n.
number
(y-x))4rgenerally
generate clientWidth/2)
to
equal
n the
point
(x,y) number
to specifying
Math.random()
to
equal want* is
it
object you So image.
to
line orthan if
name.
objectand by
Math aby greater than
or
object another
.(angle))+((docum
((document.bo
formed method
of less y Math Iand
Math.round )argN]
npower of 1and (
Properties
ofTable is yandpower O
of between
Math
n angle
of that is
that methods or around
n
of n radians)
radians) integer to integer x thebetween n
0
property
0.5 of
radians) raised of of
2
of of
n
of
radians)
of andnumber
y
to n
integer
of
of methods
radians) value </title>
rootroot List value (in higher raised
number radians) of formula, image ">
(in E lower
n x nof List returns the )+
(in arctangent n of
of of
smaller nearest "JavaScript (angle)
square 18.
square I5 cosine
absolute
DESCRITION sine
(in nextof valuenextlog greater ofxrandom root(in 18.16 andthen an
arg2,
cosine natural (in tangent
thethe arc arc
anglethe the the the the
value
to sinesquare properties
Table
the
always
use
and rotateImage
Returns
Returns Returns
Returns
Returns Returns
Returns Returns
Returns
Returns Returns Returns
Returns Returns
Returns Returns
n Returns
Rounds Return Return function
Math.property_name
then () ([argl,
Math.method
*Math,cos
= *Math.
sin
period to Rotating
y access Script =language()rotate
Math.random()
to
x
from a ((175
((175
by :15
canfollowed
numbers <head><títle>
0;=
angle
NQRT
1_2 You PROGRAM function
METHOD atan2(.
y) pow(x,y) <script =
asin(n) floor(n) max(x.
y) min(x.
y) round(n)sqrt(n)
)random( ypoB
XpOs JavaScript-
SQRT acos(n)
abs(n) atan(n)ceil(n) exp(n)
cos(n) login) sin(n) tan(n) Math <html>
:NOTE
as,