You are on page 1of 103

f Chapter Outcomes...

I
~ ~=:-:::~:-=--:-:--------_:_---____:.___J
00 Create object to solve the given problem.
00 Develop JavaScript to implement the switch-case statement for the given problem.
00 Develop JavaScript to implement loop for solving the given iterative problem.
00 Display properties of the given object using getters and setters.
00 Develop program using basic features of JavaScript for the given problem.

I .Learning Objectives...
00 To understand Basic Concepts of JavaScript
00 To learn Varia bles, Expressions, Operators, Loop Statement etc., in JavaScript

•I•• INTRODUCTION
• ( A script is a small piece of program that can add interactivity to the website. For example, a script
could generate a pop-up alert box message, or pr9vide a dropdown menu. This script could be
JavaScript or VBScript. J
• !]. script language is a simple programming language with which you can write scripts. A scripting
language is a form of programming language that is usually interpreted rather than compiled.]
• Conventional programs are converted permanently into executable files before they are run. In
contrasqprograms in scripting language are interpreted one command at a timel
• Scripting languages are often written to facilitate enhanced features of Web sites. These features are
processed on the server but the script in a specific page runs on the user's browser.
• [ JavaScript, ]script, Perl, PHP, Python, VBScript are the most popular examples of scripting
Languages.J
Client Side Scripting and Server Side Scripting:
J There are two types of scripting
languages based on where do they
exists or run as shown in the Fig. 1.1.
• Scripts is one of the scripting
language that runs on the client
machine rather than running from
the code through the server thus • JavaScript - Java Server Page (JSP)
making the response of the request • VBScript -ASP
faster than running the code through - PHP
server machine. Fig. 1.1: Types of Scripting
(1.1}
,'fJ Jo: I ('

Basics of JavaScri t Pro rammin ,t


1.2 Client Side Scri pting Language 1.3 --( Basics of JavaScript Programming

Ii:~.
1

1. Client Side Scripting: . . b er


npts 1s a rows ·
J Th e server is where the Web page and other content The server sends pages to the user/client
~ In client side scripting the environment use d to run sc ~ de i's transferr ed from th on request.
/' . ter The source co e Web The process of server-side scripting is given below, (See Fig. 1.3):
V'" The processing takes place on the end users compu · . h b
. d d' ectly int e rowser.
server t o the user 's computer over the internet an run Ir Step 1 The web browser sends a request for a particular web page of a web site to web server
The process with client side scripting is given below (See Fig. 1.2): . hosting that site.
· I web page of a web site to the web serv Step 2 The web server searches for the page in directory containing web pages for the website.
vStep 1 The web browser sends a requ est fo r a pa rt1cu ar er
hosting that site. . . . Step 3 : On find ing the requested page. the Web server collects the content, (code + HTML) of the
~ep2 The web server sea rches fo r the page in directory containing web pages for the web site. Web page.
~ ep3 : On findi ng the requested page. the web server collects the HT~L of th e web page. step 4 : The web server then parses the content to produce HTML.
.,.,--Step4 : The web server sends the HTML to the requesting browser whi ch then pa rses it to develop step 5 : The HTML stream is sent back to the requesting browser which then parses it to develop the
the visual presentation of the page. visual presentation of the page.
Web s,1e Drreclory / The use of HTML form s or clever links allow data to be sent to the server and processed. The results
/ So cli ent side scripting is used
to make Web pages cha nge -~!.--- - - -----i- .nlml I n1m Weo pages- - - . i may come back as a second Web page.

~ ~ ~~ ~
A user's request is fulfilled by running a script directly on the web server to generate dynamic HTML
after th ey arr ive at the
browser. pages. This HTML is then sent to the client browser.
Web Server
/ It is usually used to provide
·~ It 1s usefu l for maki ng pages a 4
interactive web sites that
bit more interesting a nd user- ~ 1

in terface to databases or
J( Web s,le Drreciory
fr ie ndly.
other da ta stores on the
~ ~ ~ ~
• ( It can also provide usefu l ~S-'(,'e
"rverJ
l = = 23 - - - - ~ - Dynamic Web pages - - + f

gadgets such as calculators.


server. '
I ~ ~- [~
clocks et~ but on the whole is / Some exa mples of server Weo
side scripting are PHP.
used for appearance and
ASP.Net in C#, C++. or
in teraction.
Visual Basic.
Fig. 1.2 shows concept of client weoBrowser Some languages such as
side scripting. j,_ -
Fig. 1.2: Client Side Scripting C+ +, C#, Java were not
/ [Jhe scri pti ng language needs to be enabled on the client computer]Any la nguage ru nni ng on a client des ig ned specifi cally for
devi ce that in teracts wi th a remote service is a client side language. the task. but are now often
/ Exa mples of client side scn pting languages are JavaScript (p rimarily). HTML", css· etc. used for application-level
web services.
i;
Advantages of Client Side Scripting: Web Browser
Fig. 1.3 shows concept of
(i) Allow fo r more interacti vity by imm edia tely responding to users' actions. Fig. 1.3: Sener Side Scripting
server side script ing .
.yr( Execute quickly beca use they don 't require a trip to the server. Adv an tag es of Server Side Scripting:
~ ii i) May improve the usability of Web sites fo r users whose browsers support scripts.
~ More secure than client side scripting.
(iv) Ca n give developers more control over the look and behavior of th eir Web wi dgets. .Afi) Faster as it ru ns on server which is highly configured machine.
(v) Ca~ be su bstituted with alterna tives (for exa mple, HTML) if users' browsers do not support Disadvantages of Server Side Scripting:
scnpts. Jrr It requ ires the scripting software to be installed on the server. . .
..__)vi) Are reusable and obtainable from many free resources such as Hotscripts.com and .,)if Users have to wait as every time page is submitted to server. thmgs go worse when internet
Javascript.com. connection 1s slow.
Disadvantages of Client Side Scripting: om arison between Server Side and Client Side Seri tin s:
.....,,{!) Not all browsers support scripts, th erefo re, users might experience er rors if n It t' have ~ ~ Sr~.~No~._j_~~~~ C~ll~e~n~tS~l~de~Sc~ r l~~:--:~~-+-:::--:-;----·~' ~·~ ~~-S~ld~e~S~~~~~=-=-:-:-4
been provided. o a erna ives /"?' 1. This script executes on client-side, (on user On other hand this scr ipt executes on server -
..._,fn) Different browsers and browser versions support scripts different! th us more quality co mputer where browser running) so called side, (on computer where web site running)
ass urance testing is required. y. client side scri tin so called server side scri t in .
J iii) More development time and effort might be required. (if the scripts are nor alread available 2. Less secure. This is more secure than client side scr ipting
through other resources). Y as business logic and code written is not
(iv) Developers have more control over the look and behavi or of th · w b 'd visible to user.
·· I · ·f b . elf e w1 gets; however.
usa b1ht y prob ems ca n anse I a We widget looks like a standard control but behaves differently 3. It runs on client-side thus if user computer Faster as it runs on server wh ich is h ighly
or VJ Ce-versa. is slow scri t will also work slow! . confi ured m ach ine.
2. Server Side Scripting: 4. JavaScript OQuery), VBScript are widely used PHP, ASP.NET, JSP et c technologies are
./ In server-side scripting the environment is used to runs a script is a wru, server. for this ur ose . wide! used for this ur ose.
,.~ Basics al JavoScn I Pro rarnrnt

m lNTRODUCI'ION TO JAVASCRIPT
A scripting language developed by Brendan Eich at
. Netscape to enable Web authors to desi
..__
&n
Th e followrng table shows the different versions of javascript and ECMA and their supported
browsers·
interactive sites.
. . d n !lie wer. It 1s used to enhance HTML pa I Year JavaScript l!CMA Supported Browser
Javasa·ipt OS) is a sc1iptmg languages, pnmanly use &es 1996 1.0 Netscape 2
and is com monly found embedded in HTML code l l I 1997 ECMAScript 1 IE4
h t can be embedded mt 1e 1eade r of your w b
JavaScript is an easy -to-use programming lang uage t a
page JavaScript is an important language because it is a
bb
language of th e We rowser'_]
.
:--,, e
I 1998 1.3 Netscape 4
1999 ECMAScript 2 IE 5
It can enhance the dyna mi cs and 111. . f
teract1ve eatures of your page by allowmg you to perfiorrn
calcula:1ons. heck fo rms. wri te 111 teractive games. add specia l effects. customize graphics 2000 ECMAScnpt 3 IE 5.5
se lections. and create secunty passwords and more. 2000 1.5 Netscape 6
Javas ript is an object- based sc.riptmg language whose interpreter is embedded inside web browser 2000 1.5 Fi refox 1
software . such as Microsoft Internet Explorer. Mozilla Firefox, Opera and Safari . 2009 ECMAScn pt 5 IE 9 (Except "use strict")
This allows scripts ntained in a web page to be mterpreted when the pa ge is loaded in the browser 2011 1.8.5 Firefox 4 (Except lead ing zeroes in parselnt)
f-
to provide fun ct iona lity and dynam ic effe ts. 2012 IE 10
Before the in troduct ion of JavaScript. web page fun ctionality requ ired the browser to call upon 2012 Chrome 23
"server side" s ripts . resident on the web server. where slow response could hamper performance. 2012 Safari 6
ailing upon "clien t-side" scripts. resident on the user's system , overcame the laten cy problem and 2013 Firefox 21
provided a superior experience. i----
2013 Opera 15
Java Script qu ick ly became very popular but a disagreement arose between Netsca pe and Microsoft
2015 ECMAScnpt 2015 Partially Supported in a.II Browser
over its licens ing - so Microsoft mtroduced their own version named "]Script" Although similar to
JavaScript. the new )Script version had extended fea tures and some few differences. JavaScript has one specification and several following dialects:

Im Features of JavaScript 1. ECMAScript: The official name of the JavaScript language specification, the ECMA-262
specifica ti on.
JavaScript is a scripting la nguage designed primarily for adding interactivity to webpage and 2. JavaScript: The ori gina ting dialect of the ECMAScript language specification. JavaScript was
creating web applicau ons. implemented m Netscape.
Va rious JavaScript fea tu res are given below: 3. LiveScript: The predecessor of JavaScript. LiveScript was renamed to JavaScript in Netscape 3.0 .
JavaScript 1s a lightweight, interpreted programming language. 4. JScript: The Microsoft dialect of the ECMAS cript language specification. ]Script was first
unplemented m Internet Explorer 3.0 browser released in August 1996 .
.Jr JavaS cript 1s a scripting language and it is not java.
S. ]Script .NET: The successor of )Script under Microsoft's .NET framework.
~ JavaScript is interpreter based scripting language. A JavaScript cons ists of JavaScript statements that are placed within the <script> ... </script> HTML
.....-,(" JavaScript is case sensitive. tags in a web page.
~ JavaScript 1s object based language as it provides predefined objects. There 1s a flexi bility given to mclude JavaS cnpt code anywhere in an HTML document. But there are
v8:
Designed for creating network-centric applicauons. follow mg most preferred ways to include JavaScript in your HTML file.
v :'
Complementary to and integrated with Java. 1. Scn pt in <head>...</head> section.
2. Script in <body> ...</bodp section.
v-8'."
Complementary to and integrated with HTML.
3. Script in <bodp ...<l bodp and <head>... <l head> sections .
~ It is open and cross- platform. 4. Scnp t in and external file and then include in <head> ... </head> section but it is preferred way to
.. ll!J History and Versions keep it with in the <head> tags .
The <script> tag alerts the browser program to begin inter preting all the text between these tags as a
JavaScript was created by Brendan Eich a Netsca e c · .
September 1995. It took Eich only 10 da;s to devel~ t ommunicauons Corporation programmer, in scnpt. Simple statements in JavaScript are generally followed by a semicolon (;) character, Just as
as Mocha. P he scnptmg language whi ch was then known they are in C, C++, and Java.
JavaScript, however, allows you to omit this semicolon if your statements are each placed on a
Afte r a couple of years. Microsoft Internet Explorer t 00k h separate line. So simple syntax of your JavaScript will be as follows:
implementation )script t e language and came up with its own
<ht ml >
• Later, Netscape decided to deliver the language to ECMA In . <body >
guide the pa th of JavaScript and so the name ECMAS . ternational to set the standard and to ~ <script t ype-" text / javascri pt">
cnpt came mto the . t
ECMAScript had few releases between 1997_1999 (ECMA . pie ure. ~ aocument.write (" Hello World !" )
decade. nothing new released. At that time, Microsof Script 3) and after that, for almost the next </ sc ript>
I </ body >
but it was not doi ng mu ch to improve the Janguag tdnternet Explorer was dominating the world
birth and th e focu s ca me back to ECMAScript. e an so Firefox an d ot h er array of browsers took </ ht ml ,
Bos,cs of JovoScn I p ~
1.6 ro '•1t11t1
Ciion1 /do Sc11ptlng L.!!!'~ .!.- - - , I
we will see later on. This program will p Basics of J avt Sc n I Pr mnmi"B_
11:iw to rur. a javasmpt prog ram o
n a web server. roctu C! 17

fo ll Dwtng OU put The term~ (Integra ·ed Development Enviro nm ent) refers to a powe rful ed ito r with many fea tures
HP]lc, world' that us uall y operates on a "whole proiect." As the name suggests. it 's not just an ed i or. bur a full ·
:~ can__!,!Se tl~ollow.!!:.8:~a~r!_!
tr:!_!ib~u~t~
es~w~Jt~h~sc~r:!JI2_!l_!t~a ~ - - - - - -ID~e~s;cr~l~prtticlo~n;--- - - scale "deve lopment environment."
f ew IDE available for Java script proiect developm ent and execution are:
~-!: ~ · 1 Att ribute Value Specifies the scripting language as a cont 1. WebStor m for frontend developme nt. The same company offers other editors for other
1 type tex t/ Javasc rip t E ) eni.
applic ation / ecma scrip t type (M IM type · la nguages (paid) .
app l 1cat ion / javasc ri pt 2. Netbeans (free and cross-platform).
1ext /vbscr1 t Lightweight edi tors a re not as powerful as IDEs, but they are fa st . elegant and simple. They are
2.
Defines the character encoding that the sc . mai nly used to open and edit a file mstan Jy.(tew lightweight editors for JavaScript programm ing
char se t
uses. l'Jpt are: -
def er -defer Declares that the script will not generate an 1. Y:isual Studio Code (cross-platform, free) also has many IDE -li ke features .
content. Therefore, t he browser/user age Y 2. Atom (cross-pla form . free).
. . d d nt 3. Sublime Text (cross -platform. shareware).
can contmue parsmg an ren ering the rest
ofthe a e. 4. Notepadh (Windows, free) .
~· language Ja vasc--ipt Deprecated - Speci fies the scripting Ianguag The main difference between a "lightweigh t ed itor" and an "IDE" is that an IDE works on a project·
hve script Don 't use this attribute use the type attribut~ level. so it loads much more data on stan. analyzes the project structure if needed and so on.
vbscript I instead. CA lightweight editor is much faster if we need only one file.]
----
5- s re --~
u ~ · - - -----_....--;;s=ec=ir.fi:es
___ ::=-=-
a "U,;:R;,l/,;U
c;cR;;cL;-o-;:f'a~n=-=e= i -t-.--1
x:t :e:::r=n=a·1s- c-r.,..
In this book NetBeans is used for JavaScript project development and execution which intern ally
used web server either Glassfish/ Apache Tomcat.
Advantages and Disadvantages of JavaScript In NetBeans select "HTMLS/JavaScript" category from "New Pro1ect " wi ndow. Give a specific n ame to
project, select next button and fin ish th e wizard to create HTMLS/ JS app lication.
Advantages of JavaScript: Then con firm the index.html file in HTMLS/ JS apphcanon in project explorer window. In index.html
/ . Speed, Being client s1de.[iavascnpt is very fast because any code func tions can be run file. you can write JavaS cript code and to run that code si mply right click and run th e file
1~me~1~tely rnstead of having to contact to the server and wait for an answer.]
-vY. S1mplic1ty: Javascnp t is relati vely simple to learn and implement. IIIJ JavaScript Programming
You can think of JavaScript as an extension to HTML HTML is case insensitive language whereas
,.j5-: Versa ti lity: Javascnpr plays mcely wi th orher languages and be used in a huge variety of Java Script is case sensitive language.
apph cat1ons.
~erver Lo ad: Being cl1ent-s1de reduces rhe website s~rver HTML tags create objects; JavaScript lets you manipulate those objects. for exa mple. you use the
<body> and <lbodY> tags to create a Web page. or document.
5. L~ss Server Interaction: You can validate user inpur before sending rhe page off to the server
T is sa~es server traffic. which means Jess load on your server. · As shown in following table. a fter that docu ment ' is created . you can interact with it by using
JavaScript:
f ~mmediate feedback to the Visitors: They don 't have to wait for a page reload to see if they have
orgotten to enter somethmg HTML Tag JavaScript
7 > . </ bod > docu ment
· ~~~~eaa::u~:t:;:~~::~~~ ~i~mc:~a ~~:a~::~~:~~ces that react when the user hovers over them
..,,if' Richer Interfaces: You can use Ja va Scr' t . 1 d . . . . </ form > document.m form
and sliders ro give a Ri ch Interfa ce to yo~~ s,\: ~~~i~r:. such items as drag -and -drop components Button <i nput t pe="butto n" name= "m button "> document.m form .m button
_/. E.a sy to ~ebug: Code l!1 Java Script is easy to debug and testin J To add JavaScript to a Web page. all you have to do is embed JavaScript code in an HTML file. You
J<l L1ghtw e1ght and Interpreted: JavaScn r is a Ii h . g. have two choices when it comes to embedd ing JavaScript code in an HTML file:
that allows you to build interacnvi ty mtt otherw ·g tweight, mrerpreted programming language 1. You can use the <script> and </ script > tags to include JavaScript code directly into an HTML file .
Disadvantages of JavaScript: ise stanc HTML pages.
<script> and <! script> tags can be added in head, body or in both the section in HTML page.
v1" Security: .lls the code execures the user's com . (i) Scripts in the head Section: Scripts to be executed when they are called, or when an event is
malicious purpose puter, m some cases ir can be exploited for
triggered, go in the head section. When you place a script in the head section, you will
J Relymg on End User: Ja vaScript is somenmes in . ensure that the script 1s loaded before anyone uses it.
Where as server side script will always prod h terpreted differently by d ifferen t browsers.
pred ictable uce t. e sa me output, Client-Side scripts can be a little (ii) Scripts in the body Section: Scripts to be executed when the page loads go in the body
section. When you place a scn pt in the body section it generates the content of the page .
...,;! Clien t Side JavaScript does nor allow th d' .
securi ty reason e rea mg or Wntmg of files . This has been kept for (iii) Scripts in both the body and the head Sections: You can place an unlimited number of
. ;r: JavaScript can not be used for Networkin a li . scripts rn yo ur document. so you can have scripts in both the body and the head section..
<ntml>
available. g PP cations because there is no such support
<head >
...A. Jav aScript does not have any multithre d'
a mg or multi- .. <Scrlpt >
JavaScript Code Editors process capa bili ties. I I sc r ipt ing code
</ sc r ipt >
.t, ,de ed1tor 1s the place where progra mm e
. d rs spend most of th . r:;. </ head >
CC•1P e •tors namely. ID Es and hghtwei ghi editors. Man e1r time.i.Ihere are two main types of <body ></ body >
y people use one tool of each typej. </ html>
Basics of JavaScript p ~ __
18 11111111
Client Side Scripting Language · ~
. include a separate, external JavaScript file (a Ii cuenl Side Scripting Language 1.9 Basi~ of JavaScript Programming
2. You can use the <script> and <Ism pt> tags 10 . . xtension) int o an HTML file. le
containing only JavaScnpt statements and bean ng a .JS e c omments in JavaScript:
<h tml > JavaScript supports both C style and c. . + style comments. Thus, text oetween a II and the end of a
<h ead > line is treated as a comment and is ignored by JavaScript.
<script src= "myJsfile . js "> Any text between the characters r and •1 is treated as a comment (block comment or multiline
/ / scripting cooe comment). This may span multiple lines.
JavaScript also recognizes the HTML comment opening sequence <!-·. JavaScript treats this as a
</ script >
single-line comment. just as it does the I I (two forward slashes) comment {single line comment}.
</ heao >
<body>< / body> The HTML comment . closing sequence ··> is not recognized by JavaScript so it should be written
</ html> as //··>.
When you want to create a portable HTML document then us_i~g a <script> element within the Example:
docum ent's head section is perfectly fine. But when portability is not an issue then greater <scr ipt lang ua ge= " javascript" type= "text/ javascript " >
efficiency can be ach ieved by creating external script and style files. <! - -
Embedd ing an external JavaScript file in the head section of an HTML documen t requires an src // This i s a comme nt . I t is similar to comments in C+~
attribute be added to the usual <script> rag to specify the path to the script file. /'
The script fi le is located in the same directory as the HTML document with .js file extension. Th i s i s a multiline comment in JavaS cript
Example: It 1s ver y similar to comme nts in C Programming
Step 1 : Aeate an HTML document with head and body section. 'I
Step 2 // ··>
In the head section of the HTML document, insert an element to embed an external
JavaScript fi le, </ scri pt>
<scr i pt t ype = "t ext / j avascript " src = "sc r ipts / Externa l. js " >
</ scri pt>
IID Data Types in JavaScript
• Every variable has a data type that indicates what kind of data the variables holds such as numbers
Step 3 Save this file as Sample.html on specific folder. and characters, can be stored and manipulated within a program.
Step 4 Open a pla in text editor, like Windows Notepad. and add write content as given below, / JavaScript provides different data types to hold different types of values. There are two types of data
document .wr i te (" hello, I am run ning from extern al script ! !!! ") types in JavaScript namely Primitive data types and Non-primitive (reference) data types.
al ert ( "hey, I am t nere !!! ") / The p_redefined data types provided by JavaScript language are known as primitive data types .or
Save this file as External.js in the new folder {name as scripts Jon the same location where in-bu ilt data types . The data types that are denved from pnm1t1ve data types of the JavaScnpt
Sample.html is saved. language known as non-primitive data types or derived data types or reference data types.
While you are wnting JavaScrip t code, semicolons are not strictly required. There are five types of primitive data types in JavaScript They are as follows·
Step 5 : Complete code will look like as follows. Now run the HTML document:
ExanqJ!e ~~ .
,.
._.,,,sample.html Sr. No. j Data Type Description .

< t ml> 1. / Stri ng Represents sequence of charaeters var str = "Hello";


<h ead >
<sc r ipt t ype
</ scr ipt >
"te xt / javascript " sr c "scri pt s/ Exter na l. js" >
2.
I
Number
fo r exam ole. "hello".

I
var str2 = · Single quotes ' ;
Represents numeric values, for var n = 123;
example, 100. The number type n = 12. 345;
represents both integer and
</ head > floatin2 ooint numbers.
<body >< / boay> 3. / Boo l ea n Represents boolean value either var x= true;
</ html > false or true. var y = false ;
J External.js 4. Undefined Represents undefined value. The va r x = undefined ;
docume nt . write ( "hello, I am running from external meaning of undefined is "value is /
alert (" hey,I am t here !! !"') script !!! ! ") I not assigned".
Output: I 5. Null Reoresents null i.e. no value at all. va r a2e = null;
..

..
--
r-~~~~~~~~~~~-

.=· ~ -,;_~
X tf ... k:a lhost :ki. - . - "'
tMl'W "' - .9 ..... :J • Kk
The non - nmll!ve data t es are as follows:
Sr. No.
1.
2.
Data
Ob · ect
Arra
Descri tion
Re resents instance throu h which we can access members .
Re resents ou of similar values.
bt-1:>. l ana:riq:fra:r:utt'mal 1,1,~. •r1 1
JavaScript us_es the let or var keY"'.ord to declare variables of any type. An equal sign is used to assign
values to vanables. JavaScript vanables can hold many data types like numbers, strings, objects and
more:
va r length = 16; / I Number
var lastName = "Thalor"; / / Stri ng
..,/ a r x = {firstName : "Meen kashi ", lastName : "Tha l or "}; I / Objec t
1.10 ro ra~
!!!.!:~~~!£!'2'.!.9.!~i!!!!~ ~ ~ ~ ~ ~ ~ ~ ~ ~~ ~~ ~ ~ ~ ~=--~ : :B~as~lc~s~o: f~J~av:a~S:cn~ t P
S:Ciient Side Serltin Lan ua e
C~ll:c:
•n.:.:.t..::S:.=c
ld.c..
o ~Sc_n~p_lln~g~L-•~
ng~u""
ag..,e' - - - - -- - -- -1~.1'...'1._ _ _ _ _ _ _ _....cB
~a~s,!!:c~s:::._Olc..,J:::•.:.:'•s,_~3r~J'..'
:.::. _.I
D DOT SYNTAX AND MAIN EVENT
ffl OBJECT NAME, PROPERTY, METHO '.
/
b t in JavaScript.
Eve ryth ing is an o 1ec
----...
l!!JProperty
v JavaScnpt 1s an object-based language. M rhods are actions tha t can be perfor
..../ A property is a j ata or value associated with an object. .
• A Java Script object is a collecnon of named values .e d propernes 1Tled on
. t obJ'ects are ca 1ie Objects can have many data's associated with them depending on applica ion of use r or exc:mr'-= :.
objects The named values, in Java Scn p ' h 5 performed with an object y
external source a · au ace fo rm object can ha ve a title, a width and a height as propert ies whe reas a wind w ooiec: carc h« :,·
An event is an act10n that the object or an . the dot synta x al ong with the Object name an ~1
an object's properties and methods by using d 11$ background color. a width. and height as properties. Hence. ea ch object has its 'JWn set of properties
property or method. An object can be created with figure brackets (... ) wllh an opu orn;I !1Sr of propernes A propt' rrj 1,,

ll!J Objects · I thing (either a string or a number) In co t


"key: value" pair, where key is a string (also called a "prop erty name ") . and value can be any nrng
Object li teral property values can be of any da a type, including arra y !Jte rals, funct1ors. and nes:t'O
All primitive data types can contain on lY a sing e . - · n rast, object li terals.
@bjects are used to store collections of data and more compie;: entitieu
In the followin g code user object is created with two properues:
• [ avaScript objects are collection s of properties and methods.j
J , A method is a function th at 1s a member of an obJect. . 1. The first property has the name "fname" and the va ue Meena kshi '.
J · A property is a value or ser of values (in the fo rm of an array or object) that is a member of an 2. The second one has the name "!name and the value "Thaler ".
object. You can access the object properties rn followrng rwo ways·
Objects in JavaScnpt may be defi ned as. an unordered collection of related data of primitive 01 if( user. fn ame ;
re ference types in the fo rm of "key value" pairs, user["fname " ];
...._,,,< JavaScript sup ports three kinds of objects.
Example:
/ . Intrinsic (Built-in) objects are defin ed by JavaS cnpt (such as Date, Math . Array and String).
...__7 User defined objects are rhe objects which you create.
J Host objects supplied and always availab le to java script by browser environment (such as
wrndow. document and form ). The HTML Element objects that represent the structure of a web
r <ht ml >
<n ead >
<n t le >OOJ ect </ title >
~ c ~Java Scnpt are host objects. </ neaa>
/ All objects inJavaS cnpt support expand properties and methods. which can be added and removed at <Dody>
run time. These properties and methods can have an y name and can be identified by numbers.
<SC ipt >
Object Name:
var us er = {
.,/ Each object 1s uniquely identified by a name or ID
A web page conta ins many objects, some of which are the same kind of object. These objects can be
fname : " leena shi ",
easily distinguisha b e by using its name or I ror example, a web page might contain two form ln ame "Thalor "
objects coul d be named as form l and form 2. };
\/' There are a number of ways you can create your own objects n JavaScript. document wr ite ( " ser " + user .fname+ " "+user .l name);
1. Using Constructor Function to Define an Object: </ scri pt >
....,/ We can create an object usmg constructor fu:1c ion. A co, s rucror is a function that creates and </ body>
init ali zes an object.
</~ tml >
/ JavaScript provides a special co~strucror fu nction called ObJectO to build the object. The return value Output:
of the ObjectOconstructor 1s ass igned o a var ab le .
Use r = MeenaKshi T al or
. / The new ope a tor is used o create an instance of an object To create an object, the new operator is
followed by th e constructor method . l!IIMethod
Syntax:
'V" A method is a set of statements (actions) performed by an object when it receives a mes ge.
I/ Creates an empty ge neric ooject .
var yOb Ject =new ObJect () ;
For example, aSubmit button on
a form-isan object. Tbe a1mensions of the button are pro pc rt It:' 0 f
the button object. If you click the Submit button, the form is submitted to the serve -side a ·;..l i~
! I Creates a Date O ject .
var myb 1rt hday = new Date (1961 , 5, 10 ) ; In other words, clicking the Submit button causes the button to process a method.
I I Creates a user defi nea obj ec t. In t_he following code user object is created with two properties and one method, ful ame is m e the<'.
var myca r = new car (); which returns the fname and !na me properties of object_
.._/.1 . Using. Literal Notation to Define the Object: Example:
An object !J tera11s a comma-separated list f · <ht ml>
Object literal property values can be of an o /arne-value pairs wrapped m curly braces. ted .
object literals. Y ata type, mcludmg array literals, fun ctions, and nes <head>
<ti tle >Object </ title>
,a " user = (} ; I I An empt y oo Ject
</ head>
var ore e = { , . 10 , y· 20 , radius : s 1 ;
Cllonl Sldo Serl lln Lan uago 1.13 Ba,Jca or Jav1Scrlpl Proqremmlng
<body >
<sc ript Using Constructors to Define Types:
var' user' = A constructor is a function that instantiates a particular type of Object. You invoke a constructor
fname: "Meena kshi", with the new keyword .
ln ame : "Thal or", In order to create a user defined object you have to write a function which is used as a constructor.
fullNam e: f uncti on (){ret ur n tni s. fnam e • .... ,this.lname;} The language doesn't make a distinction between constructor function or normal function.
A fun ction can be written to be used as a constructor or to be called as a normal function, or to be
};
used either way. A constructor is used with the new keyword.
docume nt.writ e("Use r " • user.f ul lName ( ));
~ ample: Creating user defined object using constructor.
</ script >
<html >
</ body >
<he ad >
</ htm l> <scr ipt >
Output: functio n Car (a, b) {
User= Meena kshi Thalor this . color = a
11!1 Dot Syntax thi s. company= b
The Properties and methods associated with any object can be accessed by using the object name
with a dot syntax (period), e.g. user. fname, user.lnam e and user.ful!Nam eQ. var c = new Car ( "black", "Nissan ")
/ You use dot syntax to describe to JavaScript how to interact with the objects, properties, fun ctions document.write( "Object Color= "+c . color )
and events in an application. doc ument.write (" <br/ >")
Extending an Object: document . write ( "Object Company="+c. company)
. / Add a new property to previously created object is called extending t he object. Following example is </ sc ri pt >
showing the concept of extending an object. </ head >
Example: </ ht ml>
<html > Output:
<head > Object Color=b lack
<script > ObJect Company=Ni s san
var student= { Mr.I;; Event
firstName : "Amit ", In Ja vaS cript functions are normally not called directly from the top level of a JavaScript program.
lastName: "Gupta ", Instead, functions are called in response to various user actions, such as clicking a button or moving
id : 12 , the mouse over a certain element.
Events:
fullName: f uncti on (){ return this.firstName +" " + this.lastName}
};
One of the primary ways in which JavaScript is executed on a Web pages is through events. An event
is a specific circumstance (such as an action performed by a user, or an action performed by the
student. class="Fifth" ; / / add a new propert y browser) that is monitored by JavaScript and that the script can respond to it in some way.
document .write (" St ud ent Id =" +st udent.id ) • JavaScript -enabled web pages are typically event driven.(fu,ents are actions t_hat occur on the
document .write ( "<br/ >") webpage~
document.write ("Student Class= "+student . class) V Events are signals generated when specific action occurs.
document.write ( • <br/> •) In order to make a web page more interactive, the script needs to be able to access the contents of the
document and know when the user is interacting with it.
document .write ( "Stud ent Name= "+student . fu ll Name ()) The kinds of events that might occur are due to:
</ script.>
1. A document loading,
</ head >
2. The user clicking a mouse button, and
</ html>
3. The browser screen changing size.
Output:
Event Handler:
Student Id=1 2
When a function is assigned to an event handler, that function is run when that event occurs.
Student Class=Fifth
A handler that is assigned from a script uses the syntax, [element] . (event] = [function] .
Student Name=Amit Gupta
where, [element] is a page element, [event] is the name of the selected event and [function} is the
Here, student class is created using literal notat· f . ~ name of the function that occurs when the event takes place.
new property i.e. class. ion. A ter creatmg a student class we are a 1
In short@e script that you use to detect and respond to an event is called as an event handler.
:!!!':~~~l.e!!!!S.!!".Et!!!!.!l!__~~~~~~~~~!!.~
1.14 ~ ~ ~ ~~~~-B-as_lc_s_o_t~J~
av~a~S::!.!l:
crlot~am'"lt!·
p
.fClient Side Scrlpllng Language ~
Basics of JavaScrl r Pro rammln
For example: - 1.15

aoc ument .onclick = clickHan~ler; . di Oto be execured when ever the user clicks
..--
10. length Sets or retrieves the number of objects in a collection . _I
This hand ler will ca use the funcnon clickHan er the ,---
11. opener Sers or retrieves a reference ro the window that created the current
mouse anywhere on the screen. ~ · name does not end with parenth
·
Note that when an event han di er is ass,
·gned the , unct10n
' .
are just poi nting the event to the name of rhe fun ctwn.
The clickHandler func ti on is d fl
,
eses w
'. e
e tned hke
- 12. outerHeight
window.
Gets the height of the window, including user interface elements, such
as the window frame, roolbars, and so on.
th is:
function clic kHandle r (evt )
- 13. outerWidtn Gets rhe width of the window, including user interface elements, such
I I some code he re as the window frame.
} 14. scree nleft / Retrieves the x-coordinate of the upper left-hand corner of the window
Im Built-in Objects in JavaScript
•In eve ry JavaScnpt host environment, some object is designated ~s the global object. In common
15. screenTop
frame, relative to the upper left-hand corner of the screen.
Retrieves they-coordinate of the top corner of the client area, relative
to the too corner of the screen.
browsers, this bject 1s na med wi ndow It is called the globa( object beca use, all global variables
16. screenX Sets or retrieves the x-coordinate of the mouse pointer's position
declared by your prog ram are actually stored as properties of th1s obJecr.
relative to the user's screen.
ln addiuon to w111d w object -~ ~· String , m ,
and Object are bui lt in objects in JavaScript.
17 screenY Sets or rerrieves the y-coordinate of the mouse pointer's position
1. Window Object:
relative to the user's screen.
• Uhe wind ow object. whi ch 1s a top -level object in client side JavaScripfJreprese nts a window or a 18. self Retrieves a reference to rhe current window or frame.
frame (wi thi n a frame set ) Since, window objecr is a top-level object, it onrains oth er objects like 19. stat us Sets or retrieves the message in the status bar at th e bottom of the
'd cument , 'histo1y etc wnhin it.
wi ndow.
For example, window.ct cumenr.frames[ i), where i 1s 1,2,3..... , refers to the 'ndex of the frame 20. top Retrieves the toomost ancestor window.
residing 111 the cu rrem w111dow
Example: Us111g properties of window object.
The open meth od f window object 1st sed t open a new window and loads the documen t specified <n tml >
by a given URL
<he ad >
var r·e: va l = wind .. . open url , name, fe at ures , rep l ace ); , SC r l pt>
where,
a,· myWrn = wi ndow.open (" ", "MyWi ndo1v" , "wiath =500, height =300, top =50,
1 15
! url Str ng tha t specifies the URL of the ocu ment to display If no URL is specified, a new left=75 ,stat us= no ");
w111dow wi th abou t:blank is disp layed. myWin .aocument ,,rite ( "Screen wiath =" + mylvi n.outerWid th ) ;
1
(11 name is Stn ng that specifies th e name of the window ml'l<in . document . .. ri t e "<br >Screen ne1ght =" • myWin.out erHeight ) ;
iii) features String thar ontR111s a !Js of n1y,, rn . documen t. 1vrite ("< br>S creen X ="+ myWin . screenX) ;
· items separated by commas Each nem cons is rs of an
pt;on a_nd a ~Jue, separated by an eq uals sign (for example, "fullscreen =yes roolbar=y0 s") myl•ll n.doc ument ... rite ( "<br >Screen Y :"+ myWi n. screen Y) ;
158
1rv) rep a e ea n rha r spenfies whet:ier rhe urJ reares a new enuy r r~places rhe ,cu;rent m}l<rn . document .1vri t e("< br>Wi ndow Name : "+ myWin.name ) ;
ent ry 111 the wind w s h1stc>ry list True meai myl•in . stat us= "status is ok "
list. False means urI reat . is u.r1 rep 1aces th e currem document in the history
. e a new enrry 111 the his rory list myl in . document. 1,r i t e (" br >Wrndow status: "+ myWin . sta tus);
Prope.rue.s of Window Object: ·
< sc ri pt>
As wind w bJect 1s a t p-lel'el obie.:r and son•e r .
</ heaa >
rat-le show the prcperues 0 fwi~d IV objecr. · p pemes are def111ed for window obiect. Following
< ht ml >
/ S'r.N;o,-;----;Pro~pert~y~~=.:::.::..:.'.'.~ ~ ~ ~ ~ ~ ~ ~-
Output:
1. .\ c t!\ f \: Jti ec t De.scrlption r.:-~-,.-....,..~~~~~----=o=--...,
Retu rns a nu] val ue
;erneves whether th e referen ed wmd ow is closed
<.' lCCI \\'},jm.;z~ (l\1
- :l't'n! :t,., ir:{\()
- ets r ge s the height of the modal di J S.Tt:ni \. "' ~~
~ets or gets the 1 ft .a og win dow.
6 \\c>J..m '\ .1:.Ut' ).. h \\ a>J,.., ,\
\\aJ..,t> U.W) ' .ltUS U ~

Methods of Window Object:


Wi ndow objecr provide diffe.ren: methods ro display dialog box. These method , a.re expla ined below.
-v{1J ale.rt Method: It displays a dialog box containing an appli cation-defined messa e.
The syntax fa.lert method is as follows: g
cootd. ... va r ret al c window . al ert( mes sage J;

~~-- - - ·---~~·- ·~- --- - - - -


tii{"

~~~~!.e!.!!".9..!:!!!l~:1!...~ ~~~~~~~__!~
1.16 ~~~~~~~~-
B-as_lc_s_o_f_Ja_v~a~Sc~r~lp:!.!tP~~
r
~Client Side Scripting Language 1.17
Basics of JavaScn t Pr rammln

Here, . to display in the dialog box. Properties of Math Object·


o message is String that specifies the messageh -·nse it returns an HRESULT error code
. h d d .t eturns S OK. Ot e, .... • . Sr. Ho, Property DelaiptfOJl
o If t h1s met o succee s, 1 r . -. . box that contains an optional messa e
_)ii) confirm Method: It displays a confirmauon dialog g as OK 1. E Euler's constant and the base of natural logarithms, (approximately 2.718).
and Cancel buttons. yZ_ LN2 Natural logarithm of 2, {approximately 0.693).
The syntax of confirm method is as follows : 0- LN10 Natural logarithm of 10, (approximately 2.302).
var retval = window.confirm (mes sage) ; LOG2E Base 2 logarithm of E, (approximately 1.442).
v-4-
Here, . . ,.__%.' LOG10E Base 10 logarithm ofE, (approximately 0.434).
.. to display in the conf1rmat1on dialog box If
:, message is String that spec1f1es the message . · no Ratio of the circumference of a circle to its diameter, (approximately 3.14159).
6. PI
value is provided the dialog box does not con tam a message. ,
Square root of 1/2; equivalently, 1 over the square root of 2, (approximately
o This method retu~ns true or false. It returns true when user clicked the OK button else false: /. SQRT1_2
0.707).
.fl) prompt Method: It displays a dialog box that prompts the user with a message an d an input field.
-$. SQRT2 Square root of 2, {approximately 1.414).
The syntax of prompt method is as follows:

Here,
var retval = window.prompt(message , defstr ); Methods of Math Object:
Sr. No. Methods Description ~- -, .. ,
.t," - '
"' message is String that specifies the message to display in the dialog box. By default, this /. abs() This method returns the absolute value of a number.
parameter is set to "". 2. acos( ) This method returns the arccosine (in radians) of a number.
c defstr is Siring that specifies the default value of the input field. By default, this parameter is
3. as in () This method returns the arcsine (in radians) of a number.
set to "undefined".
4. a t an () This method returns the arctangent (in radians) of a number.
Example: Using methods to display- dialog box.
5. ata n2 () This method returns the arctangent of the quotient of its arguments.
<ht ml>
<h ead> 6. ceil () This method returns the ~ nreget gtJater than or equal to a number.
<script > 7. cos () This method returns the cosine of a number.
window . alert ( "He re ' s a simpl e message" ) ; 8. exp() This method returns EN, where Nist.he argument, and Eis Euler's constant, the
base of the natural logarithm. - ~MO UL\,
document.write ( "Confirm . " + window . con firm ( "Go or Stop? " ))
document.write ( "<br > Prompt : " + window.prompt ( "Yes or No ?" , "Yes" )) 9. floo r () This method returns the-imp; t integer less than or equal to a number.
</ script> 16. log () This method returns the natural logarithm (base E) of a number.
</ head> ,rt. max() This method returns the largest of zero or more numbers.
</ html> xf min () This method returns the smallest of zero or more numbers.
Output: 13. pow () This method returns base to the exponent power, that is, base exponent.
14. r andom () This method returns a pseudo-random number between O and 1.
15. ro und () This method returns the value of a number rounded to the nearest integer.
+- C ..:: loca; -., _
~ sin () This method returns the sine of a number.
::· App, ._A.1_ sqrt () This method returns t.he square root of a number,
Coufinn. f.ilie -lB- tan () This method returns the tangent of a number.
Prompt Yes 19. toSource() This method returns the string "Math".

2. Math Object: Example. How to round a specified number to the nearest whole number.
<html>
__/ The Math object provides properties and method f
s .or mathematical <body >
• Unlike the other global objects Math is n t constants and functions.
. · o a constructor ~ . <scri pt type="text/j avascript">
static and can be called by using Math as an obi'e t . h · e properties and methods of Math are
c Wit our creann · J document . wri t e(Math . round(?. 25) )
Thus, we refer to the constant pi as Math.PI and we call t . g It.
the method 's argument. he sine function as Math.sin (x), where xis </script>
</body>
Syntax:
</html>
ar pi_val = Mat h PI ; Output:
var si ne_ val = Math . sin (30 );

l 1LI.-.-.-,.:...-- _ _
Basics of JavaScri pt Pr ~
, .18
Basics of JavaScrl t Pro rammm
Client Side Scripti ng Lan guage 1.19

3 . Da t e obJee
· t
:
The Date object is used to work with
. dates and times.
You create an instance of the Date object With IIIJ Basic Concepts in JavaScript
'./" In this section we study various basic concepts used in JavaScript:
the "new" keyword. d .. date": 1. JavaScript Identifiers:
To store the current date in a variable calle my_
JavaScript identifiers are names given to variables. functions, classes or objects etc. It is the same as
var my_date= new Date ( ) . ct ou can access all the methods of the object from the identifiers in other programming languages like c. C++, Java, etc.
After creating an instance of the Date obJe ~{to return the date (from 1-31) of a Date Object, You _ / An identifier is simply a name. In JavaScript, identifiers are used to name variables, functions.
"my_date " variable. If. for example. you wa methods, objects and so on.
should write the following : variables, functions, objects, methods, events, and other JavaScript syntax constructs are identified
my_date .getDate () . . es of the DateO object , like this : in scripts using unique names known as identifier~
You can also write a date ms1de the parenthes The rules for legal names are much the same in most programming languages as given below:
new Date ("Mon t h dd, yyyy hh :mm : ss" ) (i) Identifiers can only contain letters, numbers, underscore U and the dollar sign($).
new Date ( "Month dd, yyyy " ) (ii) Identifiers cannot start with a number.
new Date (yy, mm , dd,hh , mm,ss ) (iii) Identifiers are case-sensitive.
.._.....,.ew Date (yy, mm , dd ) (iv) Identifiers can be any length .
new Date (mil11seconds ) (v) Identifiers can not be the same as JavaScript reserved words i. e., keywords.
Here. is how you can create a Date object for each of the ways above: Here, are some examples of valid identifier naming conventions:
var my_date=new Dat e ( "October 12 , 1988 13 : 14 : 00" ) Employe e_Name, _EmpID012 , EmployeeAddress , $Name, EmployeePhone
var my_date=new Date ( "October 12 , 1988" ) 2. JavaScript Keywords:
var my_aa te=new Da t e ( 88 , 09,12 , 13 , 14,00 ) JavaScript is a case sensitive language where VAR, Var, and var are treated as different words - of
..,,_,xar my_date=new Date ( SS , 09 , 12 ) these three only var is a keyword .

. var my_aate=new Date ( 500 )


Fo 11 owmg are t h e most common me thods of Date object·
Description
Keywords are words that having special meaning in any programming language.
Java scri pt uses different reserved words as shown in the following table ·
Sr. No. Methods ' r JavaScript Keywords .! '
J.' Date () Returns a Date object. / brea k expor,: return abstract implements protected
Y. getDate () Returns the date of a Date object (from 1-31). I c a se for switch boolean instanceOf public
.._,.-3'. getDay ( ) Returns the day of a Date object (from 0-6. O=Sunday. l=Monday, etc.). f comme nt function i:his byte I int short
_..<. getMont h () Returns the month ofa Date object (from 0 -11. O=Jan uary, l=February, etc.). r c on t i nue if typeof char interface static

--<
6.
getFullYear ()
getHou rs ()
Returns the year of the Date object (four digits) .
Returns the hour of the Date object (from 0 -23) .
/ defau lt
I aelete
import
in
var
void
double
false
long
native
synchronized
throws
7. getMin utes ( ) Returns the minute of the Date object (from 0 -59).
I ao label while f i nal null transient
I else new lllith float pa ckage tl"Ue
8. get Seconas ( ) Returns the second of the Date object (from 0-5 9).
You should avoid using these reserved words and keywords as function or variable names as
Example: JavaScript has reserved these words for its own use.
<htm l > In addition to reserved words user should also avoid the name of Javascript's built-in objects and
<body > brows er DOM objects.
- <script t ype= "text / j avascr ipt" >
var d = new Date ()
Im Values or Literals
aocument . write ( d. getDate () )
'-Y You use literals to represent values in JavaScript. These are fixed values, not variables , that you
provide in your script.
document . write ( "." )
• Th is section describes the following types of literals:
aocument . write(d . getMonth () .,. 1) 1. Array literals
document . write(".") 2. Boolean literals
document.write( d . get Fuil Year ( ) ) 3. Floating-point literals
</ script > 4. Integers
</ body > 5. String literals.
</ html > / a y literals:
Output: An array. literal is a list of zero or more expressions, each of which represents an l
12. 9 . 2018 enclosed m square brackets([]). array e e ment ,
Basics of JavaScrt I P
1.20 r , 1111
Ctlont Side Seri tin Lin ua • · h · ·
-- t is ini tialized wi th t e spec1f1ed valu .... 1.21 BaaJca of JavaScrt t Pro rammln

When you create an array using


· an array htera 1, 1
f guments spec1fle ·
• d •• as i•·"
. h tt thenumber o ar In Java Script, you can declare a variable in following three ways:
elements. and Jts lengt 1s se o . three elements a nd a length of three·
ffe es array WI t1l · 1. With the keyword var. For example, va r x = 42. This syntax can be used to declare both local and
The following example creates t h e co . . J.
·c0l bian . Kona ' global variables .
"It var coff ees = f · French Roast ' , om '
2. By simply assigning it a value. For example, x = 42. This always declares a global variable. if it is
Boolean Literals: d , Jse declared outside of any fun ction . It generates a strict JavaScript warning. You shouldn 't use this
• I namely true an ,a ·
--..? The Boolean type has two htera 1va ues · variant.
Integers: . OJ hexadecimal (base 16), octal (base 8) and b' 3. With the keyword let. For example, let y • 13. This syntax can be used to declare a block-scope
• Integers can be expressed m deomal (base 1 · Inary local variable.
2 To declare text as a variable, we use the 'var' keyword, which tells the browser that the text to follow
(base l· f d' 'ts without a leading O {zero) .
Decimal integer literal consists of a sequence o 1gi . . . will be the name of a new variable:
Leading O (zero) on an integer literal. or leading Do (or 00) indicates it JS m octal. Octal integers can var variable_name ;
include only the digits 0-7. . .. For example, to name the variable cooicar. the declarat10n looks like this:
Leading Ox {or OX) mdicates hexadecimal. Hexadeci mal integers can mclude digits (0-9) and th, var coolcar;
letters a -f and A-F. Jn above example. we have a new variable with the name cooicar. The semicolon ends the statement.
Leading Ob (or OBJ indicates bmary. Binary integers can include digits only O and 1. The variable cooicar does not have a value assigned to it yet.
Some examples of integer literals are: Variable Initialization:
0, 11 7 and -345 (decima l , base 10) • ~ tormg a value in a variable is called variable initializatio~n other words, the process that assigns
015 , 0001 ano -0077 (oc tal , base 8) values to variable is called as variable initialization. ·
.-,,< 0x ll23 , 0x00111 and -0xFlA7 (hexadecimal , "hex" or base 16) To assign a value to a variable, we use the JavaScript assignment operator, which is the equal to{=)
0bll , 0b0011 and -0bll (bi na ry, base 2) symbol.
Ifwe want to declare a variable and assign a value to it on the same line use following format:
Floating Point Literals:
-¥, var va riable_name=var i abl e_va l ue ;
/ A float ing-point hteral can have the following parts:
A decimal integer which can be signed (preceded by "+" or "-"), Example:
~ A decimal point("."), var x = 10;
A fraction (another decimal number). In the above statement, we assigned value "10" to a variable. And we have named the variable as "x".
'.) An exponent. Normally we say "xis equal to 10", but its "x holds a number whose value is 10".
The exponent part is an "e" or "E" followed by an mteger. which can be signed {preceded by"+' or '-'). There are some rules for variable names in JavaScript. Some of them are given below:
A floating -point literal must have at least one digit and either a decimal point or "e" (or "E"). 1. A variable must start with an alphabet or an underscore .
._/' Some example of floating point literals are: 17. 5, 6. 002E21. 2. The subsequent characters can be digits (0-9) or alphabets or an underscor e LJ.
String Literals: 3. As JavaScript is case-sensitive, number is not same as Number or NUMBER
/ A string literal is zero or more characters enclosed in double (") or single {') quotation marks. Some valid exa mples of variable names in javascript are given below:
• A stnng must be delimited by quotation marks of the same type; that is, either both single quotation s 1mple_Inte r est, _name, numberl
marks or both double quotation marks.
The following are examples of string literals: Some invalid examples of variable names are given below:
· Nirali · &MyName, Mega%tron
"Prakashan " Example: For vanable.
' 12 34 ' <html>
' one line \ n anotner line · <booy >
You can call any of the methods of the Strin ob . . . SCJ'IPI
automatically converts the string literal t 0 g Ject on a stnng literal value-Ja va ...,, <scrip t type="text /java script" >
the temporary String object. a temporary String Object, calls the method, then disca,w var name = "Example of Variable "
1111 Variables document . wri t e( name)
document. wr ite ( "<nl> "+name+" </ hl >" )
~ a b l e s are "containers " for storing in format '
. ion. A variable' l - th script. </ script >
• We can refer to a vanable by name to see its s va ue can cha nge durmg e
_/ va Iue or to chan ·
v A variable is an identifier that indicates a st ge Its value. 10
Tn1 s example decl ares a varia ble, assigns a value to it,
varia bl e . <br > an
d th d· l
en isp ay s the
reference the data stored at a memory locatio:.rage location in computer memory and it is used
Variable Declaration: Then the va riab le is displayed one more t ime, only this time within a heading
element .
Before we use a vana ble in a JavaScript pro
memory to variables. gram, we must declare it. Declaring variables allocates </ body >
</ html>

,\.!.-f ""1.. n ,. _ _
Boslcs ol JovaSc~
1.22
Clle'2.!_Sloe Scripting Language Basics o t JavaScn t Pro remm,n

Out put : . d ume va riable A holds 10


Following table shows comparison operaiors supported by JavaScript an ass
and B holds 20.
I Enmple
Operator Description
IE ;Hnple of Yariablc (A == B) is false .
(Equal to Operator) This operator checks if the value of . two
:1 C.\.!l~t .:«lare<.1 • .lnltlk :,,:)\ \l., ! \°llttt lOILIIIIJlf. al di~~~:fbt'~;,: I operands are equal or not. if yes then condition
~ tl , 1 ~t!M! u J!spt3•d l)!'lt' r.....Yr umt l"lh ttJi 1u1,: ....,th!o ~
becomes true. I

(Not Equal to Operator) This operator checks if the value of two (A ' BJ is fa lse. I
OPERATORS AND EXPRESSIONS
to be executed by comp uter and th ese pr~
. ·
I !=
operands are equal or not, if values are not , i
• (!mstrucuons
computer program is a set of mstruet1ons t statements are separated by semicolon _ranu
'----'--=!! (.). An
I equal then condition becomes true.
are called as statements]JavaScn p
ands which
.
reduces to a sm g1e va 1ue. I ,. (Greater Than Operator) This operator checks if the value of left operan d I (A ,. B) is not true. I
expression 1s a combination of operators an d oper is greater than the value of right operand. if yes I
I I
An operator indicates an operauon to be per formed on data that yields a value. An operand is a dat; then condition becomes true. I '
item on which an operation 1s performed. ¥ (Less Than Operator) I This operator checks if the value of left operand I (A< B) 1s true.
I

An operator 1s used to transform one or more values into a single resulta nt valu es and the values to <
which rhe operator is applied 1s referred as operands. JavaScript operators are used to perfonn il!i
is Jess than the value of right operand. if yes
then conditlon becomes true.
I
i
I
operanon.
There are different types of operators for different uses. Simple example, answer can be given using I "=
(Less Than or Equal To This operator checks if the value of left operand (A,._ BJ is false. II
Operator) is greater than or equal to the value of n ght
expression 4 5 is equal to 9. Here 4 and 5 are called operands and+ is called operat or. I
T
operand, if yes then condition becomes true.
Operators <= (Greater Than or Equal To This operator checks if the value ofleft operand I (A <- B) is t rue.
J Operator 1s a special symbol that indicates a certain action or operation when used with one or two
operands.
Operator) 1s less than or equal to the value of right
operand, if yes then condition becomes t rue. I
An operand 1s a constant value or a variable while an operation is an act ion performed on one or two .._/, Logical Operators: .
operands either to modify the value held by one or both of the operands, or to produce a new value Logical operators are used to determine the logic between variables or values. Usm g logical
by combining the exming values of the operands. operators, we can test two or more condit1ons in one line code.
• [Therefore, an operation is performed using at least one symbol and one value. The symbol is called There are following logical operators supported by JavaScript and assu me variable A h olds 10 and
an operator and a value is called an operandJ When an operator is used between the two or more variable B holds 20 then ·
variables or constants then it forms an expression. Operator Description •.. I Eiaim,le
JavaScnpt language supports following type of operators: && (Logical AND Operator) If both the operands are non zero then condition I (A && B) is true.
J Arithmetic Operators: becomes true. 1
Anthmeuc operators are used to perform arithmetic between variables and/ or values. If any of the two operands are non zero then \ (A II B) is true.
II (Logical OR Operator)
The sta ndard amhmet1c operators in Javascnpt are given in following table. Assume variable A holds condition becomes true.
10 and variable B holds 20 then· (Logical NOT Operator) Use to reverses the logical st ate of its operand. _If J !(A && B) is false.
Operator I! a condition is true then Logical NOT operator will j
-
+ (Addu1on Operator) Adds two operands.
Description I Example
A + B=30
make false. I
- (Subtract ion Operator) Subtracts second operand from the first.
v4'.' Bitwise Operators:
I A- B=-10
• (Mul t1ph ca t1on Operator) Bitwise operators act upon the individual bits of their operands.
Mulnply both operands. A • B = 200 Following table gives bitwise operators supported by JavaScript and assume variable A holds 2 and
, I (~vision Operator) Divide numerator by denumerator 1

% (Modulus Operator)
B/ A=2 - variable B holds 3 then:
Modulus operator and remainder of after an integer j B % A= 0
div.s1
; on.
I Operator DesaiptMIJl - -
l .1: (Bitwise AND operator) It performs a Boolean AND operation on each bit
([~rement Operator) (A& B) is 2.
, h Increases integer value by one. A++ = 11 I of its integer arguments.
·· _(Decrement Operator) Decreases integer value by one. (Bitwise OR Operator)
v · Comparison Oper ators: A·· =9
I'
I '
It performs a Boolean OR operat ion on each bit of (A JB)is3.
its integer argument s.
Comparison operators are used in logical statements t d b rween (Bitwise XOR Operator) It performs a Boolean exclusive OR oper at ion on (A ' B) is 1.
va riables or va lues. o etermine equality or d ifference e
Comparison operators are used to compare a co d . d'f onal Il
each bit of its integer argu ments. Exclusive OR I
means that either operand one is t rue or operand :
II
sta tements. n lllon and are always inside con 11
A compa rison evaluate to their true or false. This true df
two is tr ue, but not both. j
:
an a Ise values are called Booleans. contd . ...

~ 1 ..,.., ,
1.24
Basics of Ja vaScri pt Prog ramming_
ra tor and operates by client Stde Scrlpllng La ngu age 1.25
. is a unary ope
(Bitw ise NOT Operator) It is a the operand.
m
reversing all b_its its first opera n d to th e left by va r res ul t l =

aocument . write (" a


a -.. o,
b= .. ~e s ultl ) ;
It moves all bits tn specified in the second T

' << (Bitwise Shift Left Operator)


the number of P1acesfilled with zeros . Sh ift ing a doc ume nt . wr 1 t e ( "< o r / >") ;
New bits a re .
operan d · position is equiva lent to var r esu l t2 = (a < o) ;
value left by. one h ift ing two positions is cloc ument . wri t e ( "a < o= " + re s ult2 ) ;
multiplying by 2 · s do cument . writ e ( " <br I> " );
equivalent to m ultiplying by 4 , etc. .

i» {Bi twise Shift Right wi th


It moves all bits in its first operand w
the nght by (A» l)is t
the number of places spec1f1ed in the s econd
var re sult 3 = ( a && o );
doc ume nt . wr ite ( "a && o= " T result3 ) ;
Sign Operator) do cument . writ e ( " <b r / >" );
I operand . var r esu lt4 = ( a & b ) ;
Th is operator is just like the » operator . except (A>» 1) ist document . writ e ( " a & O= " T r e sul t4 );
>>> {Bitwise Shift Right with
Zero Operator) that the bits shifted in on the left are a lw ays zero. </sc r ip t >
</ body >
,$. Assignment Operators:
Assignment operators are used to ass ign values to JavaScript va r iables. There are folloWing </ htm l >
assignment operators supported by Java Script. output:
Operator I Description I Example 1 a+ b= 43
a < b= fa lse
{Simple assignment Assigns values from right side C = A + B will a s sign value of ~
Operator) operands to left side operand. into C _J a && b= 10
a & b- 0
{Add and Assignment It adds right operand to the left C += A is e quivalent to C = C + A I 11!1 Expressions
Operator) operand and assign th e result to left
operand. I • An expression is a phrase of JavaScript that a JavaScript interpr eter can evaluate to produce a va lue .
{Subtract and It subt racts nght operand from the C -=A is equivalent to C =C -A An operator comb ines the values of its operands {usually two of them) in some way and evaluates to
assignment operator) left ope ra nd and assign the result t o a new value .
/ When one or m ore operators are combined with one or m ore operands then it is_called an expres sio n .
left operand.
• The operators a re special symbols that represent particular a ctions or operation and operands are
{Mult ip ly a nd It multiplies r ight operand with the I C ·=A is equivalent to C =C • A var iables. or constant values. An operator perform s an act10n or operation when used w ith one or
Assignment Operator) le ft operand and assign the result t o two operands.
left opera nd. The op eration of an operator e ither modifies the value of one or both of the operands. or to produce a
1- (Divide a nd It divides left opera nd with the right i C I = A is equ ivalent to c = c / A new value by co mb mmg the existing values of the operands. An operand or a combination o f
Assignment Operator) operand and assign the result t o left oper ands and operators that. when evalu ated, yields a single value. For example, x + y .
operand. In the th is expression x and y are operands and the symbol + is an arithmetic operator.
% - (Modulu s a nd It takes modulus usi ng two operands c %= A is equivalent to c = C %A The expression m ay also be complex and sometime a s ingle operand of an expr ess ion further
Assignment Operator) and assign the result to left operand.
1
contains multiple operands a nd opera t ors and it is itself an exp r ession . The refor e, when two or more
~ Conditional Operators(?:): simple expressi ons are combined with each other then it for ms a complex expression .
Ternary operator is ca lled as conditi onal operator. This first evalu ates a n expression for a true or Following is a n example o f co mp lex expression:
fals e va lu e and th en execute one of the two given statements depending upon the result of the (x + y) • z
eva 1u atl on . In t he above expression (x + y) is t he first oper and of the a r ithmetic operat or • and z is the second
The cond it10n al opera tor has following syntax: operand of the arithmetic operat or •. The first o perand (x + y) is itself an expression that furthe r

Example:
Operator
?:
Example
If Condi tion is true ? Then value X . Otherwise value Y. nm co ntai n s two operators x and y and one operator+ .
Primary Expressions
._,;,/ The si mplest expressions, know n as primary expressions, a re those t h at stand alone - they do not
< I DOC TYP E ntml ) mclude any simpler expressions.
<h ml xmlns="h ttp ://wWw . w3. org/ 1999 / xht ml "> In JavaScript constant or literal va lu es , \£ertai n langua ge keywords , and variab le refere nces are
<nead >< tl t le>< / t itle ></ head > called as primary expressions}
<boay > Example of constant or lit eral values as primary expression:
<script t ype ="te xt / java scri p!" > 1. 23 I I A number literal
var a 33; -K "hello " I / A s tr ing literal
varo =- 1 0; / patte rn / I I A regu lar e xpression l i t era l

..'.: .. __
, •. i t ~ P.
!l.L.....,.,, ~ -.1;1·,

/
Client Side Serl tin urn uaqe

Example ofJavaScript 's reserved


the boo1ean -
.
words as pri mary exp
ressions:
Tr ue val ue c11ent Side Scripting Language 1.27 Bas1 c.s o1 Ja-vaSc-npt Pro9 m n('!'Hr9 •.
,t •.
t ru e
false
I I Eval ut es to
I I Evaluate s t o t he
boo lea n f alse value
11 val ue
IIDI Property Access Expressions ,:-'~
nu ll / I • val uates to the nu . ct _/ A property access expression evaluates to rh e value of an object property or an a rray 1;le mer,!
- o "current " ooJe JavaScript defines two syntaxes for property access:
!.his II Eval ates t o t n- . . express ion . i dentifier
/ ·mary expression.
-../" Examp le of variable reference as pn f . h variab l e i . The first style of property access is an express ion followed by a period and an ide mif1er Th,;,
~ aluates to t he value o t e .
II - of t he variaole sum · expression specifies the object, and the identifi er specifies the name of the desired property
s um I I E al uates t o t ne value k d li ke nu ll . exp ression [ expression J
l obal variabl e , not a ey1,or
ndefinea I I undefin ed is a g The second style of property access follows the first expression (the object or array) with an other
IIIIJ Object and Array Initializers
. .. . .
. .
expressions as they mclua e a number of sube .
expression in square brackets. This second express10n specifies the name of the desired property o:
the index of the desired array element.
Object and array mma!i zers are not primary Xpress1or. Examples:
that specify property and element values. . var obj {x : l ,y : {z : 3}} ; // An ooject
. / ob· d . ·ti· lizers are expressions whose valu e 1s a newly created Object or array "!'\.
-.../ Ject an array mt a . .. . "'i!!c var a r r [obj,4 , [5 , 6] ]; // An array that contains the ooject
are sometimes called as "object litera ls " and "array literals . ob j .x // l : property x of express io n obj
An a rray initiali zer is a comma-separated list of exp ressions surrounded wi th a s_guare brack~llt obj . y.z // 3 : prope rty z of expression obj . y
value of an array initializer is a newly created a rray. ob j ["x" ] / I 1 : property x of ooject obj
Th e elements of th is new array are initiali zed to the values of th e comma-separated expressions: arr[ l ] // 4 : element at index l of expression arr
_J 11 An empt y ar ra y: no expres s ions inside br a ckets mea ns no elements arr[ 2][ "l "] I I 6 : eleme nt at inaex 1 of expression a rr [ 2]
arr[0) . x // l : prope r t y x of expression ar r[0]
[ 1T2 , 3+4 j II A 2-element array.
Firs t eleme nt is 3. second 1s 7 The element expressions in an array initializer can themselves be arru
initia li zers, which means that these expressions can create nested arrays: · /
am Invocation Expressions
An invocation expression is used for calling (or executing) a functi on or method . It sta rts "'·1th a
ar atrix = . i l , 2, 3 ], [4 , 5, 6), [7,8J 9 ]]; function expression rhat identifies the function to be called.
The element expressions in an array initiali zer are evaluated each time the array initializer i The functio n expression is followed by an open parenthes is, a comma -separated list of zero or m ore
evaluated. Th is means that t.lie va lue of an array m1tiali zer expression may be different each timei parameters and a close parenthesis.
is evaluated. Examples:
find (0 ) /I find is the fun ction expression; 0 is the argument expression.
Object in malizer express ion s are like array imtralizer expres sions, but th e square brackets an
..:.. Math.max ( x,y, z) II Math. max is the funct i on; x, y and z are the argume nts.
rep aced by curly brackets, and each subexpression is prefixed with a property name and a colon:
arr. s ort () II ar r. so rt is the function ; there are no arguments.
P = x: 2.3, y. - - . 2 }; II An obJ eet: witn 2 prope rties
When an invocation expression is evaluated, the function expression is evaluated first, and then th e
i. a r q = {};
II An empty obJect witn no properties argument expressions are evaluated to produce a list of argument values.
q.x = 2 · 3; c . 2; II Now q nas the sa me propert i es a sp
Object li terals can be nesred. For example: " ' JAVASCRIPT STATEMENTS
va rec ra ng e = { upper eft { A JavaScript program is simply a sequence of one or more JavaScript statements. Java Script
· x: 2 , y· 2 }, lowerRighc : { x; 4 , y: 5 } }; statements is used to define the logic to make something happen. A stat ement is a line(s) o f code that
The expressions m an object ini tialize performs some specific task/operation.
evaluated. They need not h r are evalu ated ea ch time the object initializer ~
fil!ll!R .· ave constant valu es bur c b b"
an ear urary JavaS cnor expressions. A statement can set a variable equal to a value. A statement can also be a fun ction call, i.e.
~ Function Definition Expressions - documen t.writeQ. Statements define what the script will do and how it will be done.
A program is usually not limited to a linear sequence of instructions. During its process. it may
A Java Script function 1s defined with help of funcu _ . . cb diverge, repeat code, or take decisions. For these purposes, control structures specify what h3 s to Le
an expression is the n ewly defi ned functi;n. on dermmon expression, and the value of su
done to perform the program.
/ A function definiri n expression is also kn .. _ / Program statements that affect the order in which statements are executed, or that affect hether
. . own as funcu on Li t e l " statements are executed, are called control structures.
A iu ncti n definmon expression cons·st f h ra · .
O
lisr of zero or m re parameter in P're ths t e keyword "fu nct10n " followed by a comma-separatel! They affect the flow of simulation code since a control structure evaluates statements and th ,
curly braces.
" n eses and a bl k f
oc o JavaScript code (the function b Y
od )in executes code according to the result. Essentially, there are three control structures
Example: 1. Sequence, where information flows in step-by-step . Sequence stateme~ t s exe cutes tr\!:'
statements of a program in a linear way one a fter another without any condition .
ar sq are fun cti on ( x) r et 'rn x • x; } 2. Selection (decision or _b ranched or conditional), where the decis ions are mad e a ccording O
hi s funct i on some predefined cond1t1on.
ret ur ns the sq a re of the value passed to it·
_ Basics of JavaS c ~,
1 28
Client Side Scripting Langu•a• . f steps) is repeat d · ~ Client Side Scripting Language 1.29 Basics of J.vaScrlpt Proqrwnm ng
. . . ) where the logic (sequence o e In a laop
3. Repetition (looping or iterative •
the desired condition is satisfied. ~ i f Statement
• The if statement 1s the fundamental control statement that allows JavaScript to make decisions and
execu te statements conditionally.
We can use the if statement to execute some code only if a specified condition is true.
Syntax:
1 f ( conditi on )

/ / execute this statement i f con dition is True;


}
The keyword if specifies that what follows is a decision control instruction. The condition to be
(c) Repetition
(a) Sequence (b) selection checked is always enclosed in round brackets Q. The statements to be executed. if the conditi on is
Fig. 1.4 true. are added in curly brackets {}. normally called an if block.
Statement id entifiers are reserved words and cannot be used as variable names (or any other thingit Example 1 :
Following table list some of the JavaScript statements (reserved words) you will learn about in th! <ht ml >
chapter: <head >< t1 tle >If statement </ title >< / nead >
ISr.No. Statement
1f else
Description
Marks a block of statements to be executed depending on a condition.
] <body>
<script type ="text / j av as c rip~ ">
1.
Marks a block of statements ro be executed depending on different var x = 7;
2. SWl tc h
cases. var y = 7;
Marks a block of statemen ts to be executed whi le a condition is true. if ( x==y )
3. whil e
{
4. do whil e Executes a block of statements and repeats th e block while a conditiOll
document.write ( "Bot h are equal •);
is true.
5. for / Marks a block of statements to be executed as long as a condition is
I rrue. </ scr ipt >
</ body >
6. f or in Marks a block of statements to be execu red fo r each element of an </h t"1L
object (or array).
Out put:
r----;;7~·~----:b~r:e~a~k ~;:--~~r.7:
T~erm=::~in~a~t~e~s~a~s~wi~·~rc~h~o~r~a~lo~o1p~.~~~~~~~~~~~~~~~~J / B oth :,;re ~qc.a.l
8. continue I Jumps out of a loop and stans at the top. f
Notice t hat in above example the condition we are checking is x == y . Double equal s ign is a
comparison operator. Single equal(=) is not used to compare, as javascript uses it to assign values to
11
variables.
/ · catc h Marbkls tkhe block of statements robe executed when an error occurs i;;-; / Example 2:
try oc . ~
<html>
12. throw Throws (gen erates) an error. I
<body>
13. try Implements error handli
14 va r TD ng to a block of statements. <script type="text/ javascript">
· ec Iares a vanable. var age = 20;
1111 Selection Statements if( age > 18 ){
doc ument . write ("< b>Qualifi es for driving </b>");
• Selection statements perform different decisions • • d
execute a specified smgle statement or gr
1 • .
O
oup of statement .
.r
cond1t10ns among different statements an
Se.ectwn sta tements provide multiple exe . . sand ignore rest o f t he statements. </script>
time a ccording to the condition. cunon paths m which they execure one execution path at a <p>Set the variable to different value and then try ... </ p>
In JavaScript we have the following condnional (sel . </body >
1. if Statement: Use this statement toe ection) statements </html >
'f xecute some cod . . Output:
2. 1 ••. else Statement: Use this statement to e only 1f a specified condition is true.
code 1fthe condition 1s false execute some code Ifth d . d anothlf QnaUDes for drMn&
. . e con Itlon is true an
3 . 1f...else1f.... Statement: Use this state
. . ment to select ed Set the variable ro different ,-alue and then try..
4 . sWJtch Statement: Use this statement t one of many blocks f d t be execut
oselect one Of o co e o
many blocks of code to be executed.
_ _ _ _ _ _.cce.ccas"'l-=
cs:..o
:c:l'-!J'.!!a~vascr1 • - -

~
1.30 -
~c~11~
,n~t~S~ld~e~S~cr~lp~l~ln~9ll•~n~g~ua~9~•-------------

vm:n if... else Statement . o execute statements in more controlled.way. We ca


The if...else statement allows Javascnpt ~ ·fa condition is true and another code if the conditjn Ulf
1
Example:
, html >
1.31
Basics ol Java Sen r Pro ramm ln

0
the if.. .. else statement to execute some co e nu
<body>
not true i.e .. false . 1 if the cond ition is true. It does not do anything if
The keyword if executes a statement on Y t~ <script type= "te xt / javas cript ">
condition is false . var your __ age = 14 ;
Syntax: var friends __ age = 16;
if ( condit i on) if (your__ age >= 18 )
{ {
execute this statement i f cond i tion is True ;
doc ument .write (" Get a dri vers license" );
~ else
{ else if (friends __ ag e >= 18) {
execute t his sta t ement 1f condit i on is Fa ls e; document.wr ite("Le r thi s frie nd drive the car ") ;
} t ent in the if block is executed, and the st t
In above syntax 1f the condition 1s true. the sta em . Is bl k 15. a enien1 els e
in else block is .skipped. If the condition is false . the statement m e e oc executed, and th,
doc ument.wrlte ( "K ids, stic k t o bicycle" );
statement in if block is skipped. ----..
Example:
</ scri pt >
<html >
<body> </ body >
<script t ype=" te xt / java scri pt "> </ html >
var age = 14 ; Output:
if (age >= 18 )
/ iud,. suck to b1cyd<
document . wri t e (" Get a dr i vers li cense.") ;
documen t . writ e( "Dri ve dad s ca r "); ~ Nested if Statement
Th e 1f...else statement is the one level advance form of control statement that allows JavaS cript to
el se
{
make correct decision out of several conditions.

</ sc rip t >


aocument .wrlte (" Anuj a, ri de a bi cy cle . ") ;
aocument.wri t e (" We are onl y 14 ");
Syntax:
If '"" u,e on e if else statement within the body of another if .else statement then It is called as
ncztcJ 1f else sta tement.
\ I

1f (condi ti on 1)
</ body >
</ html >
Output: ,.,__ I ! If rhe co ndition 1 i s TRUE then check for cond it i on 2
rnuJa.ndc a b,cyd~ Yt:u are on!! J.: if ( conai non 2)
{
Aiiii if...elseif... Statement / /I f th e cond1t1 on 2 1s TRUE
sta r ement s;
The if...elseif... statement is the one level advance form of control statement tha t allows JavaScrip!IO
make correct dec1s1 on out of several conditions. ;\
Syntax: el se
1f ( cond1t1on l )
{ I ! If the conditio n 2 is FALSE
execute tn i s stateme nt 1f conditionl i s True; statem ents;
}
else if (condition2)
{
else r
ex e cu t e t his stat ement i f conditi on2 is True;
l'
else I / If the condition 1 is FA LS E then ,.
{ False statements ;
/
;,.
ex ecu te tnis st atement if no condition is True ;

I 1,.'f
Client Side Scnptlng Language

Example:
<html>
<head >
--
i 1 >
tatement <f t t e
1,32

-
- - - - - -----"B""
aa"l'.:.:

'
c•=--o::.:f_,,J~av~a~Sc~ ... - -

would continue executing each statement in each of the following cases.


~xample: For switch statement.
Beale• of JavaScr1 t

'tt d the interpreter


The break statements indicate the end of a particular case. If they were omi e '
Pro ramml

<title > Nested If S


<html >
</ head>
<body >
<body >
<script type ="text/javascript" >
<SC ript >
var grade= ' A· ;
var age = 15 ;
if (age < 70) {
document .write("Entering switch block<br />");
if (age < 30 ) { switch (grade)
document .write (" Age is < 39 ") ; {
case ' A' : document.write("Good job<br />" ) ;
el se { 1· s between 30 and 70" ) ;
document.write ( "Age break;
case ' B' : dqcument . write("Pretty good<br /> ");
else { break;
if (age > 85 ) { case ' (' : document.write ( "Passed <br />");
document . write ( "Age is > 85 " ) ; break ;
else { case ' D' : document.write("Not so good<br / >");
document.write ( "Age is between 85 and 70" ) ; break ;
case ' F': document . write ( "Failed<br />");
break;
default : document. write( "Unknown grade<br I >")
<I script >
</ body> document .write( "Exiting s1<1itch block") ;
</ htm l> </ script >
Output: <p>Set the variable to different value and then try ... </p>
Age i s < 30 </ body >
iiilJ switch...case Statement </ htm l >
Output:
\r~ • Switch statement is used to execute one of the statements from many blocks of statements.
~ Use the switch statement to select one of many blocks of code to be executed. Entenng swttch block
Good Job
The objective of a switch statement is to give an expression to evalu ate and several different ex iting swttch bloc k
statements to execute based on the value of the expression.
Set the ,·~nabk IO different value and then tlj·...
The switch statement begins with keyword "sWJtch". and round brackets that contain an expressioa
The interpreter checks each case against the value of the expression until a match is found. U We use the default keyword to specify what to do if there is no match.
nothing matches, a default condition will be used .
Syntax:
IIIJI Looping Statements
Sometimes, we want to do something fixed number of times or until a particular condition has been
switch (exp ressi on ) met. In JavaScript, this repetitive operation is done using loops. Loops can execute a block of code a
number of times .
case condition 1: statement ( s) When a sequence of statements is repeated against a condition, it is said to be in a loop. Using
break ; looping. the programmer avoid writing the same set of instructions again.
The looping process can either be one time or multiple times until the desired output is obtained
case condition 2: statement (s ) within a single program.
br eak ; Looping is the process that repeats a single statement or a block of statements in a program until a
specified condition become true.
JavaScript supports following kinds of loops:
case condition n : statement ( s ) 1. for: Loops through a block of code a number of times.
brea k; 4 2. for ...in: Loops through the properties of an object.
defa ul t : statement ( s ) 3. while: Loops through a block of code while a specified condition is true.
4. do/while: Loops through a block of code while a specified condition is true.
Basics of Javas~
1.34
Client Side Scnpting Language

vtiiiJI
-----
for Loop
·11 use when we
want to create a loop . The for loop is th
. eillct
. . one property from obJect
In eac h Jteranon . blena.Jne an d t!his loop continues till all
. 1s assigned to vana
• The for loop is often the tool. we W1 h i !lowing three important parts. the properties of the object are executed.
compact form of loop ing and includes t . . e _o Ji ze th is counter to a starting value. The initiaJiza . Example: For for . in loop.
1. The loop initialization where we inma <n: rn l >
sta tement is executed be fore the loop beg ms. condition is true or n ot. If condition is .... <boay>
. h will test 1f the given ""eti_ <scri pt t ype= "text / j avasc ript ">
2. The test statement w h 1c d ·herwise loop will come out. -.:: var aProperty ;
. . . th will be execute ot
code given ms1de e Ioop . d crease the counter. do cument . wri te ( "Naviga tor Obj ect Proper-ties <br I > ");
. can increase or e for ( aProperty in navigator ) {
3. The iteration statement wnere we ed b a semicolon(·).
We can put a ll the three parts in a single line separat y ' aocument . wri te ( aProperty );
document . write (" <br />");
Syntax;
f or ( 1n1 uall ze; condinon ; incr eme nt ) docu rr.ent . write (" Exi t i ng from t he oop !" );
</ script >
</ boay>
exec .rte state- ent s ;
</ ht ml>

pample: For for loop


vl!l!I while Loop
Th e purpose of a while loop is to execute a statement or code block repeatedly as lon g as expression is
<lit
true. Once, expression becomes false , the loop will be eXJted. The while loop loops through a block of
<1ec r. > code as long as a specified condition is true.
cs crio~ t yoe ="t E>Ct / j 2va ~ ipt "> The keyword 'while' creates a loop that tests an expression, an d if it is true, executes a block of
for ( ar x=6 ; X< =10; x~ ) statements. i>.nd the loop repeats, as long as the specified condition is true.
Syntax:
aoc ~e t . w~i te (" The nu be r is : • Tx); 1n1: 1a1i ze ;
doe<re t . wr1te ( ".<br /> ·); ·• i le ( c ndi t ion )

</ sc-iot> execu te statement ;


</he aa > i ncrement ; f

<! t . >
Output : /ample: For whi le loop.
7).~!ll- <m:ml >
71::-~~ - <neao >
n..=x:, £
, ;!it~!l s, <Scrip t t ype ="t ext / Ja vasc rip t ">
~ ~ : s : ·J var number :;:; 3;
wn1le ( nu ber <= 10 )
:n above progra m w en the for loop is executed for the first time the value of x is 6. NoW ti'I
rondi ·on x< =lO is checked. Since xis 6, the condition is true and he. sta te ments inside the for~
oocume nt.wr it e (" The numoe r i s: • +n ber) ;
gets executed.
doc u ent . wri te (" <br/>");
When ronrro! reaches die closing bracker.s of for loop, the control goes back to the beginning offcJ number++ ;
loop. The.r e tne valu e of x gets. mcrememed by 1. Now th· e vaIue o f x 1s
. . Agam· the condition~
7
chec.1<.ed and th e who process is connnued m il the condition is fals e.
AifJj for ... in Loop </ scr ipt >
</ head >
,, There :.s one more oop s:upponed by JavaScript and it ·s called f . . in loop is usedt:i </h t l>
loop through an object s properties. or/ m loop. Tne for Output:

~_ synu~
~- • _.not er words . the JavaScri p for / in statement lo th . T'bc"""'t•n J
ops rough th e propert ies of an obJect.
~ / Tbcctallbcr u "
n.. - .. l
.,..,.. .; ,:. ... ' var :a cle a-;,:;e ooject ) l\tGl:m.t:e~ 6
!l.t!:m=,b,:r ~ 7
Tott:DR.t;u :s i
n..- .. 9
T'bc._i,,,,. ,. IO
Basics of J1vaScrl t Pro rammi
1.37

. . . JifJ• do ...while Loop


• Sometimes, we want some statem
ents to be execu
.
ted atleast once even if the condition .
ls %
et~
Example: For break statement.
<html >
.:,.[.-
( I'
. d h' sea do-while loop. <bOOy >
the first time. To o t 1s we u . This loop will execute the code block O
. . · t f the while loop. . . nee b , <script type="text / javascri pt" >
The do .. while loop 1s a vanan o . . at the loop as long as the cond1t1on is true ' e,ori var x = 1;
11
checking if the condition is true, then it WI repe t th t the condition check happen · oocument . write ( "Entering the loop <br / > ");
. . . ·1 th while loop excep a s at thee while (x < 20 )
The do ...wh1le loop 1s s1m1 ar to e . be executed at least once, even if the conditio . nd~
the loop. This means that the loop will always n IS faJse. {
if ( x == 5){
Syntax: brea k; // brea ks out of loop completely
do }
x =x + l;
document . write ( x + "<br /> ") ;
Statements to be executeo ;
} while (expression ) ; do cument . write ( "Exi t i ng the loop! <br / > ") ;
~ a mple: For do .while loop. </ scri pt >
</ body >
<html> </ html >
<body > Output:
<script type= "text/ j avascri pt "> Ente ri ng the loop
var count = 0;
0

2
doc ument.write ( "Starting Loop" + "<br / >"); 4
do{
oo cument . write ( "Current Count : " .. count + "<br I> " ); Exiting tne loop !
count++; v llffl continue Statement
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
while ( count < 5) ; continues with the next iteration in the loop.
do cument.write ( "Loop stopped !") ; Syntax: continue;
</ sc ript> Example: For continue statement.
<html >
</ body> <body >
</ html > <script type= "text / javascript" >
Output: var x = l ;
document. write( "Entering the loop <br /> ");
S2tt11lJ Loop
Cu.rren1 Counr O while ( x < 10 )
C'un'en1 Count l {
CUrmir Coum ~
Current Cowu 3
x =x .,. 1;
Cu.rm.it Count 4 if (x == 5) { continue;// skip re st of the loop body
Loop sropptd' }
Set the \Wable ro different \'llue ind theD u; document.write ( x • "<br />") ;

IIIJ Loop Control Statements document.write("Exiting the loop!<br /> ");


</ sc ript>
JavaScript provides full control to handle loops d . · atiOI </ body >
when you need to come out of a loop with a_n switch statements. There may be a situ </ html >
. . out reaching its bottom Output:
There may also be a s1tuat1on when you want t 0 5k'1 · th el1
iteration of the loop. P a part of your code block and start en r-=--------~~
Entering the loop
• To handle all such situations, JavaScript provid b . en~ 2
are used to immediately come out of any loop es reak and contmue statements. These stat_einely J
or to start the n · · pect1V · 4
15111 break Statement ext 1terat10n of any loop res 6
v break statement indicates the end of that particular ... ()I)(
7
8
of a switchO statement. case. The break statement is used to JUIIIP
9
The break statement can also be used to jump out of IO
The break statement breaks the loop and cont' a 1oop. L Exiting the loop!
Syntax: break ; mues executing the code after the loop (if any).

! ~ ~ A~tr.sn.a..-..• ...,v:.--.-' ~ - -- - - - - - - - -·-


Basics of JavaScrl t Pro ramml
Client Sid• Serl tin Lan u1 • 1.39 . 'I bl to
n the method is a va1 a e
CLASS AND PROPERTIES . . m ing patterns to make classes eve . Since show() is in the prototype of Person, and pl is an instance of Perso ' rti
• I well-known p1 og1an1 n IVUh. '. pl. r o'i towing code shows the complete construction of class and use of prope es.
In Java Script there are seveia ·~
us ing the class keyword. . n:ample:
.
Defining a Class usmg Construe
tor Functions : b ' t Tl
d to onstru ct n ew o Jee s. 1e new operato . v ·- <htm l >
. . f tions that are use t1s llti; <head >
c nstmctor funwo ns aie unc . ctor fun ction . <t itl e > Class and Properti es </ title >
to create new ins tances based on a consnu t rs such as n ew Array() a nd new DateO but </ hea d>
. . J aS cript onstruc o · . • We l:li
we have seen some bu1 1t-111 av h ' h to build new obJects. <OOdy >
als o creat e our own custom templates from w ic <Sc ri pt >
function Pers on( name , age ) {
, I I ni ti alizing a ons tr'uc t or fu nction
thi s . name = name ;
' unct i on Per·son( name , ag e ) { this. age = ag e ;
th i s. name = name , }
/ / Add i ng a method to the construct or
thi s. age = age ; Pers on. prototype . show = funct i on () {
return ' Name= ${th is. name } Age= ${this . age}';
) t . fu ncti·on called Person with two parameters: name and ait // used backtick key above tab key
We have created a co nstrue or . .
Internally. when above code ts translated to the class syntax. it would look hke as follows:
var pl = new Person ( "Meena ksni" , 35);
1/ I nit ia lizing a class defin it ion
ao cument . write ( pl. show ( ) );
class Person ( </ script >
con structor (n ame , age ) </ body >
i:h 1s. name = name, </ ht ml >
this . age = age ; Output:
Name = Meenaks hi Ag e= 35
)
The only difference in the syntax of the imtialization is using the class keyword instead of functiO!I
WI Querying and Setting Properties

.
As earlier explain dot syntax or square bracket[] is used to obtam the value of a property. The left-
and assig ning the properties inside a constructor() method. hand side of dot( .] should be an expression whose value is an object.
Now we can create a new ins tan ce with new. If using the dot operator, the right-hand of dot[ .] must be a simple identifier that na~es the
-¥ va r pl = new Person("Meenaksh 1" , 35 ); property. If using square brackets, the value within the brackets must be an express10n that
Defining Methods in a Class : evaluates to a string that contains the desired property name:
The co mmon practice with co nstructor functions is to assign m ethods directly to the prototyp va r nam e= Per son . name ; // Get th e "name" property of the Person class
instead of in the ini tialization, as seen in the show() meth od below: var age=Per son.age ; // Get the "age " property of the Person class
func ti on Person ( name , age ) { ../( OR
this.name = name ; var name=Person("name"]; // Get the "name " property of the Person class
t his . age = age ; var age=Person[ " age"] ; // Get the "age" property of the Person class
To create or set a property, use a dot or square brackets as you would to query the property, but p u t
them on the left-hand side of an assignment expression:
I I Adaing a methoa to the construc tor
Pers on.city= " pune"; / / Create an "city" property of Person.
Person. prot ot yp e . show = functi on( ) {
OR
ret urn · Name= ${this . name} Age= ${thi s. age }',
Pers on["c i t y"] = "Pune"; / / Set the "main title" property.
Internally, with classes this syntax is simplified d h . the cJaSS· Example: For querying and setting properties.
Using the method definition shortha d . · an t. e method can be added directly to rnOfl <html>
concis e process. n introdu ced m ES6, defining a method is an even
<head>
class Per son {
<title > Class and Properties </title>
cons truc t or ( na me, ag e)
</head >
this.na me = name ;
tn 1s.a ge = age <body>
// Ad di ng a method to th e constructor <script>
shOw() { function Person (name , age) {
return ' Name= ${this.name} Ag e= ${th ' this . name = name;
l s .age} ';
this. age = age ;
Basics of JavaSc
1.40 rl tP,
Lan ua e . .. ). · t crea t ion
/ / obJee ·
( "Meenaksh1 , 35 ' Client Side Serl tin Lan ua e 1,41 Basics of JavaScrl t Pro ramm•
var pl = new Person e+ " Age="+ pl. age); // Querying P

~~
. ( "Name="+ p1 . nam . .. rope
document.writ:
Person . city= Pune ,
"· // setting a "oty property of Person.
// Get the "city" property of the Person
rt1 11
1111 Property Getters and Setter
._/
J:'- m. f'
A JavaS~ript object is a set of key/value pairs. Each pair i~ perty". There are two kinds of
var city=Person . oty . ) Class
document. write ( " City= " + city ; properties:
/ Data Property: This is the property most of us are familiar with, and is the property used in 99%
</ script > of code.
</ body > -.../. Accessor Property: Properties defined by getters and setters are known as accessor prop~es.
</ html>< / html> Accessor property generates its value dynamically when being accessed or set. (it calls a fu nction
Output: implicitly).
Name- Meenakshi Age 35 Ci ty=Pune An object property is a name, a value, and a set of attributes. The value may be replaced by one or two
l!!J Deleting Properties
methods, known as a gettei:., and a setter.\Eroperties defined by getters and setters are sometimes
known as accessor propertieito distinguish them from data properties that have a simple value.
The delete operator removes a property from an object. Its single operand should be a pro When a program queries the value of an accessor property, JavaScript invokes the getter method
access expression. Surprisingly, delete does not operate on the value of the property but 0~ (passing no arguments). The return value of this method becomes the value of the property access
~~~( ~ expression.
delete Person . city; / / The Person object now has no city property. When a program sets the value of an accessor property, JavaScript invokes the setter met hod ,
OR passing the value of the right-hand side of the assignment. This method is responsible for "setting,"
delete Person["city"); // The Person object now has no city property. the property value. The return value of the setter method is ignored.
l. If a property has both a getter and a setter method. it is a read/write property.
In following code two types of objects are created using object literal (object literals allow y
directly create plain objects) and second using function constructor. OU !
-K 2. If a property has only a getter method, it is a read-only property.
3. If a property has only a setter method, it is a write-only property.
<html > • Properties can be created at the same time when you create an object or can be added into an
<head > , ~ stin~
<title > Class and Properties </ title > ...........- Followfog example shows how to define accessor properties when creating a new object from an
</ head > object literal.
<body >
Accessor properties are defined as one or two functions whose name is the same as the property
<script >
name and which the function keyword replaced with get and/or set.
/ / object creation using object Literals
var x = { Example: For getter and setter property.
name : ' Meena ksh i · <ht ml >
<head >
}j
<title > Class and Properties </title >
document.write("Name= " + x.name+ "< br >" ) ; </ head>
<body>
delete x. name;
<scri pt >
document.write (" Name= "+ x.name+" <br >")· var person = {
/ / obj~ct creation using function constru~tor name : "Meenakshi",
function Person (name , age) { age: "35" ,
this. name = name. get fullName () {
this. age = age; ' return this. name + " " + this .age ;
},
var pl = new Person( "Meenakshi" 35) . set fullName(name ) {
document.write( "Name=" + pl ' ,, ' · - - -var parts = name . split ( " ") ;
Properties . name+ Age=" + pl("age"J+" <br >"); //Query!~ this.name = parts(0);
delete pl. name · t tris.age = parts[l];
document.write( "Name="
Properties + pl . name + " Ag e= " + pl ( "age" J ) ; //Querying };
</ script> document.write("Name=" + person.name + " Age =" + person.age);
</ body >
per~.~n. fu ll~ame= "Anurag 39 "; / / set properties / / get Properties
</ html > 1
Output: doc ument.write ( "<br > Name=" + person. name + .. Age=.. + pe rs on . age );
Name= Meenakshi I / get Properties
</script >
Name= undefined </ body >
Name=Meenakshi Age=35 </html>
Name =undefined Age=35 Output:
The delete operator only deletes own pr ~~.- - - - - Name=Meena kshi Age=35
· f opert1es n t · h - - - - - - -------:- :...iff,
you must d e Iete 1t rom the prototype ob. . • o in erited ones (T d 1 . h rited proP"'·', Name-Anurag Age=39
Ject in which . . d , o e ete an in e
11 is efined).
~
C.llent Side Scripting Language 1.42 Basics of JavaScript Pr ~

• We can also define getters and setters on an existing object, for that ~se Object.defineProperty. The
Object.defineProperties allows you to set more than one property at a time.
Example: For getter and setter on existing object.
<html>
<head>
<title> Class and Properties </title >
</head>
<body >
<script >
var person= {
na me : "Meena kshi " ,
age: "35 "
};
Object. def in eP roper ty ( person, "full Name", {
get: f unc t ion () {
r etu rn t his . name+" "+ t his . age;
},
s et : f un cti on ( name ) {
var part s= name . sp l it (" " ) ;
t his. name= pa rts( 0];
t hi s .age = part s [l ] ;
}
} ) j
do cu ment.writ e ( "Name= " + pe r son . name + "Age="+ person.age),·
I I get Properties
pe r son .full Name = "Anu r ag 39"; //set properties
document .vir it e(" <br > Name=" + person.name+ " Age="+ person.age);
//get Propert ies
</script >
</body >
</html >
Output:
Name=Meenakshi Age=35
Name-Anurag Age 39

f4it4it44·)if#iit·i,h
1. What is script?
2. Describe types of scripts with example.
3. What is JavaScript?
4. Enlist features ofJavaScript?
s. What is an operator? Which types of operators are used by JavaScript?
6. Explain the terms: (i) Method, (ii) Property, (iii) Event, (iv) Object name.
7. Describe the term expressions in detail.
8. What is loop?
9. Explain for decision making statement in JavaScript.
10. What is meant by event? Which events are used by JavaScript?
11. Describe delete properties in JavaScript.
12. Explain querying and setting properties in detail.
13. Compare client-side scripting and server-side scripting.
14. What are the advantages of JavaScript?
15. Describe setter and getter properties in JavaScript.
•••
,,

~((t-\r.~ay, Function and String


i::: .. ~ ' .~ ( ,, ' ~:{, 1.•

[ Chapter Outcomes...
[!] Create array for the given problem.
[!] Perform the specified stri ng manipu
· Iat10n
· opera t10n
· on the given
· ·
stnng(s),
l!l Develop JavaScript to implement the given function.
l!l Develop JavaScrip t to convert the given unicode to character form.
l!l Develop JavaScript to convert th e given character to unicode and vice-versa.

!.Learning Objectives...
l!l To study Concepts of Arrays in JavaScript
l!l To understand Functions in JavaScript
l!l To learn Basic Concepts of String in JavaScript

DJ! INTRODUCTION ''


• Array, function and string are the basic concepts in JavaScript.:f_he Array in JavaScript are used to
store multiple values in a single variable~
• Array stores a fixed -size sequential collection of elements of the same type.
• An array is used to store a collection of data, but it is often more useful to think of an array as a
collec.tion of variables of the same type.
- • A JavaScript function is a block of code designed to perform a particular task. A JavaScript function
is executed when "something" invokes it (calls it).
• A function is a group of reusable code which can be called anywhere in the JavaScript program. This
eliminates the need of writing the same code again and again. Functions allow a programmer to
divide a big program into a number of small and manageable functions.
• The string object in JavaScript lets you work with a series of characters. JavaScript strings are used
for storing and manipulating text. ,/' •.

D l'ARRAY~-
"-"' Array is used to store a set of values in a single variable name.
• Arrays are a fundamental part of most programming languages and scripting languages. Arrays are
simply an grdered stack of data items with the same data type.
• Using arrays, we can store multiple values under a single name. Instead of usin a ~arate variable
for each item, we can use one array to hold all of them.@n array is a special variable, which can hold
more than one value at a ti~
•• [2.1]
2.3 Arni , Function •nd Strl

RR . ll because arrays are merely ~ ample:


mu Declaring an Array dl d a1rnost I~
s are han e --c:-ties anu me
thods . a spetiai <ht ml >
• In JavaScript. obJects and array ~~ <head >
kind of obJect. Both objects and arr::1~ple values in a single va:1: a ~alue to an element of <t itle > Ar r ay </ t itle >
JavaScript arrays are used to store . t do noVWhen you ass gl - .. he llo .. ) the length an arra,
\onath nrooertY. but obJeC s '.;.\'' Ar r ay[100 - ' propern, </ hea d>
GArrays have a~ ;.
whose index 1s greater than its Ieng
th (for example, my
th similarly. 1f you m
ake th e len gth p roperty small --, ~
er, an,
<bod y>
automatically increased to the new lengthg ·fthe array is deleted <s cri pt >
element whose index is outside the len ° 11ar items= new Array("One", "Two", "Three") ;
Single Dimensional Array: tax used in creatin g a new object. Use Arra..r. document.write (" Length of array is : " + i terns . length) ;
. . x is same as syn ,v / s cr ipt >
• Since. array is an ob1ect. its synta
constructor to create an array. . . t ways· </ body >
You can invoke this constructor in three disnnc . output:
/ . Call it with no arguments: Len gth of ar r ay is : 3
var a = new Arra ( ; .
This method creates an empty array with no
elements and is equivalent to the ar r ay literal[].
. gth·
1!11 Defining Array Elements
.,,hich specifies a 1en · Array is used to store a set of values in a single variable name. In order to differentiate between these
•. _;Y. Call it with a single numeric argumen t · \ set of values. Array make use of index.
var a = new Ar ra y( l 0 ;
. .
· f
ra with the specified length. This orm o
f th A Q
e rray constructor once an array is declare we can define its elements as follows:
This technique creates an ar Y k w in advance how m a ny elements will bt 11ar i t ems= new Array ( 3) ;
can be used to preallocate an array when you no items [0] "One" ;
required. · l f th i tems[l] = "Two" ;
J Explicitly specify two or more array elements or a single non-numeric e ement or e array: items [2 ] : "Three";
11ar a = new Array( S, 4 , 3, 2, 1, "t est in g, t esti ng" ); As Javas c~pt ~ aticaU:y changes the value oflength when you ~elements to an array that you
In this form. the constructor arguments become the elements of the new array. created with the Array keyword. f>.rray indices in JavaScript always-start at 0, not 1, so the length
property 1s always one greater th.ffiThe largest index in the array. ·
~ ple: Accessing an array value is quite easy. We use array index to access a value. lf we want to access vall
<html > from th e ab ove syntax, we use Array[OJ. So,
<head> Arr 2y[ ~] holds «one"
<tit l e > Ar r ay </ tit-e > Ar ay [ l ] holds "Two"
</ ead> Array [2] ho l ds "Thr ee"
<cod >
<script > ? mple:
ar a l = ne Arr ay(); <html >
do c r ent .w it e( "Lengt h of 21 ar r ay is :" +al.len gth ); <h ead >
a2 = ew A r ay( 3) ; <t i t le > Ar ra y </ tit le >
</ head >
o c -::e nt ...•rite (" <Or > e gt of a2 arr ay i s :" + a2 . le ngth );
<bo dy>
11ar a3 = e Array( S, 4, 3, 2, 1, "te stin g, t esting");
<scr i pt >
doc~ment .wr i te (" <br > e gth of a3 ar r ay i s :" + a3. l engt h); var items = new Array ( 3) ;
</ script >
items[0 ] "O ne";
</ <ooy>
items[l ] = "Two" ;
Output:
items[2 ] = "Three";
al ar ay i s :0
' a2 array i s : 3 do cument .wr ite ( items [0] );
e , gt • ' a 3 a r ay i s : 6 docu ment .write ( " <br >"+ items [l] );
if~iifjl1ru~:.ti:.ali~·Zll =·=g~an:-: :=- :A:r ~ay~~~~~~~~~~~~~~ --- document.write ( "<br >"+items[2] );
<I script >
Sometimes declara ·on and initializa ·0 n st . iniJ!I </ body>
efforts. Tne f owing example declares an ep ca~ oe combined together to reduce program ' Output:
array v.1th three elem t
ar t s : ne ... f,. r~ a
. . . .
c·o . ·- • •
e , 1wD , ree ") ·
ens. One
While iru a.lm n g array with declaration th ' · and Two
e em ents sho d be separated by a comma. - en all elements m ust specified in parenthesis Three
Arrav Function and Strln
cuent Side Serl tin Lan ua e 2.5

""91 . h each element of the array. Here As arrays are special kinds of objects because of this, you can have variables of different types in the
mail Looping the Array by looping throud~ play elements of the array one by. We 'liil! same Array.
ts of an array and 1s one
• We can display all.elemen by.one m each loop ber of elements present inside th · ,e-,c:arnPle:
i1fcrement the mdex of the array w the total num e •tr.,
. s we must kno . , v <html >
To 1dent1fy how many 1O 0 P · ame length. f rotation or looping and we Will <head >
which can fi nd out usmg array_n . 't of our number O try lt
upper 1im1 <script >
So this number we Wiil set as fOllowmg code
display each element of the array usmg va r ar r = new Arra y(" one","two " , 30 );
docume nt . write ( "Length of array = " + arr . length +"< br >") ;
<html >
for (i = 0 ; i < 3; i++ )
<head >
<script >
var scripts = new Array(); docume nt . write ( "element arr ( i ] +"< br >") ;
script s (0 J "PHP ";
scripts ( 1] "ASP "; </ sc ript >
scripts(2] "JavaScript" ; </ head >
scripts (3] "HTML "; </ html >
for ( i=0; i <scripts. lengt h; i++) output:
{ Length of ar r ay=
document .write (scripts[i] + "<br >" ); element one
element = two
</ script >
element = 30
</ head>
</ html > Two Dimensional Arrays:
The for loop in the above code loops through the elements of the arr~y ~nd display one by one Generally, creating two dimensional arrays is very similar to creating one dimensional arrays. Some
vertically by adding one line break at the end of each element. The upper limit of the for loop is set to languages allow us to create two dimensional arrays simply by adding an index item, however
scripts.length value which is in this case equal to 4 . Q avaScript doesn't support two dimensional arrays]
Save the HTML document and open the page in your browser to see the following output: / JavaScript how ever, allow us to simulate a two dimensional array. We can do this by creating an
PHP "arr ay u f a :1 a rray".
ASP To do this , we create an arr~. loop through the array, and for each element, we create a~ ray.
Ja vaScript Then, we simply add an index for each column of our grid. In JavaSript this would look som ething-
, HTML like as given in following example.
pample: J iample:
<html> <html >
<heacJ > <h ead >
<sc r ipt >
<tit le > Array </ title >
var arr = new Array();
for ( i = 0; i < 5; i++){ </ head >
ar r[i ] = i; <body >
<sc ri pt >
for ( i = 0; i < 5; i++){ var num = new Array(3);
document.write (" element "+ arr[i] +"<br>"); f or ( i = 0 ; i < 3; i++)
num(i] = new Ar ray ( 3) ;
</ script > num[0] [0) l;
</ head > num[0] [l] 2;
</ html> num[0][2] 3;
Output: num[l) [0) 4;
element 0 num[l ] [l) s·
element 1
num[l)[2] 6·
element 2
num[2) [0) 7·
element
num[2) [1) 8;
element= 4
num[2)[2) 9·

/
Client Side Scripti ng Language 2.6 Array, Functi on a

for ( va r i = 0 ; i < num. l en g t h ; i++ )


~
it ems [i t ems . l e ngth ]=·· Eight .. ;
fo r ( var j = 0 ; j < num . length ; j ++ ) i t ems[i t ems . length ] =" Ni ne ";
f o r ( i =0 ; i< items . le ngt h ; i H )
{
document wri t e ( num[ i J[j] + "< br >" ) ;
docu me nt . wr ite ( it e ms [ i ] + ·• ") ;

</ s cr i pt >
</ s c r i pt > </ IJoOy >
</ body > </ ht ml >
</ html > Output:
ze ro One Two Thre e Fo ur Fiv e Six Se ven Ei ght Nine
Output:
IID Sorting Array Elements 1<

~
The in dex of t he array specifies the order in wh ich elements a ppea r in an array when a for loop
_
15

u sed t o display t he array. Som etimes we want elemen ts t o appear in so rted o rd er. w ich m.eans t .a
4
stri ngs will be presented alph abetically and numbers will b e displayed in asce n di n g o rder.
• (rh e elements of an a rray can be di splayed in sorted ord.e r by callin g the sortO method o f the array
objecf\The sort method of Airay object retu rns an Array object with the elements son.ed
E
/ The synt ax of sort meth od of Array object is as follows:
7
arrayObj. sort ( )
8
By default , th e sortQ method calls the strin g casting m eth od o n eve ry array elemen t e it h er i ts
integer, fl oat or strin g. So the result of sortQ method on integer and floa array will n ot as y ou
E111:Adding an Array Element y
expect. To get numbers is ascendin g or der use\f'un ction (a , b) {r eturn a - bfjnsi d e son m ethod .
ampl e :
<ntm l >
<he ao >
<t i t l e > Arra y </ t i tle >
</ nead >
<boo y >
e end o f an arra y and returns th <s c r i pt >
: : e array or c llection. e new length of an array. v ar a r r l = [ " Re d" , " RED" , " r eo " , "Gr ee n " , " Blue " ]
.. . , e_ var arr2 = [ 1 , 20 , 3 , 45 , 44 , 0 . 5
docume nt . write (" Before sort i ng ar r l =" + a rrl ) ;
d ocume nt . writ e ( " <br >Af ter s or t i n g a r rl= " + a rrl. s o r t ( )) ;
oocume nt . wr i t e (" <br> Befo re s o rt i ng arr2= " + a r r 2 );
( r : ::.: : > oocu me nt . write ("< br >Af t ersorting a rr 2= " + a rr 2 .so rt ( f u c t i o n ( a , b ){ r e t r n a- b ) ) ;
</ sc r ip t >
</ boOy >
</ h ml >
Out pu t :
Be f or e s ort i g a rr l= Red, RED, red , Gree n , Bl ue
After so i ng ar r l =Bl ue , Green, RED, Re el, re d
,a- e--s = '""""' 0--2; ' ; ;; Bef o e s or i ng a r2= 1 , 20 , 3, 4 5,44 , 0 . 5
Af ter so r ti ng a 2 ~0 . 5, 1, 3 , 20,44, 4 5
:. : €"- s~e: • e r :: )
::_ s::: By defa . sort m ethod arrange the elemen ts in as cending o r der . ow t o display el.eme ts o f
desce ndin g order make use of i::gverse methods afte r the so rt m et h od as shown in f llo · array
: : 1=- s:2: - - ... € '€ • ; -...,,bample: o wtng ex.amp
: : ="" 5_ 3: • c .J ... • ; < t ml >
<h ead >
<titl e > Arr ay </ tit l e >
</h e ad >
<body >
<scri pt;
"Gr ee n" , " B- ue " j ; .£!!!"' Side Scnptl n9 Language 2.9
"R" • · r eo"
" Red " , c.. ' ~ .
, e., J ,
, _ #

var arr - - . , i t ems [0] "One ";


45 44
a r a rr 2 = .. 1 , 20 , 3 ' i t ems [ l ] "Two" ;
a rrl. sort () ; . • ;n Order .• .. ar r 1.re e r se {) ,. " <or >"); items .2 ] "' Th r ee "' ;
.:ioc ,:e t.writ e( De scend . g ·:· +arr 2 . sor t ( f unc ti on ( a , b ) {r eturn b-a })); va r sl ; i tems. j oi n()
cocur.:ent . wr i te ' "De scend i ng order oo cument . wri t e ( sl + "'< or> " ) ;
</ SC i ;:r:: > var s2 ; i tems . join(' - ')
<, bod > oocument .write ( s2 + "< br >");
<I t ,l> va r s3 ; items . co ncat ()
Output: do cument . wri t e ( s3 + "<br>");
Desce ndin g Oroer : eo,Red,R ED, Gree , SlJe var num ; new Array ( 3) ;
~~De~sc~e~n<l~i~g~O~~d~e~r~:~4~5~,44::=;,~2~0~,~3,~l~,~0~-~5~~~--::~:::::~~~~~~~~~~~~~~~
------.._ num[ 0] "Four ";
l!!R'I combining Array Elements into a string . . num[ l] "Five ";
mM . of an array into a smgle stnng. num[ 2] "Six " ;
• Sometime the re is need t o combine all elements
var s4 items.concat ( num ) ;
Let ite ms is an array cons ist oft.1-iree elements as follows :
do cumem:.write ( s4 + "'< br >"') ;
new Arr ay( 3) ;
"One "; </ sc r ipt >
ite
ite "Two "; </ body >
i t ems 2 "Three "; </ htm l >
By com bi~ing the array e ements means to display contents in a string : Output:
"On e -' Two, Three" On e , Two, Thr ee
/ Array elements can be combined in rwo ways: One-Two -Three
-...,,l< Using the concatO Method: One , Two, Thr ee
• rne concatO method separates each value with a comma. It is used to join two or more arrays. The One , Two, Thr ee, Fo ur , Fi ve, Six
existing arrays does not change but returns a new array, containing the values of the joined arrays. ..../ The slice method of Array object returns a section of an array. The syntax of slice met hod o f Array
The syntax of concatO method of Array object is as follows : object is as follows :
* a r rayOb jl.conc at () 1( a rr ayObj . slice ( start, [end] )
V.'hen concat method is used without any parameter then all elements of arrayObjl will displaye: where,
separated by comma. o Start (Required): The beginning of the specified portion of arrayObj.
a rr ayObj l. conc at ( arra y0o j 2, a r ray0b j3 , _ar r ayObjN , ) c End (Optional): The end of the specified portion of arrayObj.
When concat method is used with parameter then all elements of speci fied arrayObj will combinal The slice m ethod copies up to, but not including, the element indicated by end. If start is negative, it
is treated as lengt h+ start, where length is the length of the array. If end is negative. it is trea ted
~ th arrayObjl.
as lengt h +end where length is the length of the array. If end is omitted, extraction continu es to the
J- Using the joinO Method: end of arr ayObj. If end occurs before start, no elements are copied to the new array.
The join met_h od of ~ay object adds all the elements of an array separated by the specified
~ample: Using join and slice method of array object.
separator stnng. The JomO method also uses a comma to separate values. b u t you can specify I
character other than a comma to separate values. <nt ml >
J The syntax of join method of Array object is as follows:
<h ead >
<s c r ipt >
-ti. a r rayObj . join ( [separator])
var arr; new Array(l,2,3,4,5,6,7,8,9,10 };
Here, use of separator is optional When join method is us d "th a isby
default separator used by JavaScript to · · all e WI out any separator then comm document.write(" <br >After join method "+ arr. join(" - "))
Jom e1ements of array as a string. __.
var newarr;a r r.slice(l,3)
) lxample:
document. write( " <br>After slice method " + newarr )
<h t ml >
</ scr i pt >
<h ead >
</ head >
<title> Array </ title>
</ html >
</ hea d>
Output:
<body>
After join method l-2-3-4-5-6-7-8-9-10
<sc r ip t >
After slice method 2, 3
va r items new Array(3 ) ;
Arra Functlc n anc Stri
2 .11
Client Side Seri

EIII Changing Elements of an Arra~ ta to-do list In


to-do list the elements are added at the end
kt kes its position an11 lt 1111 Objects as Associative Array
• An array can be used to 1mplemen t and second tas a • we have seen the . operator used rn access the properties of an object. It is also ~ossible to u se the
fi r st task of to-do list 1s completed it come ou the first element of an arraYJThe shiftQ . (dot) opera tor, which is more commonly used with arrays. t o a ccess these properties.
l"tavaScript provides sh1ftQ me th Ods to remove k on th e l ist and retuInetJi~
5 the other tas s up Thus. the following two JavaScript expressions have the same value:
7emoves the first element of the array then move rns \
obj ec t . property
removed item. ~
object [ "pro per t y" ]
~ m p l e: The important difference to note between these two syntaxes is that in the first , the p r o perty name
<html> is an identifier, and in the second , the property name is a string.
<hea d > second notation is more popular with associative array. An associative array_is array o f Key:Valu e
<title > Arra y </ title > ...ll ·rs wh s a cts as index t o get any value. The value associated with any key can be accessed
</ hea d > using second notat ion.
<body > we can create an associative array by assigning a literal to a variable.
<script > var a r r = { "One" : 1 , "Two " : 2, "Three" : 3 };
va r items = new Arra y( 3) ; Unlike simple arrays, we use curly braces instead of square brackets. This has im p licitly creat ed a
items(0 ] "One " ; variable of ty pe Object. The content is accessed by keys, whatever the method used to declare the
items[ l ] = "Two"; array.
items [2] = "Th r ee "; va r y = ar r("One"];
items . s hift (); We can not use a simple for loop as the elements are not accessible by an index in associative a gay,
bu t the for in loop is ideal for this. Keys are ass igned to the variable "key", and with the key we access
fo r ( i=0 ; i <i terns . length ; i++)
the value .

document. write ( items [ i] + " " ); ....yxample:


<ht ml >
<head >
</ script >
<t itle > Array </ title >
/ body >
</ head >
Output:
<body >
Two Thr ee
<scri pt >
/ The pop Q method r emove an item from the end of an array and popQ returns the removed item.
var arr = {"One ": 1, "Two" : 2 , "Three": 3};
~xample: for (v ar key in arr )
<htm l>
<hea d>
var val ue = a rr[key] ;
<title > Array </ title >
document.write ( key "+value+ '<br>');
</ he ad >
<body>
<script > </ s cr ipt >
</ body >
var items = new Array(3);
,. i terns (0] "One";
Output:
items[l] = "Two"; On e = 1
items[2] = "Three"; Two = 2
items . pop(); Th r ee
for (i=0;i<items.length;i++)
We can also create an associative array with the Object reserved word , and can assign keys and
{ values as given in following example.
document . write(items[i] + " .. ) ; yExample:
<html>
</ script >
<head >
</ bod y>
<ti t l e> Array </ titl e>
Output: </ head >
One Two <body >
Ana Fur,c1>0n Sf1d S • "
2.13
client Side Seri
<>cr1 ;r ) . .
ar o = new Ooj ec tl )' doc ume nt . writ e ("< br>After pop met hod "+a rr.join ( " , " ))
o[ "One " J = 1; arr . sh i ft ()
o( "Two" ] = 2 ; document . write (" <br >After s hift me t hod "+ a r r . jo i n(" ," ) )
0 " hr ee " J = 3;
arr . rev erse ( )
fo r (var i i n o ) document . write ("< br >Afte r reverse meth od "+ar r . joi n (" , "))
arr.unshift ( l )
" ="
~ o[i] ~ ' <br >' ) ;
oocu ent .write (i + document . write( " <br >Af ter unsh1ft methoa "+ar r. join (" , " ) )
</ script >
</ scri pt > </ head >
</ body > </ html >
Output: output:
After join method 5,6,7,8 , 9
One=l
Afte r pop method 5 , 6, 7, 8
Two =2
After shift methoa 6, 7, 8
Thre e=3
After reverse method 8, 7, 6
Methods of Array Object: . After unsnift me tnoa 1,8,7,6
The following table lists the methods of the Array object:
Sr. No. I Methods I Description 111
=::] /"" FUN CTION _ .
Functions are building blocks of any programming language. Function 1s a block of statements that
1. cone at Returns a new array consisting of a combination of two arrays.
' performs certain task.
2. indexOf i Returns the index of the first occurrence of a value in an array.
/ Functions are of following two types: . . .
3_ j oi n I Returns a String object consisting of all the elements of an ilTij 1 . Built-in functions are the functions that are already defined m the 1avascnpt. Examples are
\ concatenated together. writeO, alertO , promptO etc.
4. l astindexOf Returns the index of the last occurrence of a specified value in an array. 2. User-defined functions are defined by a user. Sometimes, this fun ctions are simple , a nd
~ pop Removes the last element from an array and returns it. sometimes they are quite complex.
~ pus h Appends new elements to an array, and returns the new length of the array. EDI Defining a Function
7. II reve r se Returns an Array object with the elements reversed. Before we use a function we need to define that function .
~ The most common way to define a function in JavaScript is by using the fun ction ke~rd, foll_owed
I
Shi ft Removes the first element from an array and returns it.
by a unique function-name (The name cannot, Begin with a d igit/keyword/ reserved, a list of
~ s lice Returns a section of an array. parameters (that might be empty), and a statement block surrounded by curly braces.
.,,..w. sort I Retu rns an Array object with the elements sorted . A fun ction definition consists of following four parts:
11. splice
Removes elements from an array and, if necessa ry, inserts new elememsm ~ Function name:~ identifier that ~mes the functio aj The name is a required part o f function
their place, returning the deleted elements. declarati on statements, it is used as the name of a variable. and t he newly defined
12 . I toString Returns a string representation of an array. function object is assigned to the variable.
~ - un shift For function definition expressions, the name is optional: if present, the name refers to the
I Inserts new elements at the start of an array.
I val ueOf function object only within the body of the function itself.

~<
===========~==========-~ ~~~ ~~~~ ~:: : :-
II> 14.
I Gets a reference to the array.
y . ' Parentheses:~ pair of parentheses around a comma-separated list of zer o or more identifiers]
._;?x a mple: Using methods of array. These identifiers are the parameter names for the function, and they behav e like local variables
<html > within the body of the function.
<he ad> -,_>.- A code block: A pair of curly braces with zero or more JavaScript statements inside. These
<script > statements are the body of the function : they are executed whenever the bmchon 1s mvoked
var arr new Arra y( ); ~ An optional return keyword: (!he return keyword tells the br_owser t o return a value from the
a rr. pus h ( 5, 6, 7) ; fu nction definiti the statement that called the funct ion]Not all fu n ctions ret u rn a wlue~
arr.push (8, 9) ; For example, a function that displays a message on the screen doesn't need to return a value to
the statement that calls the function .
document .write ( "After j oi n method
arr . pop () "+arr.join ( " , " )) 1111 Writing a Function Definition
..:;:rw;can write a function with argument and without arguments in JavaScript .
....c. ~
Arrny1 Fun ction ftnd Strl
2 14 Ar ra • Funcllon and Stttn
II n t "" ld-, crlp tlng Lnnuung-,
cuant s tdo sen ti ~ Lo_!l~ll • 2., 5
Th e ynt ,x fo r t\m ti n wi th ut ar um n ts Is give n be l w ·
,, Funt t i n \,tl t l1 u t .wgume11 t / p r Jni
l Cl'S - Scope of Variable and Arguments r
_/ ,he sco pe of a variable means h ow the different parts of th e r o ram can acc ess that variabJe. In
. . . . ,.,.1
t typC'• "t 1~ t , J.1 ., - I" pt "'
v 1
JavaS cript t h ere are two types o scope name y , ocal s cope and Q!_obal s cope. .
h 11 1tt1 11 fu n t l on _ n:. mt..' ( ) (ft vari b le ca n b e d lare w ithi n a function wh ich is called a o.cal 1able, b ecause th e
va ri ab le IS lo ~ O th e unctioi}O the r tha n function in whi ch local variable are d e fi ned n o on e IS
<. at eme nt s aware of th e existe n ce of su ch local variables:-
/ A variable can be declared outsi de a fun ct ion which is called a global variable, because it is availab le
, , 5 ri. rp~t~'~~~~~~~~~~~-:-:-:::-:=::-::;-;-::;--:-;;-~IPll~;;-;;:~~·-;:;-;:·~;i:·~~;:-;::-~ - •.! to all parts of you r JavaScr ip .
- - .~: . . t kes 11 0 parameters ca lled sayHello]avaScnpt 1s defmed here. --....
..._,,,E "ampl e: A simp le fun ction t1ia I a • Java Script d evelopers u se the term scope to describe whet h er a statement o f a JavaScrip t ca n u se a
, u ' 11J t t e • " t ext / ja a sc rlpt "> v~ variab le is considered in scope if the statement can acce ss the variab le.
fun ct ion a Hell oj av as r ipt () A variable is out of scope if a statement cannot access the variable.
<scr i pt ty pe ="text / J avas c ript" >
ale 1·t("He ll o ja va.c ript" ) ; var x= 10 ; I / gl obal var iab le
fun c tion add ( )
, , sc i p t'
Her~~ ~-;rtQ is a predefined fun cti on f w ind ow obje_c t wh ich will prompt when user executes the var i t em="pen"; / /local var iable
program nd displays a dialog box ontaining an apphcanon-defmed message. docu ment . write ( "The cost of th e "~ ite m+ " is "+ x);

E!II Adding an Argument </ script >


A function typi ally needs data to perform its task . For example. we could ask the user to enter the
The extent to which a variable is accessible is called its "scope" and is determined b y where t he
salary a nd percentage increase in salary instead ofwritin this data into the fu ·on definition.
variable is declared.
You can use as many arguments as necessary for the function t o carry out it s task. Each argument
A variable declared ins ide a function block is only accessible to code within that same fun ct io n b lock.
must have a unique name , and ea ch argument within the parentheses must be separated by a
(fhis variable has "local" scope and only accessible locally within that function , so is known as a
co m m a . "local variable:.]
~ t a x: • A variable declared outside all function blocks is accessible to code within any funct ion b lock. This
// Function 1, i th arguments / parameters C variable has "global" scope and accessible globally within any function in that script so 1s know n as a
script type=" te xt / javasc ript" > "glob al variable".]
fun ct ion f un ct ion_name ( parame te r-list ) Loca l variabl nerall referable to global variables as their limited sco e re ven ts p o s sible
acc_idental conflict w ith other variables . Global variable iiames must be unique throughou t the en tire
scnpt but local variable names only need · e throu hout their own fu nction b lock - s o the
s tat em ents

---
same va r iable name can be use m d ifferent functions without con fli ct.

</ scrip t >


~ a mple: "-V- J- ('\ () .
<ht ml > 11' ~
y.Example 1:
<he aa >
// A si mple function that ta kes four parameters an d Compute the d istance between
I / Cartesi an points ( xl ,y l ) a nd (x 2,y2 ).
<titl e > scope< / title >
<s cript t ype =" te xt / ja ascri pt "> <sc r ipt >
fun ction dis ta nce ( xl, y l , x2 , y2 ) { var gl oba l= "Global Variab l e <hr >"
ar dx = x2 - xl; fu nction i ni t ()
ar a 2 - yl ; {
return at h . sqrt ( d x• o x + dy •d y ); docu ment .wr ite ( global);
s ho w( ) ; // function calling anothe r f urnc tion
< ' sc r i pt > }
function sh ow ( )
~ mple2:
{
1/ Fun ti o~ exp r essi on s can i nc l uoe function name, wh i ch is u sef u l for recursion.
var local= " Local Variable <hr >"
va r f = fu cti n act ( x) { if ( x <= 1 ) r et urn 1; else return x·f act (x -1 ); } ;
document.write( l ocal);
~ple 3: oocument . write ( global )
11 F 1.1 t1 e xp r essi on s ca n al s o be used as a gume nts t o ot her f unctions :
;Ja ta . s o rt ( f unc ti on( a , b ) { ret rn a- b ; } ) ;
Arra
2.16 Function •nd St~ Arra . Func!ion and Strfn
cuent Sid• Serl tin 2.17
. . . , h f t . n block we have ass ig n e d
</ script > w e have defined a funct10n showO usmg keyword ' func n on . Int e unc 10
</he ad > a value 10 to variable x. The next line is document.writeO statement. . ·
<body > This funct ion showO will not print "The cost of the pen is 10" to t he screen a ll by itse lf. It has to be
<SC ript > called. which we are doin g using the statement showQ;.
init ();
</ script >
EIIJ calling a Function with Arguments

.
In the previous point. we defined a function showO wit h ou t any values m the round brackets .
</ bod y> • In practical situations , we mi ght need t o add some values (paramet ers) in the round brackets.
</ html > 1 1 . bl . d 1 d . ' d f Jyntax:
Here global variable is declared in script whereas oca vana e 1s ec are ms1 e a unction. Save
the HTML document then open the page in your browser to see the values of the global and local functi on functionName ( pa r a_l , para_2 ... para_n ) {
stat eme nts t o be executed ;
variables written by the functions.
0"" _ _ __ - 0

/ xample:
~ c It ~ 1oca1ho~8080 1,, \i•cn..,tr" ... ;:.,Jr ·-.1,•hn2 - <html >
; : · - -y...- -u..w.;u .... O ""• D stoa C] J<..l' <nead >
Global Vm:,abie
<title > Calling Function with Argume nts </ title >
<script type="text / javascript ">
Local \'.iabl<
function add ( x, y ) {
result = x + y;
docu me nt.write ( "aad1tion is : " + r esult) ;
document . write (" cbr / >") ;
CALLING A FUNCTION
Calling a function means using the defined funct ion . a function can be called from any section of
</ s cript>
the code. One can call a function without argument or with argumen ts.
c / heaa >
Syntax: functionName () ;
Above syntax is very simple, just functionName with empty brackets and a semi-colon. cbody >

1111 Calling a Function without Argument <script type =" text / ja vascri pt" >
add(10 , 10 );
A function is called without any argument simply by using function name followed by paramhesis ada ( 23 , 12 );
as shown in following example. </ script >
J xample: </ body >
<h tml> Output:
<head > addition 1s · 20
<title > Calli ng Function without Ar guments </ title >
<script type= "text / j avasc r i pt" >
I. o.dd,uon is 3 S
va r x= 10 ; Notice how we are passing parameter values to the fun cti on. The function addQ is called twice.
function s how ( ) Ev:rytime we want to add two n umbers, we need not write the code for it every single t ime. We can
{ wnte the code once, and call it as many times as we want.
va r item= "pen" ;
document . write (" The cost of the"+ item +" is T x);
EIII ~ailing Function from HTML
A fun_ctio~ can be called_from HTML code on your web page. Now rather han explicitly calling a
fun ctio n , 1t will be called m response to an event, such as when the web page is loaded or unloaded by
</ script > the browser.
</ head >
For example you have written two different functions named as welcome() and goodbye() a nd you
<body> want t he code of welcome function should executed when a h t ml form body is loaded in browser and
cscript t ype="text / javascript">
you want goodbye function should executed when a html fo rm body is unloaded in browser .
show(); For this code will look like as follows :
</ s c ript > <body onloao = "wel come ()">
<body onunl oad = "goodbye ()" >
c/ bod y>
OR
Output:
<body on loaa = "we lcome () " on unload "good bye ()">
The cost of the pen is 10
2. 18 Arra Function and StH
Client Sk:Se Sen tin L•n u1 e Arra . Funcuon and Str. n
2.19
c11ent Side Serl
....p'a mple: fun cuon Valiaat elogon ( id, pwd )
<html >
<head > var Retu rnVa l ue ;
<title > Calling Func tion f rom HTML </ titl e > · aaa ' )
1f ( ia === · 111 · && pwd
<sc r ipt type= "text / javascrip t ">
function wel come () ReturnValue = true ;
else
alert ( ' welcome dear . · ' )
} Return Value = f alse ;
function goodbye ()
{ retu rn Ret urnValue ;
alert ( ' By e bye .. ' )
</ script >
<I script > </ head >
</ hea d > <body onload="Logon ()">
<body onload="welcome () " onunl o ao="goodbye () " > </ body > </ body >
</ html > </ html >
Here. we have called only LogonQ method on body onloadQ evem.(Qnce t he control w ill p ass t o
Logon O method it will call ValidateLo on method im~p:..:l::.;ic:..:i..::tl~y-=)~ - - - - - - ----,
~~~ ~~~

111 ...
Browser call the GoodbyeQ fun ction right before the user moves on to another web page. • •<ti ·

1111 Function Calling another Function


-:,· In a large scale applicat ion which comp r ises of many functions there may be requirement that one
'fi'° function is calling another and w h ich further calling an other in chain . This page says
In JavaScript we can simply call a funct ion either on a specifi c event o r can call it from another Va lid u,gon
function also.
ylxample:
<htm l >
<heaa >
<titl e > scop e </ titl e>
Returning a Value from Function
<sc ript > Sometimes, we w ant the func t ions to perform some calculations and return the result , so that we
function Logon () can use that result outside the funct ion. We use return statement to return a value.
{ A JavaScript fun ct ion can have an opt ional return statement. This is required if w e wan t to r eturn a
value from a function . Th is statement should be the last statement in a function .
var user ID ;
For example, we can pass two numbers in a function and t h en we can expect from the fu nction to
var password ;
return their multiplication in our calling program .
va r va lid ;
userID = prompt ( ' Ent er user ID ' , ' ·) ; ..,...s-'yntax: return val ue;
password = prompt (' Ent er password · , · ·) ; ~ample:
v alid = Valida teLo gon (u serID, password ); <html >
i f ( valid=== true) <head >
{ c ci tle >Javascript Retu r n statement </ ti tle >
ale r t ( ' Valid Logan '); </ he aa >
else <boa y >
<script type= "text / javascript ">
alert (' In valid Logon · ); fu ncc ion areaRe ct( L,B ){
va r area = L• B;
return area;
2.20 Arra ' Function ana St~o
Arra y. Funcilon llnd St ng

-
Client SldG Scri pting Lan guage 2.21
x= areaR ec t ( 6, 8 ) ;
doc ument.wr it e ( x ) ; ,......... I This method returns the index within the callin g Strin g object of the I
5. l ast in de xOf ()
</ scri pt > I last occurrence of the speci fi ed value, or - 1 if n o t found.
</ body >
</ html >
- 6. l oca l eCompa r e () This method returns a number indicating wh ether a re ference
\ string comes before or after or is the same as the g iven string m sort ,
..
ii
Output: order.
48 -::-,,;r: mat c h()
rep lace ()
This method used to match a regular expression a ga ins t a stri:.g .
Th is method used to find a match beti.veen a regular expression and
Jn above program areaRect(6,8): calls the function and passes values 6 and 8. The function calc ~ 8.
the area. and returns it (in our case, 48). Now, after the function has returned a value, areaRe~( tes a string , and to replace the matched substring wit h a new substring.
68 9. s earch () This method executes the search for a match betwee n a r egular
is 48. This value 48, is assigned to x. The statement document.write(x) will print 48 in the webpage · )
expression and a specified string.
/1'0. s lic e () This method extracts a section of a string a nd r eturns a new string.
l!lsTRING s plit () This method Splits a String object into an array of strLr1gs by
y / A string value is a chain of zero or more Unicode cha racters (lett~rs, d igits, and punctuation mark~ v>1"· separating the string into substrings.
-.../" You use the String data type to represent text m Jav aScnpt. You include string lit erals in your . 12. I s ubs tr ( ) This method returns the characters in a string beginn ing at the \
by enclosing them in single or double quotation marks. scnpts specified location throu gh the specifi ed number of characters.
..._r' The String object is used for storing and manipulati n g text. A str ing simply st ores a series of 13. s ubs t ri ng () This method returns the characters in a string between two indexes
characters like "Amar and Akbar". into the string.
14. I t o l ocaleLowerCase () This method returns the characters within a string are converted to
A string can be any text inside quotes and we can use simple or double qu otes as:
I lower case while respecting the current locale.
var car name =" Alto XC60 ";
15. j t olocaleUpperCase () This method returns the characters within a string are converted t o
var carname = ' Al t o XC60 · ; u pper case while respecting the current locale .
The String ~bject let's us to work with a series o f character s and wraps Javas cri pt's st ring primitive 16. tolowerCase ( l This method returns the calling string value converted t o lower case.
data type with a number of helper methods. 17. to St rin g ( ) This method returns a string rep resenting the speci fied obiect.
Because Javascript automatically co_n verts between st r ing p r im itives a n d String objects , we can call 18. toUoo erCase ( l This method returns the calli ng string value converted to u ppercase.
any of the helper methods of the Strmg obJect on a s t ri ng primitive. ~ - valueOf () This method returns the primitive value of the specified object.
Creating a String object use following syntax: Jxample: For the length of a string.
--k var sl=new String (); // empty str i ng <ht ml >
va r s2 = new String (" Mee na kshi " ); <body>
V The string parameter is series of characters that h as been p r operly encoded. ,; c- 1pt >
1111 Manipulate a String va r t xt = "Hello JavaScript World!" ;
document . write ( "<p>" + txt.length + " </ p >");
In javascript there are various properties and method s associat ed w ith St r in g object. w e can make var t xt="Amar and Akbar" ;
use of these to perform some manipulation o n strin g. aoc ument . write ( "<p>" + txt.length + "</ p>" );
String Properties: </ s c r ipt >
</ body >
.Sr. No. Prope rty Description </ htm l>
v- constr uctor This property returns a reference t o t h e St ring func t ion th a t created the Output:
23
object.
--./1. lengt h This property returns the length of the st ring . ~
14
, J_o_i_n-in
- g~ a-S_t_r-in- g~ ~~~~~~~~~~~~~~~~~~~~~~~-
J. prot otyp e This property allows we to add prop erties and m ethods to a n object.
Stnng Methods· concatenate a string means form a new string from given two strings b y placing a copy o f the
second string behind a copy of the first string. The new string contains all the characters from both
Sr. Ho. Method Name the first and second strings.
Description
, ,Y. charAt () / In java script we have two ways to concatenate two strings:
This method returns the character at t he specified index.
1. Us ing concatenation operator(+).
-./" c a rC odeAt () This method returns a number indica ting the Unicode valu e of the 2. Using concat function of String.Object.
character at the given index.
/ Concatenation Operator(+) takes two operands. The+ operator does string concate n a tion if one of
co nca t ( ) Thi_s method combines the text of two strings and returns a new its operands is a string and return a concatenated string as follows:
strmg. var str1 new String ( "Meena kshi");
J. indexOf () Th is method returns the index within the calling String object of the var str2 = new String ( "An urag " );
I first occurrence of the specified value, or 1 if not found . var str3 new String ( "Thalor ");
contd. .. . var str4 strl+str3 ; / I Meenaksh iT halor
,--
Arrn Function ond Sirin Arra Function 1nd Sirin
Client de Seri Ung_ Longuo o ct11nt Sid• Serl Un Lan uo • 2.23

concatO method of String object dds tw o r more strings and return s a new si ngle st r ng The
output:
syntax of n at() 111 e1hod 1s give n below: str . cnarAt(0 ) i s :T
stri ng .c nea t ( t r 1ng2, s t r in g) , t r ingN) ;
st r . charAt(l ) 1s . h
~llmple: str . cna r At ( 2) i s: 1
str . charAt (3) is : s
, ht ml '
str .c harAt ( 4 ) is:
,hea d' str .charAt ( S) i s :i
, tit le ' s ope < t i t l e
, cr·11 t ' ill! Retrieving a Position of Characters in a String
var t r l • new td ng( "Mee nakshi " ); ~ n d a character or characters in sting we have two methods namely, indexQfO an~
a r <tr : • ne1< St ri ng "Anu rag " ) ; The indexOfO method returns the position of the first occurrence of a specified character in a string.
This method returns -1 if the value to search for never occurs.
va r t r) . new St r ing "Tha l or");
.I( str ing . in dexOf ( searchvalue, [start))
ar str4 , st r l tS tr 3; Here, start is optional specifies at which position to start the search, by default it is 0 .
ar t r·S • s t r 2. oncat ( t r 3); / The search() method searches a string for a specified value, and returns the position of the match.
ar r6 = s t r l . concat ( st r2,s tr 3) ; " The search value can be string or regular expression. This method returns -1 if no match is found.
doc men t . 1<r 1t e ( " t r 4 : " + s t r 4 ) ; .,t string. search{ searchvalue )
documen t . wr ite ( " br >s t r S + st rS ) ; ~ ample:
do ume nt . wr ite ("< Or>str6 " ~ s t r6 ); <html >
<head >
, / s ript ' <title > scope</tit le >
hea >
<I , s cript >
<body> </ body> function init ( )
, / ntm l> {
Output: var st r = "how are you>";
s t r4 M enakshi Tha l or var nl = str . search ( "o" ) ;
st rS AnuragTha l o r doc ument.write(" ' o' found at location " - nl) ;
va r n2 = str . indexOf( "u" ) ;
s t r6 Meena shi An uragTh al or

EIIJ Retrieving a Character from given Position document.write(" <br> ' u · found at location " + n2)
var n3 = str . search( ' are ');
• [A string 1s an array of characteri} As we are ~ware, an array has one or more el~me nts. that a.re document .write(" <br >' are· founa at location " T n3)
identified by an index. Each character m a smng 1s an array element that can be 1dent1 f1ed by Its var n4 = str.indexOf ( ' you ' );
documen t . write ( " <br >' you ' found at location + n4 )
mde
• (You can copy a d 1ara cter from a stri ng to a nother string by usmg the char At() method of the String
</ script >
objecQThe cha rAt O method requ ires one argu ment . which is the index of the cha racter that you
</ head >
wa nt to cop
<body onload="init()" ></ body >
yiiample: For charatQ. </ html >
<ht ml Output:
<head > ' o ' found at location 1
<titl e >Ja vaS crip t Str ing charAt () Method </ tit l e > · u · found at location 10
</ head > ' are · found at location 4
<boay > 'you ' found at location 8
<script type="text / java s cript ">
va r st r = new Stri ng( "Tni s is st r ing" ); Dividing Text
doc ument.write ln ("st r . cha r At (0) i s : " + str . charAt (0) ) ; Consider you have a string of concatenated data elements where each data element is separated by
do c ument.wri t eln("<br /> str . cha rAt ( l ) is : " + str .charAt {l )) ; comma and you have to provide each data element of concatenated string into its own string.
do cum ent. wri teln ( " <Or /> str.c ha r At (2) i s : " + s tr.cha r At ( 2)) ; The above mentioned task can be completed with help of split method of String object.
documen t . writeln (" <br / >str.c harAt (3) is : " + str.charAt (3 )) ; The split() method creates a new array and then copies portions(substring) of the string into its array
document . wrlte ln (" <br / >str . charAt (4 ) is : "+ s tr.charAt (4 )); elements. You must tell the split() method what string (separator/delimiter) is used to separate
document. wrlteln (" <br /> s tr .c harAt (S) i s : "+ str . charAt (S )); substrings in the string.
/ script ,
/ The concat(l method of string object combine two string objects whereas split method of string ob ject
</ body >
divide a string into substrings using the specified separator and return them as an array.
</ ht ml>
Client Side Scnptlng Language 2.24 Arra y, Function and S Arr.y, Function and Strini
~ S
id• seriptlng Language 2.25

~ The syntax cf split method is as follows : ~


first argument of substrQ is mandatory which specifies the position where to start the extraction.
stringObj. split ( [ separat or[, li mit J J) second argument_of substr is Optional which specifies the number of characters t~ extract. The
Here. sepa rator is optional argument which is a string or a regular expression object that iden .fi1 second argument is not for the end index, it's for the amount of characters. If om itted. it extracts the
character or characters to use in separating the string. If omitted, a single-element array coma 1ti 1. es
rest of the string.
the entire string is returned. n ng
The first argument to substr can be a negative integer. in which case the start of the returned string
Limit is also option argument wh ich represent a value used to limit the number of elements retu / is counted from the end of the string.
;n the array. med _--:
.!J(al11Ple:
, j'xample: -- 'F <html >
<ntml > <head >
<heao > <title > scope</title>
<t itle > scope </ ti tl e > <script >
<scr ip t > function inn ()
f nction init () {
var str = "J avaScr i pt is a Sc ri pting Language. "
var st r = "How are you? "; document.write( "< br> substr : " + str.substr ( 16 , 9 );
document.write ("< br >substr : .... st r. substr ( 16 ) );
var resl = str . spli t ();
document . write ("<br>sub str : " + str.substring ( 16,25 ) );
document . wr ite ("< br>Res ultl = "+ resl );
document.write("<br >substr : "+ str.substring ( 16 ) );
ar es2 = str . split (" o") ;
document.write ("< br> substr : "+ str.subs tri ng( 25,16 ) );
docume nt.wri te (" Result2 =" + re s2 );
var res3 = str . s pl it ( " ",2 ); </ script >
docume nt . write (" <br> Res ult3 =" + res3 ); </ head >
<boay onlo ad= " in it ()">
</ script > </ body >
</ hea d> </ htm l >
<body on load= "init ()"> </ body > Output:
</ html > subs tr : Scripting
Output: substr : Scriptin g Language.
Res ultl = H,o,w, ,a, r, e , ,y,o,u,? subs tr : Scripting
subs tr : Sc r ipti ng Language .
Result2 = H,w ar e y,u>
substr : Scripting
Result3 = How,are

l!D Copying a Substring Em Converting String to Number


Consider followi ng two variables are given to you and you have to perform addi tion of these
As we know, splitQ method is useful wh · . numbers.
individual data elements but it isn't f en ~ou are sepa:atmg a stnng containing data elements into
I d o muc use to you if you need to copy one substring var num l = 42 ;
nor er to extract a small portion fro . . . var num 2 = ' 82 · ;
explained below: ma strmg, JavaScnpt provides two methods of String object as
• If we will apply num1+num2 then we will get a concatenated string rather than 124. To get the
,.;!. substring: e~ected result first we need to convert the string datatype into number. To do so Javascript provides
/ The substring Q method extracts the characters from a s . . . different methods for conversion of one data type to another.
returns the new sub stri ng The synt f b . . tnng, between two specified mdices, and Jo parselntQ:
· ax O su stnngQ 1s as follows :
:,;_ st r ing.substring ( sta r tindex, [endindex]) ; The parselntQ method converts a string into an integer (a whole number).

This. method extracts
· th e ch aracters located in a strin f .. . .. It accepts two arguments. The first argument is the string to convert.
endindex argument of substring is Optional If 'tt d . g rom startmdex to endindex-1. The The seco~d argument is called the radix. This is the base number used in mathematical systems. f or
. / If "startind • . . om1 e . It extracts the rest of the string our use, 1t should always be 10.
ex LS greater than "endindex". this method ·11 .
_/ str.substring(l , 4) == str.substring(4, 1). WJ swap the two arguments, meaning ar size= '42inch';
....,Z.: tubstrQ: var integer = par se!nt ( s ize, 10); // retun 42

J The substrQ method extracts the char acters from a strin


length, and returns he new substring Th
.
g, starting from startindex and of specified
/ . parseFloatQ :
The parseFloatQ method converts a string into a point number (a number with deci mal poin
. ' · e syntax of substrQis as follows·
4 st r1ng . substr ( startindex, [lengt h]) . va r si ze= ' 3. 14inch';
va r poi nt Num = parseFloat ( size ); / / r eturns 3 .14
,,._J. ·- -

Arrn Fun tt n 0110 Stt1n


idO cri p tl ll \J Louguo go
11on t

< / e r· I p '
8num er If -in n 11- 1st of nl numb er (w hole or With
... / 11 er.1d ..
me then,•ise it will re turn ~ N . nn ~ r 11ym f r .. Not
u er
--- ~ , body o n l o.1,1• "in l t () " >
I

~
,/ IJod y >
~ -\ :..:3 ·,.

---
</ t1Cr11 l '
ut-e - 1 : : . :, ),
- .?Ra re tu 1"1h output ,
r et u,..n s Na _ _ __ Adc1it I o n• _
2_s_o__________
---------------
iJII changing the Case of the String
• J. vas n pt provides two me thods to chang t he cases of a s tring a explai n ed b low :
' - e3:.:::'
,."':"l : l?' toLowerCasc () :
, s .: r i:-::' The to L w er Rse () me th od co nve rts all of a stnng s cha ra cters to low erca It does n o t t ake ny
l"J • ct1 0 1 it ' rgum e nt
Th t Low er a e() m eth od conv n s a U strmg charact rs with d cim 1 Un de v Ju betw en 65
.. A .. ) and O CZ"' ) t o thei r lowercase equivale nt (by add ing 32 t o their decima l Un Ju e. fro m "a "
;: . 8 - .. ....¥ at 7 . t o .. z.. at 122).
u t• , l • pa rs ei rn num2 , 10 ) ; to Upperca se() :
-ent . .. -i t e · ~ i ti n= "• resu lt ) ;
_/ Jav s crip t s to UpperCaseQ method conv rts a ll of a stdng·s characte rs to upp re s . It doe. n ot t k
ny argumen t. The to UpperC seO m eth od does th e opposite of the t o Low r as O m "th d .
It onve n s all stnng chara ters with d c1ma I Uni code valu e betwee n 97 ("a") a nd 122 (""z" ) t o th i r
ad =" 1111t ( "> -¥ uppercase equivale nt (by subst ract ing 32 fr om thei r decima l Un i ode va lu e, fr om .. A.. at 65. t o .. Z ..
90 .
p ample:
Output : <html >
<1.coi - i =1 -4 <body >
EID Converting Numbers to Strings
In JavaScript, there are two main ways in wh ich any value can be converted t o a string.
<sc r ipt >
var t t ="H e ll o Ja vaScript World ! .. ;
documen t . wr it e ("< p >" + txt . toUpperCase() + " </ p >" );
. toStringO Method: docu me nt . writ e( " <p >" + t xt . t o l owerCase() + "</ p>");
The toString O method can be used t o convert both integers and decimal valu es (floats) to
doc umen t . write ( " <p> " + t xt + " </ p >") ;
_,,corresponding string.
</ sc ri pt >
/ The syntax oftoStringO is as follows : </ body >
ber . to St ri g ()
/ h ml >
~mple: Output :
var nu , 100
var str num. t oSt ring () HE LO JAVASCRIPT WORLD!
ar num 100 hel lo Javascr ipt worl d!
var st r + num He l lo JavaScr ipt wol'ld l
Concatenation Operator(+): e.l~~~~~~~~===----.,,.~-.p,,,=-1
w.a_. Finding a Unicode of a Character
r - ~- - ~ -
You can use th e concatenation operator (+) to combine a string and a number. The concatenation
operator automatically calls the toString Q method on numeric values to convert them t o a string. Uni code is a s tandard that assigns a number to every character. numbe r. a nd symbol th at c n b
For example. / displayed o n a co m puter screen, including ch a racters a nd symbols that are u sed in 11 languages .
ar num 100 V'" A computer can only understands nu mbers and n ot chara ct ers. You m ight war th t when you
var st r :. + num
enter a character. such as the letter w. the character is autom atically convened to number called
ample: Unicode nu mb er that your computer can understa nd.
<ht ml>
<head >
<title > s c ope </ title >
<script > n
y
You ca n determme th e Un icode number or the character that is a ssociated with a Unicode number
u sing the charCodeAt Q m ethod and from CharCodeQ method.
__;!"81 charCodeAtQ Method
functi o n init () / cha rCodeAt() is a string method that is used to retrieve a Unicode v lue for ch r cter ta s~ iflc
{
var num l = 2 3;
var num2 = 80 ;
X· posi tion .
The parameter / parameters to the charCodeAtQ method is index position for whi ch you want t kn ,
the Unicode value.
a r r esult= num l + num2 . toSt r ing () ;
docu men t . write( " Result= "+ result ); -"* Syntax: stri ng . ch a rCodeAt ( [position] );
~ If this positio n parameter is not provided, the charCode At Q method will u se Oas the default.
\fii(•fj fromCharCode() Method
. a strmg
. method that IS
· used to create as t rm
· g from a sequence of Um code values .
.
fromCharCodeO IS
.../ · one or more unicode values .
The parameter/parameters to the fromCharCode () met hod IS
~ ~§~y~n~t~a~x::~St~r~i~n~g~.f~r~o~m~C~ha~r~C~o~d~e~
(v~a~l~u~e~
l ,'.__'v~a~
:' lu~e~2~,_:__·~
" ~ v:a~lu=e~ n~)~;~~~~~~~~~~~~---
~ ample:
<html >
<head >
<title > Scope </ title >
</ head >
<body >
<script >
var txt = "Hello JavaScript World I";
document ·. write(" <p>" + txt.charCodeAt() + "</p >"); / / Unicode of H
document.write(" <p>" + t xt.charCodeAt(S) + "</ p>"); // Unicode of space
var res= String.fromCharCode(77 , 69, 69, 78, 65) ;
document.write( res );
</ script >
</ body >
</ html >
Output:
72
32
ME ENA

1. What is an array?
2. How to create array in JavaScript? Explain with example.
3. Define the term function. What is the use of function in JavaScript?
4. How to initialize an array? Explain with example.
5. What is string? How to declare it? Explain with example.
6. Describe the term looping an array with an example.
7. How to add and sort elements in array? Explain with example.
8. What is meant by function argument? How to add arguments in functions? Describe with
example.
9. How to join two strings?
10. Define the terms:
(i) Function
(ii) Array
(iii) String.
11. With the help of example explain retrieving a character from given position in JavaScript string.
12. How to combining an array elements into a string? ·
13. Describe the term objects as associative arrays in detail.
14. Write a program to changing the ca~e of string.
15. Which methods are used for finding a Unicode of a character?
16. Write a program to calling a function with or without an argument.
•••
3 ...

For Ev ng
[ Chapter Outcomes ...
00 Write Ja vaScript to de sign a form t o accept in put va lues for t he give n p ro bl e m .
00 Use Ja vaScript to imple m e nt fo rm event s to solve t he give n p roble m .
~ Develop JavaScript to d y nam ica lly ass ign speci fied a ttribute valu e to the g iven fo rm cont ro l.
00 Use the g iven intrinsic fun ction w ith spec ified pa rameter s.

!Learning Objectives...
00 To underst a nd Basic Con cepts o f For ms in JavaScript
00 To s tud y variou s Fo rm Co ntrol Ele ment s w ith Exa mple
00 To le a rn Eve nts a nd Eve n t Ha nd li ng in JavaScri pt

INTRODUCTION
• Q orms are one of the most common web page elements used with JavaScrip~ avaScript is commonly
used with forms for following two reasons:
1. To add functionality that makes forms easier for users to fill out, and
2. To validate or process the data that a user enters before that data is submitted to a server side
script.
• JavaScript Form object represents an HTML form . HTML forms are a very powerful tool for
interacting with users.
• Forms provide you with a way of grouping together HTML interaction elements with a common pur-
pose. For ·e xample, a form may contain elements that enable the input of a user's data for registering
on a web site. Another form may contain elements that enable the user to ask for a bike insurance
quote.
• HTML forms serve the purpose of collecting information provided by the visitors, which is later sent
back to the server.
• One of the primary ways in which JavaScr.i pt is executed on a web page is through events.~ event is
a specific circumstance (such as an action performed by a user or an action performed by the
browser) that is monitored by JavaScript and that your script can respond to in some way]
• You can use JavaScript events to allow users to interact with your web pages. The most common
events are actions that users perform. For example, when a user clicks a form button, a click event is
generated.
• JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipul'ates a page.
• {Jvhen the page loads, it is called an eveni] When the user clicks a button, that click too is an event.
Other examples include events like pressing any key, closing a window, resizing a window, etc.
[3.1]
Form and Even~
3.2 For ni and E'tlenl H~
~!.ES~
cr~lp~tl~n~g1La
~n~g~u~a~ge~~ ~ ~ ~ ~ ~~ ~ ~...231.3~ ~ ~ ~ ~~ ~~ ~ ~ ~ ~--'-=-~ ~ -
Client Stde Scnptmg Langu age
/ The attributes of the form are:
1 _ id : The un ique identifi er. . . . . f nctions o f DOM. because
2 _ name: The name. its role 1s equ ivalent to that of identifier but for the u .
the method get ElementBy!d is based on the 1d. . ha sub m it butto~ote
3 action:\flie name of a script to be loaded when the form 1s sub mitted . Wlt . in p a r amet er t o
· that t he names and values of the graph ic components are given automatica 11 Y
the script . - tion of th e a ctio~t
4 . onSubmit! Event fired up when the form is subm itted and before the execu
can allow t o· determin e if he action must be executed or n ot .
~mple: .. .. ..
<form name= my f orm ia="myform" act1 on ="page . htm l " onSubmi t ="tesi: () >
. . . objects .. .
</ form > . . n return fa lse, the form
The onSubmit attribute associates a test fun ction on the fo r m . If t ne fun ctio
data are not sent, we stay on the same page. check box. rad io b utton ,
A form element that can be represen ted as a text box. password text box, . b t t ) file select ion
subm it button , reset button, hidden input field , image (wh ich acts as a submit u on ·
box or general button.
Followin g table lists HTML form ele ments:
sr. No. HTML Element I Tvne Pronertv Event Handler I Descrlntion and Events \

J -.......7 I " button "


<in p ut type-"button "> or oncllck I Apushbu tton.
<Dutton t yp e-"button " > I . 1.
2. <i nput t ype="checkoox" > ' "checkbo x" onchange A toggle butt on without ra dio \
\ button behavior.
3. <i nput type ="file " > I "file" onchange · An input h eld for en enng the
I name of a file t o u pload t o the
1
\ web seiver, value property is \
read-onlv.
<i npu,: ,: ype="hi daen "> "hiaoen " none I Data submitted with the form I
I

Ent er your nam e :


5. <opti o n >
i
I
none
none
I but not visible to the user.
\ A single item within a Selec I

I
object , event handlers are an \
the Select ob ject, not on
<input type ="text " name ="inputbox" va l ue ="" />< br> I
I individual Option obiects .
<input type="button " name= " butt on " value="Clic k" onclick ="show " /> 6. <input type= "passwora " > "passw ord" onchange I An inpu t field for password
</ fo rm > '\ entry where typed characters \
</ body > I are not visible.
</ html > 7. <input i:ype="rat10 "> I "raa io " onchange A toggle button with radio
button b ehaviour wher e only
Here.
1. form name= "my form " defines a nd names the form . Elsew here in the JavaSc r ipt you can I \ one selected at a time . ,
reference this fo rm by the name myform.
2. a ction ="" defines h ow you want the browser to handle the form when it is submitted to a CG!
.y.
<i nput t ype= "r eset " > or
<button t vpe= "r e set" >
<select>
"reset "

"se l ect- on e"


oncllck

oncha nge
I A push button that resets a ,
form .
\ A list or drop-down m enu from \
program running on the server. As this example is not designed t o submit anything, the URL for
th e CG! program is om itted . \ which one item may be selected ;
3. method="GE defines the method data is passed to the server when the form is submitted. , (also see <ootion>\.
<select multiple > "se l ect - on change \ A list from which multiple
4 . input type= "text" defines the t ext box object. This is standard HTML markup .
multipl e" items may be selected (also see
5. inpu t type="button " defines the button object. This is standard HTML markup except for the
onClick h andler. I <ootion >.
<input ty pe="submit"> or "submit" on e lic k I A p ush button tha t su buuts a ,
6. onClick="show" is an eve nt han dler it handles an event, in this case clicking the button . When the <button t voe =" submi t "> form .
button is clicked, JavaScript execut es the code written inside show function . <input t ype="t ext " > "text " on cha nge
1111 Form Object and Elements \ A single-line text enuy field..

I
I the default <inpu > element it
~ Form object is represented by HTML <form> element. The syntax of <form>is : , type attribute i omitted or I
\ unrecognized . I
<f orm name= "id =" a ction ="onSubmit="> . . . </ form > <t exta rea> I "te xt area" I
on change . A multilin e text en try field.
"} . ..
Fo rm and Event 11~ ~ i
3 4
Cllont ldo Sorlp tlr,g Leng_uogg ~ .!!J>lln La n . 9 ~ - - - - -- - 3.5
> a with following par mete rs
Tu declare form e lement u e in pu t g be process d . ..el Properties and Methods of Form
name· c n used so th a t t h e va Iue
of he e lement ca n d
n be rext (d efa ult ). passwor . c heckbox ~ b. l ents property
- 1· · O f inpu 1 v lues ca , ,/ The Form o Ject re presents a <fo r m > eleme nt 111 an HTML docume n t. The e em . () d
2 _ typ e · Can be u sed to spec1 Y the type v 1s a n HTM LCo llection t hat provides co nvenient access t o a ll ele ments of the form . The submit an
ra di~. submi1 . res t . h idden . image f1l or butt on reset Q meth ods allow a for m to be submmed or reset under progr am control
3 . id : Iden 1ficario n name o e le m e nt It is required when type is set t o c h ec kb ox or radio. / Ea ch form 111 a document 1s rep resented as an element o f t he docu ment .forms[] arra y . The
4 . valu : Ca n be u sed o s pe c1fy t he i111t1al va lue . elements of a form (buttons . in p ut fi elds. che ckboxes, an d so on) are colle c t ed in the array like obJect
It should not be u sed when rype is s t to file. di o t o set t h e im t ial st at e of a ch eck box f orm .elements.
t to chec kbox or ra ..
s. checked : Can be used when type 15 se h for m a t checked =" ch ecked · properties o fform : o~\'c-\'n'"'
l d It nus t be used t e ·
or rad io button to b e se ecte I 111
fy the maximum num
ber of chara cters a llowed in a text box. Sr. No. Properties I Description I
d
6 . m axlength: C n be u se to peci f h locatio n ofan 1maoe fil e .
et O I mage to spec1 Y t e O ·-Jc" act i on f Read / write string that reflects the a ction a ttribute o f he form .
I
s:rc: an be used w h en type is s . f the al te rna tive text of t he image. Which
e l ements( J An array contai n ing all of the elements o f the form . Use it t o loop t h roug h
8 . a lt: Ca n be u s ed when type is se t o image to spec1 y /. form ea sily.
should be a sho rt de sc ripti on f then you can assigning value s to th ese forrn I
Once. you h ave crea ed form control objects on orm 3. e ncoding Read/wnte string that specifies h ow the for m d ata is encoded . .
co ntrol objec ts
A particular element on htm l fo rm s h ould b e proper I Yu
sed as per the DOM hierarchy . 4. length The number of elements in the form. .
For examp le a textbox on a web docume nt will be represe nted by . 5. me t hod I Read / write string th at specifies how the method the form is submitted . I
I
f eni: 10 prope r t y / methoa
doc ~me nt. for ms . orm_1 0 . e 1 em - . et ElementByld() and getEleme ntsByTagName()] th rough
6. name l The name of the form . I

Q.avasc npt also prov1des some methods ~ · .


1
ithout using above n ot ation']Follow ing example 7. ta r ge t ! The n a m e oftlfe t a rget fra me or wi n d ow form is to b e subm itt ed t o .
which you can also u se a html element irec Y ~ wi ll oet assigned to form control objects. Methods of For m :
shows that w he n u ser c!Jck on b tton the n some va ue o
sr. No. 1 Methods Description I
,~xa mple : 'T
<h ml> I ~r~
L_~l~-~ ~~ e ~s ~e .t:...-_(~)~- -~R~e=s~et~s~t~h~e~f~o=r~m~. ~ - -- ~~ - - ~ - - ~ - - ~- ~- ~ ~ - - - ~ --,
<heaa > 2. I
suomi t ( ) T Submits a fo r m . ,
cit le >Ass 1gn Va l ue s</ t itle >
Methods of Events :
, s cr io t> ~r'i,
f_unc~ 1on assign () '<:'""",... e~ y Sr.No. Events Description
0
t ._, ,£ I/- 1. onRese t Code is executed when the fo rm is reset (by clicking on "reset" b utton).
docum ent f orms. oook.c 1tie .value: "Scr1pt 1ng Tech nology ";
2. onSu bmi t Code is executed when form is s u bm it ted .
oocume nt: .forms. book. aut hor . va l e : "MeenaKs h1 Thal or " ;;
Forms and t he eleme nts t h ey contain ca n be se lect ed from a d ocument using sta n dard
methods li ke getE lementBy ld Q and getElements ByTagName() :
(I SCr1pt >
< /h ead >
J getElementByld Method :
It retu rns a re fe rence to the element by its ID.
<bo c., >
<f o ... m 10 = · booK" ac t i on : "" >
Following is t he syntax o f get Elem entBy ld () :
< l"' O·... t 1:; =" t1 tle' >< br >
e l emen : oocumen t.getElementByid (i d ) ;
c .. Pu t 1 = a1,, "lor· >
Where .
- i np u t tyoe: u tton " id : "ctn " va l ue: "Ass gn Va ue s" onc ll ck : "ass i gn()" > element 1s a reference t o an Element obje ct. or null if an element w ' t h the specified ID is not in
the document.
" COO~ >
id is a case -se nsit ive string rep resenti ng the u n ique ID o f the element being s ought.
rtn"l > J · getElementsByTagName Method:
Ou tpu t : It returns a n HTMLCollection of ele ments wit h the given ag name. Th e complete d ocumen t ·s
searched . includin g the roo node.
- c
The r e urned HTMLCoilection is rve , meaning hat it updates i elf automatically t o stay in sync wi h
th e DOM tre e w ith out ha ving t o all d ocum ent.ge tElementsByTagNameQ a g ain .
va r ele ments : documen t . ge El ementsByT agName ( name ) ;
Where .
e le me nts is a li ve HTM LCoUection of fou n d ele m en sin t he order they app ar in the tree.
nam e ·s a s t r in g representing h e na me of the elemen s. frhe special string ••• represen a ;
elements.) ~
Form and Event ~
3.6 Form no Event t-,ar,d '~
~ Ide Scri p ti ng Language 3 .7
Client Sid• Scripting Language

ampl e 1: Addressing component directly. output:


<html>
<head >
<title >Assign Va l ues </ tit l e >
<scr ipt>
f unction assign ( ) I Apple
~ B~
1 e
"S cripti ng Te chno log y"';
1 ")
J Grope>
document. getEl eme ntByi d ("t i t e . va u = = "Meenakshi Thal or" ;
aocumen t . get El em ent Byio (" author") . value • . lmso
P"""l'Pk
• Gu,a,a
</ s cript >
</ head > T Ko Lut Itam 6
<body > ~ciic item One. Ban.1:J."1
dorm id ="book" ac t ion= pC'ci6c Iton T wo Pinca-;,plc
<inp ut i d=" t itle" >< br >
<inp ut i d="a utho r " >
<inp ut type="but t on" i d="btn " val ue ="Assign Val ue s " oncl i ck="assig n () " >
1!11 <input> Element of Form
/ The <input> t ag defines the start of an input field where the user can enter his dat a . l n X HTML. th e
</ fo r m> input tag has to be closed. It is done so by placing a backslash (/ ) at the completion of the tag .
</ body > <inp ut t ype=" " name;: " " va l ue " " / >
</ html >
1. Attributes of <input> Tag:
Output:
/ type: Type indicates the type of input element that has to be giv en in the box. The default valu e
~ AwgnV•luu is "text." Following table disnlavs the various attributes of tvne .
~ ~ C ~ IOCdt ost.3Pb0 1 dt>n-'"' , 1........ ,.., ~ _ Sr. Attributes Use
Meaning
;:· Apps --j,. ~~ -Us~ ·.i~1 1n - 0 imp
No.
y. bu t ton A button is an input type t hat will n ot <i nput t y pe ="bu tto n" v al ue ="Su bmit ">
S<nt<mg Te<hn _ O!IY w ork without an extra code being.
tAHfl i ks -Th.iUOf
v checkbox This value creates a checkbox which Financ e: <i nput type =c hec kbo x/ >
can either be on or off.
I
i

ample 2: Address in g comp onent d ir ectly.


v hi dd en This indicates that the field is h idden This is h idd en : <i np ut type =hi Oden / >
a nd the user does not communicate \
<h tm l > I I with it. Hidden is commonly used by II
programmers who do not want users I
<body >
<p id =" pane l ">< / p >
to see t he value. The value used in
h idden is still submitted with other
I
II
'
<ol> information when the submit button
<li>App l e is clicked. It usually passes the page I
<li i d=" iteml " >Ba nana
<l i >Grapes </ ol >
<u l > v image
name and page number that the user
ison.
Image creates an image that is also <i nput type=image
I
<li>Mango a "submit" button. When the user src =" . . graphic s /my image . jpg" / > I
<l i >Pin ea pple clicks on the image , the form is
<l i >Gua va submitted. Image also requires
</ ul> the "src·· attribute like the image tag . \
<d i id= "panel" ></ Oi11> l...fi- pa ssword Password indicates that the fi eld is Passwor d : <input t ype =pa s s ~o rd / >
<script> for typing a password. Password \
va r ite 1 = do cume nt . getElement Byid ( "iteml " ) ; works just like the text type field, the
only d ifference being that whatever
var elems = documen t . getEleme nts ByTag ame ( " li " )
var ite 2 = e le ms [ 4 ] ;
is typed is not displayed on the \
screen. Instead of showing what is
do c ument . wr 1 e l n( "Total No. List I tems : " T e l ems. l ength) ; typed, the brow ser displays a series of I
document . 1ri t e("<br> Spec if i c I tem On e : " + iteml.in nerTe xt ) I
asterisks ("), bullets (.), or somethi ng
document.write ("< br >Specific Item Two: " + item 2 . inne r Te xt ) !
else to show that the user is typing a
</ script> secr et content. .
</ body> coatd. .
< / html>
--
CII n1 Sid• Scrlptlna L_aa,nnaa,u,aa,aaee _ _ _ _ ___:J!;!,8~ ------------F~or_m~ on~ Evont Handlin ~ pll~ Ln nouo_oo _
e .v

I/ r aoi o Ra d io IS used to create a series o f


choices o f which only one can be
selected. Select ing a r adio butto n
option automa tically deselects a ll
other options. Several HTML rad io
<input t ype =radio na me =" na me "
va lu e ="a" I> Am i t <br / >
<i nput type =ra dio na me =" name"
val ue=" b" /> Bh anu <br / >
<i npu t type=ra cJ io name="na me "
/
11111
'
Textarea
A Tex 1Area obi l represe nts n HTM L ,. t xt
fi Jd . o ft en within an HTM L form
ra ., I ·m •nt 1tw1 n· e , mol ,ll n,. 1,-x Ir• u t

Th e 1niti I co ntent o f the text a r a Is s p cl fled a · pl In text be twc,.n h ,. ,,. t . r,-,1., nu · 111·"' 1 r .. ,., •
tags . You can q u ry a nd et th dlsp l yed tex with he vtt lur pr o pert y
bu t tons a r e created by usi ng t he same v al ue="c " I> Che tan <Dr />
. / TextArea is form co ntrol element like fn p t and SP lec . Li ke th ae vbJ"" C-t ' .. I\ <l,.f1n <I!, tm·m.

7. reset
name but d ifferent values .
Thi s va lue resets t he form so tha t th e <i nput type =reset/ > - . / n ame. ry p e,
f orm Co ntro l.
nd value prop rt1 es , nd t h 0111 .. r p, o p r1 ,., and 111 ,: t li d rl ocu nw nt,.d 1"

fo r m is in the way It was before


/ Th e <tex ta r ea > ta g 1nd1ca tes a fo rm fi elct w here th e ,w •r can e nter a 1· rg •· .irn o un t <J f ~ "! A 11
anything was typed in.
u n1Im1ted numb er of char c ters can b wrltten tn the iex t -ar _a Th e d foulr 11 t n f 1·~xt · r•· ·• 1 • I ix .. tl
submit Submit creates the submit butto n <i npu t ty pe:submi t value:"se nd 1 " I> pitch . Thi s tag 1s a lso xa ly similar in n c usag , with HTM L
JV which submits the form t o the se rver. f ollowing tab le s h ows ~ ~ tes of "textarea/ taB
There can be two s u bmit button s on a
form . To d o this , the submit button s~ Attrlbuh~ M~~ng 1 u,e

..,y.
I text
h as to be g iven t he same nam e bu t
different va lues
Text creates the text entry fie ld w h ich Ent er your name : <input type:text / >
No.

is the m ost popu lar type o f data entry


fi eld . Text is the d e fault input type. If col s and cols in di ca te how m a n y c h aracters " a r· ,, nam<· • " «:,rnmr·n •, " tr:, l •. ~ 41'?
the t ext field is needed , t here is n o rov,s wide t h e t ext a r a sh o u ld be. Row s row. • &> , 1 c-x ·._ ,,,,,
n eed to specify the type, as the indica te how many rows s hou ld b
default type of t he <i nput > tag is p resent in t he exta rea Jt does n ot se t \
I "text ." any hmJt to how mu c h text can b e
/ name: Nam e assigns a n ame t o t h e input fi eld . It is required in most circumstances. The name o f the
inpu t fi eld is used to se n d th e in fo rmation to t he server.
First Name : <i npu t t ype: "te xt" name:"firstname" />
typed in. 1t Jus t sets h ow m uc h are lo
visib le. I
wra p descr ibes how t he t ext -a rea , ~ d r ea niJrne • "cr,mmerit~" , , p •~<1 f ,
J

value: Valu e sets t he va lue fo r t h e inp ut fi e ld. It sets the default va lue for t ext and password fields, wraps a t he end o lines . , 1 .. , ·a,
sets t he button text in su bm it a nd reset buttons . a nd sets the values of choices in radio but tons.

vll!IIText
<inp ut t pe:submit val e : "s end t his "/ >
Soft : It wraps lo ng li n es rn the I
tex t area for easy ed it ing . It does
:1o t se nd t h e carr ia ge retu rn t o
t he s rver
I
I
Inpu t "t ext" is a n object to e nte r a single line of text whose content will be pa n of form data . In h tml Ha rd : It looks s im Ja r t o so ft . but
a text is cre a t ed by followi ng cod e: 1t s nds the ca rria ge re tu rn s t o
<inp ut t pe ="t ex t " ame ="textna me " id= " textio " value:"" / > the serve r .
~ample: -O ff: Off does not w r ap at all . It I
<ht ml > jus di s plays and se n ds the teY.t I
<head > cc----L xac ly a s typed ln . I
~
==='-"=-=c...c
ample:
--==--= - -- ----·--· - - - - --
<tit i e >Assign Va lues </ title,
</ hea o > <h ml ,
<oody> <he ad ,
E -er al e of A <i 'l put type: "t: e,c c " id= "txtl " ><br> ' titl e, Assign Val es</ tle,
Ent er alue of B< · put: type= " ext " i d= " txt2 " ><or > '/heao,
sum= <i np t t ype ="text " id= "t xt 3" ><or > <body ,
</ body> 'form me hoo= " pos " a c io n•"" ,
</ 1'1 l> Me ss age : <br /,
Outpu t : <te / are a name ="mess ge" cols • " 40" o,,,5 a" :, " ,ies
<br ; ,,b r />
Emer ·.·ah.J.e of A 'inp yp e="submi" value •"Se no " / ,
Ema \'.tlue of B </ form >
sum= <lboay,
'/h ml>
,-
~ d• Scrip ting L1.1nguage
3 , 11

f,cS.ID p le:
, 1tr>l'
-' ~ d )
Ente- alu~ of A <1nout type• "text" 1d• "t xt. l " >< Or
Ente r value o - B<in put t pe ="t e xt " id• "txtl " <Or>
sun• ,inout t pe=" t ex t " 1o• "t xt3 " >< Or >
,inp ut t ype• "outto n· O'lc hck ="c ompu te ()" al ue ="Ado1t1 on" >
... script >
func ti on compute ()
{
E!!IIButton .. . . var a• doc ument get ElementB yi d( "t xtl " . alc, e
:__;. :"".~a:-:::: ...... :s~...a :e : :i:--- : .,.::ig
var b• document . get Element By! a( "t xt2 ") . a l ue
;=-, - ~c:- x =' <'.? = " a: : : ~- =··, va r C• pa r s ei nt ( a }.,- pa r seint ( b )
, :- : . . : : 1:"e = "" : :::: .:- - , - ~is l; "> <1 fo r > document . ge tE l ementByid ( "t xt3 ") . a l ue =c

nen t ,
wh.Jc..'1 sta.ns the loading of th e file assigned to the

3. a fe
· fl ed as follows :
c:,c • "clic ( nis ) ; " 1 >
like text or ima ge9J3u t , thi s 1s not the case with the

ag :

-
En,r~,~ - 3 5,5

I Sr. Us e
rum= SO
No .
It sets the name o f the b n on tag It <button name•"new" > ew • </ bu non ,

J . col s
works lik e it works mother tags
Th e bunon t ag creates one of the <butto n t ype •b utton , Hello 1 </ bu tt on > V
Fi I ii Checkbox
Radi o a nd checkboxes are an integral part of forms that allow a user to make a selec t i n with a
ro ... s I three butt n s give n below: <button type•submit > Se na It ! s imple click of the mouse.
Button (a s default) crea tes a J </ button > • ( You can prompt users for specific input by using a list of checkboxe~one, one or more checkboxes
normal button like a bunon is I <button t ype•reset> Reset Thi s ! may be checked by the user according to the information they wish to sen d with the fo rm .
created wit h the input tag . I </ bun on> V A checkbox is created by using the input element with the type= "checkbax" attr ibu te-value pair.
Submit creates a submi t button , / A checkbox in a form has only two states (checked or un-checked) and is independent o f t he sta t e o f
like a su bm it b utton created with other check boxes in the form . Checkboxes can be grouped together under a common name.
the in p u t ag. .,,,,Example:
Reset creates a reset button like a <h;:ml >
reset button created with the <head >
input tag . <title >Assign Values< / title >
Event Handling with Button: </ head >
<body >
/ The onclick event is the most frequently used event type which occurs when a user clicks mouse left <form method•"post" action•"#URL#" >
button. You can put your validation. warning etc against this event type.
Select your favourite fruit <br>
J The "on Click" is a event handler, which executes a piece of JavaScript when an element is clicked on. <input t ype• " checkbox" name• "Fruits " i d• " a " / > Apple
/ Remember that any event handlers are added inside html ta 't · ·d · · <input type• " checkbox" name•"Fr ui ts" id • " b" /> Ba na na
. . . gs, no ms1 e <scnpt> <l s cnpt>.
Fhollowit ngtexadm ple uhsmg mput text fields and an input button. The form is designed to demonstrate
ow o ge an set t e text in a text fields The HTML f th · <br /> <br />
attribut e i e oncl.ickQ p . h b · or e mput button includes an event handler
. · · · ressmg t e utton calls a function (compute) that: <input type•"submit" value•"Regi s ter " / >
1 . Retneves the value in the text fields . </ form >
2. Displays the result in another text field . </ body >
</ html,

J'1'1l'WI""----.-~-- - --
·-Jr..,....-
Cl en Side Seriptmg Lan g uage 3.12 Form and Event ~
Client Side Seri
3.13 Form and Ev•n Handl in~
Output:
var 1, s umma ry = .. . .
Sel~t ~·ouz- fa\-ounte frutt
panel = doc '
ument . getEl ement Byia ( "pa nel ");
" Apple .; Banana
form = document . getEl ement Byi a ( " Ea tables .);
f o r ( i = e; i < form . Fr uits . le ngt h ; i++ )

1 J . chec keCI )
if ( fo r m. Fr ui ts [
summar y T= for m. Fr uits [ i J. a lu e • " "

v
am Radiobutton
The radj o bu ton a llows the user to choose one of a p redefined set of opti o ns . You can define groups
p~nel.inn e rHTML = "Your Favorite Fr i t s a re : " T s umma ry;
( ooc ument . getE lement ByICI ( .. rec ") . ch eckec )
l"t
with the name property of t he rad io b uttons . pan el · innerHTML += " <br >Your Fa o rite Colo r is :"
/ Radio buttons wi t h t he same n ame belong to the same g roup . Radio buttons with different names + Clocume nt .getE leme nt By i d (" r eo "). v a l e ;
belon g t o diffe rent gro ups . At most one radio button can be checked in a group. else if ( Clocume nt . getElement ByICl ( "blue " ) . c heckeo )
/ Ra dio buttons work just like checkboxes except they a re typically set u p to be m utually exclusive of pan el.innerHTML " <br> Your Favor ite Color i s : "
o ne an other. i.e. when one is selected, all the others are automatically 'dese lected'. T docume m . get Eleme nt8y ICI ( "o l ue " ) . v a lue ;
else
/ A radio button is c reated b y using the ' nput element with t he type= "radio " attribute-value pa ir . Radio panel. i nnerHTML += " <br> Your Fa vori te Co l o r is :"
b u tton s in a fo rm can be grouped together using the same name attribute , such that, if on e of t hem • Clocument . ge tE lementByld (" gr e e n " ).v a l u ~ ;
is checked. a ll the others are a utomat ically u n -checked.
/xample: Using radio button on form . </ s cript >
</ head >
<html >
<bod y >
<heao >
<f o r m 1d=" Eat abl es" actio n="wel come . html" met hoo =" POST ">
<tit le >Ass i gn Values </ t itle > Fa vor ite Fru its? <br >
</ heaCI > <i nput type="che c koox" name= "Fr uits " value= "Ma ngo" >Ma ngo &nbsp;
<body > <input type= "checKbo x" name= " Fr ui t s" va l ue="Or a nge"' >Ora nge &nbs p;
<f o rm meth od="pos t " actio n="#URL# " > <in put type="checkbox" name= "Fruits " val ue=" Banana " >Ba nana &nbs p ; <or ,
<inp ut type="rad io " name= "genoe r " iO= " raCl i o_femal e" va l e ="fema l e" Favo r ite color ?<br >
<inp ut type="rad io" name= "co l o r s " i d= " red" val ue="Red " >Reo <br >
c hecke d= " chec ked" >fema l e
<i nput t y pe =" radi o " name= "co lo rs " id= "D l ue " val ue =" Blue" >Bl ue <b r >
<i nput ty pe= " raCl io" name =" gende r " 1Cl="r adi o_male " val ue="m al e" > ma l e
<inp ut ty pe ="radio" name= "colors " iCl= "green " value ="Green " >Green <br >
<br / ><br / >
<input id=" Dt n" type= " button " va lue ="Co nfirm Ch oices" onclick =" po ll () ">
<i nput type="s ubmit " val e= "Regis t er " /> </ f orm>
</ form > <p id ="panel" >< / p >
<I body > </ bod y >
</ ht ml > </ ht ml>
Output: Output:
F a,·on te F ru 1ts?
• female male
U 11ango -!' Orange .!!! Banana
Fav onte color '.'
• I Re<t
• B lue
' •Green
Example 2: Usmg radio button and checkbox on form . (.fo-;:,rim,·Cholc;s I
<l"ltml>
Your Fav cnte Fruus are:Orange Banana
<heaa >
Your Fa-..onte Color ,s :Blue
<ti tle >Radi oBu t t on ana Check Box </ ti tl e >
<scr i pt > -Select
function po ll ()
'-"" The Select element represents an HTML <select > tag , which displays a graph .cal list of ch o ices t
User .
3. l 4 Fo rm and Event ~ ~ Scnpung Langu.oge
l.15
• \..:! the En- , ,f ·ple atu-fo te ·5 prese n:. t he ser m ay sele ai:1Y number o f op ·ans from _he s
11
<f orm a c ion= "" e cd= "POS · ,
t'.;;;.: a -0 , e is no-. p~ese nt, t:,e user m a y select only one o nor9and op tio ns have a rad io b , . on ' Se lec i a ="c tyli s t" onch a ge= " i it ()">
te.:- ~vicrr - se!ec'J ng one dese ects wh ich ever was previously sele c ed . <option>Pune </ op ti on,
..._,-- :-o add a · ·: box o r drop dovm box yo:.1 can use se ect element with o p ion tags.
<Op tion s e ec <:d >Mu, ba 1< / op io >
A typical dropdo•,m list 15 instantia ed sing t he following <opt ion> Calc t a </op i on,
<Option> Del i </ opt io n,
e l </ op: 1on >
<o pt ion >Mysore <I option >
e 2</ p - 1 0 >
</ sel e ct >
e 3</ p: ion >
< ' se ect >
</ f orm >
/ With op ·on ag you can use fo owin g para m eters: <P id= "pa nel" ></ p >
S-el ected: Can be used to specify tha he opti on is initially selected. </ body >
Valu e: Can be used t o speofy a va lue for the option . </ html >
~mplel: output:
<ht l >
< ead >
< 1t le >Assign al ues </ title >
</ heaa >
<boa y>
<form methoa =" post " action="#URL# " >
My fa vori te fruit :
<select na me= "fruit">
<option a l ue ="Apple" >Apple </ option > Example 3 :
<option alue="Pea r" selected >Pear </ op t ion> <html >
<option val ue= "Peach " >Peach </ option > <h ead >
</ select >
<tit le >< / title >
<br / >< br / >
<input type= " submit " value= "Send" I> </ he a d >
</ form > <body>
</ body> <h l > Registratio n Page </ hl >
</ html > <form name="registration"
Output: action= "http : // nirali publications.com/ registration. html ">
:\fy fa\·orite fruit : Pear Fi rs t name: <i nput type="text" name= "realname" / > <br />< br />
Last name : <i nput type="text" name="sirname " / > <br />< br />
Send I Password : <i nput type="password" name="pass" I> <br/ >< br/ >
"------' Re-Type Password : <input type= " password" name="repass"/> <br / >< b r/>

Example 2: Gender <in put type="radio" name= " sex " value="M"/ > Male
<ht ml > <i nput type="radio" name="sex" value="F"/> Female <br / >< br />
<he ad >
<title > Select Option </ title > City where you want to tra vel <select name="city " >
<s cript > <optgroup label= "North" >
function ini t () <option value= "001" > Delhi </ option >
{ <option value="002"> Chandigadh </opt i on >
var panel = document . getEl ement Byid (" panel" ); </o ptgroup>
var elem = do cume nt . getElementByid ( "ci tylist" ). options. se le cted In dex; <optgroup label= "South" >
var city = doc ument .getElementBy id (" cit y list" ) .options( elem ] .va lue ; <option val ue=" lll "> Kerela< / option >
panel . innerHTML = "Selected : " + city + " - I ndex : " + e l em ;
<option val ue ="112 "> Kanyakumari </opt i on>
</ script > </optgroup >
</ head > </s e lect ><br />< br />
<body > <l abel for="moreinfo "> Do yo u want more information about cit i es? </ l a be l >
<i np ut type="checkbox" name="moreinfo" id="more i nfo" /><br/><br/>
3.. 5
~ - .
S]dtl~Scn~~~gLL..ansp.a,::::.,x,::~:>ee.._~~~~~~~~~_!_:_:_~~~~~~--~~~~- """'=-- E
E-:. .e, '" , :, ./ ' :::::;; ,e- .... ~ s : • f olloWJr.g tab le g1,es H,
cteY: :p···-ea -.a e= · c ~ · Attribute !
y-' on oaa ; ne body of e documen as Just been y read a.."ld parsec
<I 2 > ,this arrnou e perta ins only to body and frames_ J
a.: ion ont1nloao Th e browser is reaay to load a ev, document in ;,lace cf r..he c-..:.rren:
a e; "co f i ." /> Aoo e I nf o J
one l lCK
I docum en (tlus a ' but e on y pertains o body and frames.et).
< r / >< - />
,7 I A mouse bu n has been dicked and r eased over e tle en t
pr ype ; • r-es e.: • e ="Rese1: " />< br />< br / > ondb clic The mouse has been double-clicked over the" em enL
/ onmouseoown I Th e mouse has been clicked over the element
al e="Sub i.: " />
<i p u1: t pe ; "su o it " Jr. onmouseup I The mouse has been released over the elem ent.
</ f or- . > ....fa
onmou se ove r Th e mouse has jus: moved over the element.
<I

</ h.: ml >


ody > I ,.?:
/ •
.JY.
onmousem-ove
onmou seou'l:
1~~: ::::: ~:;~v: ~:dr:::~
0
l~:~:e :i: : 'e~:rr over the e lem e nt.
10 . onf ocus The e em ent has just received the keyboard focus (tlus attribu e pe ains i
Outp~u~t~=~~~~~~~~~~~~,
, only to certain elements , including a, label input, select, textarea . and i
Re.gi.stration Page
button).
11. onblur The element has just lost the keyboard focu s (attribute pertains o nly to the
same elements as on focus).
12. onkey pr ess I This element has the focus and a key has been pressed and released .
&..-Tr~ P- - . c _-_-.:..__ __ - ---
13. I on keydown I This element has the focu s and a key has been pressed.
~ · !..t.it li F-.;ic I
...,1,( 14. on'<eyup Th is elemen t has the focus and a key h as been released. ·
~,...- - ~~- !
c
15. on sub 11: I
Th is element is ready to be submitted (a pplies only t o form elements) . I
v1{>, on rese t I This element is ready to be r eset (applies only to form elements) . 'or II
- -~-JI I_ - - - - - - - - - - - - __ _.t
17. onse le c t Text in this element has been selected (highlighted) in preparation ,
ed iting (applies only to input and textarea elements) .
Ad.dhifn1aJ bform•do•
18. onch a nge The value of this element has changed (applies only to inp u t , textarea, a nd
select elements .
v--£Vent Handler:
~ When a functi on is ass igned to an event handler. that function is run when that event occurs.
~ ffl FORM EVENTS / A handler that is ass igned from a script used the syntax, · [e leme nt] . [event] ; [ f un n ion]; ·

in JavaScri pt, functions are normally not called directly fro m the top level of a JavaScript program. wher e, [element] is a page element, [event] is the name of the s elected event and [fu nction] is t he
Instead, functions are called in response to various user actions, such as clicking a button or moving name o f the fu nction that occurs when the event takes place.
the m o s e over a certain element. / For example:
Events: document . onc lic = clickHandler ;
This ha n dler will cause the fu nction clickHandlerO to be executed whenever th e user clicks th e
/ One o f the p ri mary ways in which JavaScri pt is executed on a Web pages is throu gh evems0n event
mouse anywhere on the screen.
is a specific ci rcu mstance (such as a n action performed by a u ser, or an action performed by the Note that when a n event handler is assigned, the fun ction n ame does n ot end wit h paren eses.. W e
b rowser) · hat is m onitored by JavaScri pt and th at the script can respond to in some way] a re just p oi n ti ng the event to the name of the function. The clickHand ler fun ction is de fined like
v" Java ' pt -enab led Web pages are typ ically event driven . Events are act ions that occur on the this:
webpage_ f nc ti on clickHandle r ( evt )
/ Events are . ·gnals gen er ated wh en specific action occurs. I I some code here
}
make a web page m ore · teractive, e sen pt need s to be able to a ccess the contents of the
Example, Intrinsic event handling in HTML
ow when · e use r is ime racrJng with it .
< t ml x.mlns ="h np :/ / .....,w . w3 . org/1999 / xhtml ">
._/ ' · d5 of events tha 'gh · occu r are ue ~o-
<h ead >
'- A docu e · lea g,
<Lit le > Even t handling . t !< / t itl e >
' / heao >
<bod y onloaa =" ind . a l ert (' Bodyload ed .') ; " onu nl oad="window. a ert (' Uri lo adi'>g._.' ) :" ,
r
Client Sid• Scri pting Language 3.18 Form ana Even,'-'-
- - - - ~
cuent 5 1de!..:S~c,:;rl=C.>L.- ~ ~' - - - -- - - - -- - 13:!
,1!_
9_ _ _ _ _ _ __ _ __ ___..!F~o!!_r!m
!1_'•!!:n~
d_!E~ve'.!!!
n!..
t Ha~nd
~ll!_r:n!.9.
<form action =" nttp : // WW\e.google .o rg " onsubmit ="wi ndow . al e rt ( ' Submitt ing ... · ); "
pample:
onreset= "w indow . al er t ( ' Re s ett i ng . . . ' ) ; ">
<h tml >
<p > <head ><tnle > Events </ titl e >
<inp ut t ype= "te xt " name="someText" on keypress="w i ndow . a l ert ( ' Text fi e ld got <script >
character. · ) ; "onse lec t= "window. ale r t ( ' Text s elected . ' ) ; " 1 > f unction reac t ()
<br /> {
<input type= " button " nam e= "aB utt on" val ue=" Clic k Me"
alert ( "Pl ease ent er any va lue " )'
onclick="window . alert ( ' Bu tt on clic ked. ·); " / >
</ p > </ s cript >< / head >
</ f orm> <oody >
</ body > <f o r m name="myform" ac t ion= '"' met hod=" pos t " onmouse down= "react ()" >
</ htm l >

.
<i nput val ue="clic k mouse here " >

..
Output: </ form >
- ------ -
"' ... . </ body >
</ html >
~ -----J, output:
click mo se h ere

• LJsivaS cript enhanced form is different from a stra ight HTML form . The main d ifference is that a
JavaScript form relies on one or more event handlers, such as onClick or onSubmit)rhese invoke a
Ja vaScript action when the user does something m the form . like clicking a button.
The event handlers, which are placed with the rest of the attribu tes in the HTML form tags, are Event Object and Event Listeners:
invis ible to a browser that don't support JavaS cript. Because of this trait, you can o ften use one form An event object provides information about the element that has generated an event a nd enables t o
for both JavaScript and non-JavaScript browsers . retrieve it i.1 script. An event listener is essentia lly a mechanism that instructs a n object t o respo n d
m:I] Mouse Events to a pa rticu lar kind of event.
Java Script 's interaction with HTML is handled through events that occur when the user or browser In the DOM event model, when an even t occurs, an instance of a host object named Event is created.
manipulates a page. !his instance contains information about the event. including the type of event (click, mouseove r .
v>- When the page loads, that is an event. When the user clicks a button , that click, t oo, is an event. etc.) and a reference to the document node corresponding to th e markup element that generated the
event ; th is node is called the event target.
• ~ noth er example of events are like click mouse button, pressing any key, closing window , resizing
win dow ets)Here, we will see how a document object r eact to mouse-related events. • The Even t instance properties type and target , respectively, provide this information~ce an Eve n t
Mouse related events can be categorized as followi ng ways: instan ce is c reated, it is sent t o certain event listeners}
J- Simple Events: There are following simplest mouse events: ( In the JavaScript version of the DOM':,an event listener is si mply a fu nction that takes a s in gle
argument that is an instance of EventjA call to the addEvent Listener() m ethod on a node object
(i) Mousedown: Triggered by an element when a mouse button is pressed down over it .
associat es an event listener with a type of event occurring on that node .
(ii) Mouseup: Triggered by an element when a mouse button is released over it.
/ The syntax of addEventListenerO method is as follows :
(iii) Mouseover: Triggered by an element when the mouse comes over it.
do cu ment. add Event Liste ner( e vent, funct ion, useCapture)
(iv) Mouseout: Triggered by an element when the mouse goes out of it. where ,
(v) Mousemove: Triggered by an element on every mouse move over it . Th e firs t parameter is case-insensitive String which sp ecifies the type of the event (like "click " or
._;2. ~ompl~x Events: Also browser provides the following more complex events for conven ience: "mousedown ").
;::) Click: Triggered by a mouse click: mousedown and then mouseup over an element. The second parameter is the function we want to call when the event occurs.
Cont~menu: Triggered by a right-button mouse click over an element. The third parameter is a b oolean valu e sp ecifying whether to use event b ubbli n g or eve n t
(iii) Dblclick: Triggered by two clicks · h · · capturing . This parameter is optional.
Wit m a short nme over an element. There is also a
mousewheel event. but it's not us d Th ll . Event Bubbling is the event starts from the deepe st element or target element to its p a r ents, then
e · e scro event 1s used to track scrolling instead. It its ancestors which are on t h e w ay to b ottom t o op. At presentell the m odem browsers ha ve eve n t
occurs on any scroll, including keyboard scroll.
bubbli ng as the default way o f event flovi)
A complex action may cause multiple events.
For example, a click actually causes mousedown, Event Capturing is the event starts from top ele ment to tar get element. Modern b rowser d o n ·t
mouseup and click in sequence.
support event capturing by default but we can a chieve that by cod e in Ja vaS cript .
Form •net Event '1a~
~ e s cripting Language
3.2, Form and E.,..,t Ha"" ng
output:

DIV

t
Fig. 3 .1
mouseover and mouseout Events:
-..: .::...:...::~ :-:..:....:.::-:.:0-~1. ~=':.:. .. _ C.T:4 C..~e5 C-"1 en:..-:: ha...! · e:- u":e specified ele.me 1 t Vv,tho ,. / The mouseover and mouseout events are triggered whenever the mouse moves on to or off of an
::--.e-_""'i"ll-:-:::=.f =r::::f :;;-e...,: u.::.:..:L ."-::-:. :::...-: ::.::.. : c·:-c::: .!.s:e.r:e...-s • any D M obJe n only HTMi object. The mousemove event is triggered whenever the mouse is moved.
--:- - - - - :_ - .. • = ~\:..=. · : .-....-:-· .=-~- The mouseover and mouseout will get fired each time you move the mouse over and aroun d a ·d
':=:= ~.:i-?7:e-..:::..:..:.::e.::.::..."'"' - r::-e:::-x =-a....~es :: ~e.: :'I. ::_ . :: ·s -· KE e,;e.r t reacts to bub lin g and element. This means that you could be seeing many unnecessary event fires even thou gh it s.eeffi.5
~ - =---=- . .:__ __--=. :-' - -: -- : _ --- .. • :: :-:~!::.. x.:::.:: ' ?
like y u ar e moving your mouse v,;thin a single regt_,..·_o_n_.- - - - - - - - - -- - - - - - - ,

' :,:_;: ....

.:
-__- ---
,. __ - · . -
- - _._
.......
:-: 5: . :--..:--- -=-:' .. ... ,:_ ( -- )-
-- , ,/

Fig. 3 .2
:· :s. . :--:= --- -w _- = <=- > .. .:::- :: :: :: ( ::: =c:::
/ Mouse ove event triggers on every mouse movement. It's target is the topmost arid most nes ed
en which is covered by mouse.
v emove and mo s.eover/ mouseout trigger when browser in ernal timing allov.-s. That mean.s 1f
move th e mouse fast . intermediate DOM elements and parents will be skipped.
;,,•mg example is us ing onmousemoveQ. onmouseover() and onmouseoutO ent handle:-s t
h andle mousemov e, mouseover and mouseout events respectively.
Example:
:- - e..-. r-v- _-= <s. - >"-:::~s ~ ~ ......-: ,:.- ... : <::::'" >

<b dy >
< i id =" pa el ">< / di v>
.a- ;,.2 - :: = ----- - -~ . g:e-:=: e-~--: :: ~a ' • a e~ " <s c ri pt >
~~::; :~::\~~ : ;: ~~:;: : ~~:: ~s= , w ,· va panel, flag ;
::ra - a~ . -:. ~.;!.. !: ::.: ... = ~?- -=:e~ ! 1c~ ~es ,x - sE- ; oa e l =doc r.en - . getEle&e tByid (" pa nel " );
;.z ..~~ . c se ... : = - - S.EJ,-Pes:.-.:i se ;
,.a- - ::.i . .:l. - 1.."Se:;:_h .. = - _;e ..:,,,. :t.e-5 .. 0"'SE ;

Ooc en t . o seaove ;
J i rt l: , fa _se ) Pa nel. o
pa el.on
ar pa nel, flag ;
,.·.·~-
~ .
·,
~ ting La nguage
3 .22 Form end Event 11•~ 323
Cll~nt Side Scripting Lanqu•qe
ample: use of keystrokes.
fun ct ion mo usemove ( e )
£)( <ntml xml ns="ht tp : // WWw . w3 or g/ 1999 / xhtml ">
<ne ad >
if ( flag )
<t tt l e>Key Even t </ i tle,
{
"Mouse is at X : " + e . x + Y: " + e.y ; </ head >
pa nel. i nn ert1TML
<bo dy >
<di v io="panel " , </ Olv >
<scr ipt >
function mou seover ( )
var pane l ;
panel = document . getEleme nt Byld (" pan el ") ,
flag = false ;
"Mouse is Over"; panel . i nnerHTML = " Press a key . .. .. ;
panel . in nerHTML
ooc ument . addEv ent L1stener ( "key down ··, keyoown , f alse );

func tio n mo useou t () oo c ument . addEve ntListener ( "k eyup" , ke y u p, f al se );


document . addE ventListener (" key press " , ke ypres s , fal se) ;
func tion key down ()
flag = tr ue ;
{
pan e l.1n nert1TML += "< br /> Ke y Pre sseo :
</ script >
</ body >
function keyup ()
</ht ml >
Output:
panel. innerHTML "< or / >Ke y Releaseo " ;

C ,j loca {. func t on key press ( e )

;:· App,
v ar ke ynum = (window . event ) > eve nt .keyCode : e.wh 1cn ;
Mouse" 31 , - 08, Y SO
panel . in ne rH"TML += Stri ng . fromCna rCooe( key nu m);

Em Key Events </s cri pt >


</ Dod y >
Here, we will see how a document object react to key-related events. Key related events can be <I tml >
categorized as following ways: Output:
/ Keyd.o wn: A key is pressed down .
~ Keypress: A character key is pressed .
locai~ '·, _
,...Y. Keyup: A key is released.
~ There is a fun damental differen ce between keypress and keydovm .
Preual-.e-,
1. Keydown triggers on any key press and gives scan -code. Key Pt S\ed a
2. Keypress triggers after keydown and gives cha r-code, but it is guaranteed for character keys Key Rclca, ed
only.
/ The onkeypress event occurs whe n the user presses a key (o n the keybo ard). The order of events Button Event Handling:
related to the onkeypress event: • frhe onclick Event is the most frequently used event ~ype which occurs when a user cllcks mouse left
1. onkeydovm, 1iutton~ou can put your validation, wa rning etc against this event type. _
• The" on Click" is a event handler. which ex.ecutes a piece of JavaScript when an element ts . ' ed on.
2. onkeypress, and .:___ Remember that any event handlers are added inside html tags, not inside <scnpt> <lsc.npt>
3. onkeyup. Exarnple 1 : Using three input text fields and an inpu button. The form 1s designed to demon !e ~
As mentioned earlier the onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIIT, ESC) in all to get and set the text in a text fields . The HTML for the input button includes an even an~r wh1c..
browsers. To d tect only whether the use r has pressed a key. use the onkeydown event instead . W!ll call a fun ction (compute) when user clicks on the button. Enter th value in firs o s an
because it works for all keys . click on Addition button to get the resu lt in thi rd text field .
' \ ' ~-

Form and Ev.nt ._ 110


~ ct1wn~• ~'e!''llJJ:!'_n u• - ' - - - - - - - - - -_l3~.2~~- - - - - - - -
, / criP t '
</ hea d'
~1 tle >S t t e .. , t i t l t" ' ooc1 ,
p
o,, tt n i d=" myBtn " t ype •" butt on" >Cli ck f ol' a 111es s age l / but t o n >
s ri p t t y pe =" t e t J ava script .. >
al ue
v a r b ,t t ~ n = wi nd ow .aocument . getE l e111entByid ( "myBtn");
a lu e ou tt n . a ad t vent L1stener ( '" c lick "' , sayHello , false) ;
</ s c r ipt '
/p
</ bod
, / h t ml '
output:

< : _-~ ,,:. - ::. -: =" .. :i-:- · ~ c-== · :i._ :-:


. : : .: - : . :: - =~ · : e _

< s.:: r::: >


~-= as .. -: :: : ·>
'i • .,. ., tr:: : : ::.v </ ~1:

ffl CHANGING ATl'RIBUTE VALUES DYNAMICALLY


..
Earlier w e have seen we can change the attribute of an elements at scripting time~ va script prol7ide
us fac"li, t change an attribute of an element by assigning a new value to the attnbute t runti.m ~
,_/ \ e ca p :·•,:te the code of change in attribute value in a user defined function and can call that
~~~ ..
ction when an appropriate event occurs.
+- c - ,x;;,,.'"<=..,.=-;;:-- - · • G°he c.: an ge in any attribute value can be reflected to the user by highlighting e value r text 'f
s m e c >!:\Here we will show the updated value in blue and change the background color to pin :
~ T e onchange event is associated with many elements l<input> , <select>) of a form i an
he pful to make call to a function where the change of attribute value code is written.
y" The onchange event occurs when the value of an element has been changed or the o.irs r m ved
away from the element_ For radiobuttons and chec:kboxes, the onchange even occurs whe the
checked state has been changed.
In foll win g exa mple onchange event is u sed with three textboxes and whenever us.er will make
cha.Y1ge in value of these textboxe.s the Highligh method is called wit.'1 the n am e of the elem e.n
Example 1:
<ht l>
<nead >
<title > HTML Fori:, </ title >
'"i::~.. ... =· :cn / · a 2sc ri p: · / > <sc ript type= "text / j avascript " >
fu nct ion Hig lig t ( E e ent )

.... 1"'1 ~ -
Ele e nt. s l e. color = · blue ·
. : ,r ;,,e - El e t.styl e . bac grou dColor ' pi
-=y r;.e : - - ~ - . ta g<:>·t . );
</ s cript >
</ hea o >
Client Side Scripting Language 3.26 Form and Event H ~
3.27
Form and EYent Hendlln
<bo dy > CHANGING OPTION UST DYNAMICAUy
<f orm nam e=" myf orm " action=" " me thod ="po st " > we have changed the attribute val d . h
<p > .AS . in the option list at runt' b ues . ynam1cally in last section same way ~ e can c an ge
options . . ime Ywntmg the code in a function:}
First Name : <input va l ue ="mee na ks hi" type= "text"
./ The purpose of a~ opti~n list.is to present a user two or more items for choice Elements in option list
name =" Fn ame" onchan ge=" highlight ( th is) " I >< br> V are usu.ally set w_ en t e option list is created. However, you can change the ~ontent of an option list
Last Name : <i np ut val ue= "th a l o r " t ype= "text" at runtime by usmg a Javascnpt function.
nam e=" Lname " onc hange="highlight ( thi s) " I> <br > following example provides two radiobuttons to the user one is for fruits and another is for
Email : <input valu e=" th a l or . meena ks hi@gmail . com" type ="te xt" vegetables.
name= " ema il " onc hange=" highlight (thi s) " I> <br > When user will select the fruits radiobutton, the option list should present only the fruits names to
<input name =" su bmit " va lu e="s ubmit" type= "submit "/ > user and when user will select the vegetable radiobutton. the option list should present only the
vegetable names to user so that user can select a appropriate element of interest.
<i nput na me= "rese t " value="Meth od" t y pe= "res et" / >
This task can be achieved by calling a updateListQ function on onclick event of each radiobuttons.
</ p >
The updateListO function will be called with the value of the checked radiobutton so that it will check
</ form > which radiobutton is source.
</ bod y >
Example:
</ html >
<html >
Output: <head >
First Name: r-,i~a_g <t i tle > HTML Form </ title >
<s cript language= " Javascript" type="text / javascript" >

f ail·~tr
Last Name:.,_jT_h_a_lo_r_----::-----:-:--~
me:7~s~ ~maH.c~
function updateList( ElementValue )

with (document . forms . myform )

Example 2:
if (ElementValue == 1)
<html >
<hea d >
OptionList [0]. text = "Mango";
<titl e> HTML Fo rm </ titl e>
OptionList [0].value = l;
<sc rip t t y pe ="tex t / j av a s cri pt " >
fun ct ion OnS e lecti onC han ge (e l e me nt) Optionlist [l]. text = "Banana" ;
var s e lected = e l e me nt. options [element . se l ec ted! ndex) . valu e ; Optionlist [l] . value = 2;
a l e rt ( "you have se l ec t ed : " + selected) ;
if (ElementValue== 2)
</ sc r i pt >
</ head > Optionlist [0]. text = "Potato";
<body > Optionlist [0] .value = l;
Select an item fr om the follo wi ng lis t : <br /> Optionlist [l]. text = "Cabbage";
<select onchang e = "OnSelect i onChange ( t hi s) " > OptionList [l] .value = 2;
<o ption value =" Appl e " >Ap ple
<option value ="Banana" >Banana
<option value ="Orange " >Orange
</ select >
</ script ?
</ body >
</head >
</ html >
<body >
Output:
<form name="myform" action="" method="post " >
Select an item from the following list: <p >
1e 3 <select name="Optionlist" size="2" >
<option value=l>Mango
<option Value=2>Banana
</select >
: ·~ :<~: - .. _.:..
; -.-. '~ - ~ ·

' :" ,
. . -b---:

;.r_.r.

ez. . - ; . : ; ;,-:~ -- :.· ~ ,:z·, · - ~ · ~· . . ~~~ · ~z. :~O, . . ~-; 2.~


r __ , , - F : , ..- : .

- ...... . :.,~ ·-:-~::r:,:; "' .. ~ .. :..· .;_~ ,._ :.- ~ -~· .... ~ - .~..-a

':; .. f;"'J.Z...'-~ ~: t ;;: _:- ~ . .-~. . ~ -- ·..,": :_ .... :;·_: ".:~ .. ::--'..,....,: ~ _:,;:_; ......... =: ;; ~ /--~":"':.",.;.'It. .. :. ; ":. : :... ;, _:; :._";¥ ·.~
~·z :..:..' . .r:A~' ·J .. '.:::L · ;:: '.,, ..-, ;- .. ",,k;:, !",.,; : ;.r:t:. f-: ~;. .. - :,7 .. ":..: ! ~ . __.....- :,~:: ~J';;,70~:
"",:....t .... : ....~ ::... ..::.i.:..: ~ :.:_:.::--J :..,-.. J,,.1:;... ••• : / ~ .... ...:~ ~ :.7 "": ~ ...:..,-,;: ~.-:.:.:~: ,. "'., E :-:. "'. : 1:: .~:',~ ::.~ .. : ~ : :...~; · .$~::

/ k "-·· ... ~..:.t.A ~ --:.~ ~J.-: . : l "::""- t .:.;- .. ""t.:~..~:. • ·,;-,:.: :: ~ 7;,r:;= ~:. . :::r../-:,;'f/;- . !:. . . '. f:" ··1;~ .. ~;;D
1

/ ) . -::- ~ "/.:J . : ~ '"'.;;-: ·. "h: '..;"'._ y RF.,, ::&"K... '::".'::/' )l";r: '.,: _. : . -":.-:..."::"Jo/-.J ;,_.:.,: ...: . :-..r:..':;.,::;:..~f;;. : "...f :r.£ ?:?-.:.<: ;!
'/:."..,,::;,::,.,,;r "/.ID;:".. : . · · ~ ',:"": " :,':::"' "••/./'/,.~..,'A:,:...': ~ 'l .. ~ :.r~: . '!l .. _:<;~:::,,:...-..,[, :-..,:,t:r/.LJ.:-1-r: .
4

~ .;.,,, ~ .:. n . . t.-:; .;;·r.; :,,;:·.7 ! .. : ..7-.~'~: •:.;" ~" ~-- ...A"~; ·:n:. .~ ..1=: ~::._(.ft; u . . ~I' ~ / ·n~:, ~ ~c--"'~ ;;f..d
· : . ./ . . .~~. •:. .,: :~ . . r ;. ,. . . .... . ,;. . . . .... ,., ,. . ..-..~ :~~~ ·:..! J',, .-.! !1;,;., . . ,..::; · _~r
, :;~".r-N~ ,: ff'/.&·: ..•...;., ....': ::,.;,..rs:: · :. . . f !:·,t ::.i:;r.J1./f.(,.:::".. ....~ ~t7'1 ... 1J:: L ·11: ~J., !J<:.rw
~ "/() ... •..s; f .... .. ht -1 ... : ...1: '...:-•,.nr:.k ,. . t ";,f; ~f:.'_."' ... '..;r. ., l'!'[ .. __..1:,I:.{ ... ~<:...r ~. . n 'Jr. Ih ·111:: ha·,e chan ged an option list cynamically same '"'-a'J we can change a •

:=-~~~; ::::;:\::•?;. ;:~:~:'~d:·:~·::;/t~r, • ~ . >; .LS r;f ~ III g example make use of op on list (consist of fru its name) a nd a bu
~ rm vr, LJ be aded hen option · t shows the list of f rui and labe of b
p ...unp1;- · k on h e bu n o its label wi.U ge changed to .e "vegeta I.es" a nd list 1l display all
Here. bu o is acting as a togg. b-utton and its label keep changing between fruits a
click.
, ,. ~ ..... , ,. ~ f' rr) 1fj ,., l f: ,

, •;.r r i ;.,~- l orie, ;:;g~ ·-: ci , ~'S...::r1:::,,.. .. YP'-• .. tt: / / Ja , a~r. .. ip ..


fv r,~ r; ~rcle r. 1o 1 1 e ad,
, i le > HTl',L FOr'l'.1 </t i le )
Jar I a " ( U ~l? l!:( "l:(l : "
'scri pt lang age= " Javas cript" ty pe =· ext/ · a va sc r i pt ">
w1 n ( Co urr:n . f orms . 111yformJ
func tion updatelis ( Ele ent Va l ue )

1f I a . r.he r. ed ss ue )
w1 h (documen t.forms.myform )
x• • a .val
if (b.che ck d •• tru e)
X+ • O. va l ue+" " if (ElementVal ue == "Fr · ts ")
:uo Form a nd Event Ha . , Sid• s cnpt1n9 Language
~ ~
. Ii . . 3.31
Fotffl 8'>d e..- ~
following app •cation is retrieving the firs 1
toggl e9un on. val e ; "Vegetables .. ; wit'l email option becauSE of that us name and last name from use.r and sing a rud!len ne!ci
Op ti on i st [0] .te xt ; "Man go "";
clicked. the add EmailQ function is call~Would not able o enter email.Whe.n the s bmi bu.non 15
the user's first and Last names. Th e fu .. · The ado.Email{) function ates an e- mail address =mg
Opt i onList [0].val,e ; 1 ;
element, and the form is submitt..d to~cnh oCnGthen assigns the e-mail address to the ·ralue of ~1le E.ro.ail
OptionLi st [l] . te xt ; "Ba na na "; . ~~~~~~~~~~~~~~~~~­
~~_:...~~~~~~....::..::.:.::.:::~-~~~e..'.:.::~ljP~rog~ra~m~
Opuonlist [1 ]. al e ; 2; fXaJllple:
<html >
1f ( Ele,:;e nt al e ;; " eget2oles ") <h ead >
<title > HTML Fo r </ title >
: ogg e3 tto , . a ue ; " Fr i ts " ; < scr i pt l ang uage ; " Java script • type ; "te xt 1 j ava sc ri;:rt • >
func t ion a:ldEma il ()
Optlo 1st [ 0 . i:ext ; " Po -a t o " ;
Op i onlist [ 0] .v al e ; 1 ;
,ii.:h ( document . forms . myform )
Opti on ist (1) . text ; "Cabbage " ;
Opt ionli st [ - . al ue ; 2 ;
i f ( Fna e. value . lengtn > 0 && Lna e . val ue . lengt h > 0 )

Emai l.v al ue= Fname. value . cha r At ( 0 ) • Ln ame. va lue + "@,< z . co

</ sc r iot >


<I ,eaa >
< tx>oy >
</ scrip.: >
<f or a e; " for " act ion ; " " e,: Od; " post "'>
</ hea d>
<p >
<Dody >
<select: na e ; "Optio i s t " s i ze; " 2 ">
<f o r na me; "my fo rm"' action; "" method;"pos: · >
<op- ion val ue;l >/olango
<p >
<Optio al ue;2 >8a. a na
First Name : <input type; "text " name; " Fname " / > <br >
</ select>
Last Name : <input type= "text " na e; " Lname " / >< br >
<br >
Email: <input type; "hidden " name;"E ai l" / ><br>
<inp t name ; " t ogglebutton " al •e; "frui s " t ype; " reset "
<i nput name;"'Submit" v alue;"S ub it" type; " but ton"
onclic k; " pda t elis t ( this.v alue )" >
onsubmi t =• ael dEr:.ai l ( ) · ; >
</ p >
</ fo </ p>
</ body > </ form>
<I t l> </ body >
Output: </ht ml>
'M"ango - - Output:
fi3oiato --i
Cabbage
'===. ---- - '
i Banana
i=- -
. I

First · ame:,)nee---"a_kshi
_.,·- - - - - ~
I Fruiis j I Vegetables Last Name: ~
Email: L-- ' - ~ ~ ~ ~ ~ - - '
- -I

ID MAHIPULATIHG FORM ELEMENTS


In last section, we have seen various example of manipulation of form elements before submi~
any form to CG! application. Javascript provide us facility to manipulate elements on a form after INTRINSIC JAVASCRIPT FUNCTIONS
the user clicks the Submit button and before the form is actually submitted to the CG! application. ~avaScript has a special set of f nctions called ·ntrinsic functions that mimic actions
Javascript make it possible with help of hidden element which is similar to any html element exce.pt
Utton and Reset bu tton of a form.
it does not appear on screen. An intrinsic function is often used to replace the Submit button and the Rese button wi
A hidden element has a name and value that is sent to the CG! program along with other elements of graphical images:-which are displayed on a form in pl.ace of these buttons
the form for processin g.
Form and E ent ~

ags t simulate the functionality of submit and : ex~ = o c Q :. gc: : :.:;- ~- :3: :-:
1f c : s.e :1 :ec : I") : e.rc

sc r1;:, -: >
</ heao >
<tioay >
Fo - :t le > <1np t t 1;Je= "tex : " : a =· .y - ex;: • 01sao.e ·= "C1sa e-=·
" al e= "0 1sa- leo a:!. ~·
<OU tt on ond ic =· ogg l e isac.ec; (); " >C a ge Sta: e< ' bvtton >
<:.-,:--: .-,) </ bocy >
<I t l >

ou~:
<:~...,... --e - ~, .- - · ac ion="" rnet hod= " post " >
< lj, )

2 :
<i t ty e =" text" na e =" Fna e "/> <br >
<i put cyp e= " te xt " na e= " ln a e " /> <br>
src= " s o it . jpg " onclick =" j a ascript : docu ment.forms .
eo ,~, C a e St te
----- I
Oisabted value CN,
~----
<i r:g s rc =" re set .j pg " onclic ='"javascript : docume nt .
my form.submit () "/>
ll!J Read Only Elements
forms . myform . reset () "/ > / Most of the <input> element uses read-only property to sets or retrieves whether he contents of th e
</ O> elemen t are changeable.
, / fem> / Jf the s ate 1s read only, t.1-te user cannot modify the contents of th e elemen . bu the eleme nt
, / booy > con ·nues to get focus a nd be selec able. If you want to prevent the user from i teract.ing, ·th the
,; object, use th e disab ed property.
Output: / The possible values of read only prop erty are true or false that indicates whether the con ten of the
e ement can be changed.
F'tr'I ·.. "ain.e:J.1- - -- - -- - - Following example using a textarea and a button. Initially textarea read- oniy property is set beca use
I L N amte·'
of that user will not able to change the text written m textarea.
Once, user will click on button then readonly property becomes false and now user can change . e
content of textarea.
Example:
<html >
<nead >
<script type= "text / java scr i pt" >
E!II Disabling Elements functio n changeState ( ) {
v It is co m~on_to display a form with some elements disabled, which prevents the user from entering var text.area = document. getElementByl d ( "myText");
textare a . r eadOnly = ! textarea . readOnly;
inforrnano n mto the element.
Following are the characteristics of disabled elements:
</ script >
1. Cannot have focus.
</ heaa >
2. Do not receive or fire mouse events. <body >
3. Cannot receive user input. <textarea id ="myTe xt " rows="3" r eado nly="readonl y"> Change t his t ext \</t ext a e a>
4. Disabled elements are rendered in gray by default in browsers. < button o n e lie k=" c hangeState () ;" >Change me <I butto n >
Following example uses a textbox with disabled attribute and a button. The button is acting as a </body >
t oggle button which will check the content of textbox and detect that whether textbox is enable or </html >
disable and make state enable if disable or vice versa. Output:
Example:
<html > [ '•, . , , ,, rn
<h e acl>
C an e m
<script type="text/ javascript">
function ToggleDisabled () {
4...
Cookies and Browser Oat
~ hapter Outcomes... ]
00 Create cookies based on the given problem.
00 Develop JavaScript to manage a coo kie in the given manner.
00 Write JavaScript to manipulate the speci fi ed att ributes of window object in the given manner
00 Write JavaScript to create browser history object of the given objec t.

~earning Objectives...
00 To learn Concep ts of Cookies
00 To understan d Basic Concepts of Browser Data

ffl INTRODUCTION
• A cookie is a small piece of information from a web server th at is stored by the web browser in the
client's machine. This information is sent to the server each time the client requests a page from the
same area in whi ch the information was received.
• By default, the cooki e will only be sent back during the same session with the web server.
• Modern web browsers support a number of ways for web sites to store data on the user 's com puter ·

m
• t:A
with the user's permission - then retrieve it when necessary.

COOKIES
cookie is a small amount of nam ed dat~ tored by the web brows.fr and associated with a particular
web page or web site.J
• Cookies serve to give the web browser a memory, so that scripts and server side programs can use
data that was input on one page in another page, or so the browser can recall user preferences or
other state variables when the user leaves a page and then returns.
• (cookies are still one of the easiest, simplest, and most widely used persistent storage technique for
web pages today. They are easy to set, safe, well understood by most people who browse web pa ges,

rm and require little overheadJ


Basics of Cookies
• Cookies are usuall small text files, giv~n ID tags that are stored on your computer's browser
directo r program ata SU ol ers. .-- - -
:---
• C~es are created when you use our browser to visit a website that uses coo.kies t o keep track of
Y0 ~r movements wit~in the site, help you resume w ere you le~t off, remember your registered
login, eme se ec 10n, preferences, and other customization functions.
' Th.e website s~ores a corresponding file (with sam e ID tag) to the one they set in your browser and 1·ri
this fl · · -. ·
. 1 e they can track and. keep . mformat10n on your movements within the site and any
Information you may have voluntarily given while visiting the website, such as e-mail address.
'[4.1] •

...............
Client Side Sc ri p ti ng Langu n "
·
-----. 4 2
.

l informa tion excep _ -


_

t for the url of the web~ th a t reatect th.


- b
--
Cookl os nnd Brow a"!. O,i,

c .,,~ample:
.,,.. In thi s example cooki' e Will get c
43
· - - - - - - -- - - -~ ~ ~~
CooklH and ~
B r o:""~a l ~
( Cookies u sually d n't cont ain muc 1 . . , ---- ff t s ·Rnd a random num er.
- .......~=- .,.,.~
coo 1e t e uranon o t e coo ie
k' 's ab1ht1es a nd e ec .
. . cont a ins. it u su all y ca nn ot be used t reveal Yoi
<ht ml >
<head >
reated on onchange
event oftextbox.
Due to the little amount of informatwn a cooki e tr
identi. ty r person a llY 1·ct e nff.ri
1 , • ng informati .'1.
on . k. \ ll n -persist en_!lr.,nd . e nt cookie s. <titl e > Cookies </ title>
~ . persist
f k. nam ely ess1on coo 1es __ <sc rip t > -
There are t\'II O ty pes o coo ies · - . - . ~ ~se r's sub fo ld er w hile you a r e visitin
1. /session cookies are created tem or nly m Y k. . deleted . ga fun cti on Writ eCookie()
...r website. Once you leave t h e si te · the session co~o=1~e..,1::.. s..:::.;'--c--
. subfolder and are activa ted again on ce you vi· . {
· ki fi ain in our brow er s . Stt
,?-· Persistent coo e I es rem _ . kie A persisten t cook ie rema ms m the brows . with (document . myform)
the website that created that_part1cu 1_ar _coo c.ookie's fil e. ers { -
sub folder for the du rat io n penod set withm the
document. cookie ; ::-N~~e="
.,,_.Advantage of Cookies: . . . alert("Co O k ' + person. value + '',· "
r:- -simplest technique of m amtammg the st a te. le Written")
--2. Cookies are maintained a t client side .
.,.,»isadvantage of Cookies: </ script >
1. It will not work if cookie is disabled from the b rowser
</ head >
2. Only textual information can be set in Cookie object.
<body >
How Cookies Work?
@ Reques1 + Cookie <form name;"myform" action=" .. >
By default, each request is considered as a new
request. In cookies t echnique. we add cookie Ente r your name : <input t~pe="text" name; "person"
</ form > .·. onchange;"WriteCookie() "/ >
witnresponse from the ~ervlet. So cookie is
stored in the cache of the browser. </body>
After that if r"equest is sent by the user, cookie </ html>
is added with request by default. Thus. w e Client ® Response Cookie T Output:
recognize the user as the old user. . Fig. 4 _1 -k
Fig. 4 .1 shows the working of cookies.
(_A cookie is nothing but a small text file t hat's stored in your browsei)It contains some data:
1. A name value pair containing the act ual data.
2. An expiry date after which it is no longer valid.
3. The domain and path of the server it should be sent to.
11!1 Writing a Cookie with JavaScript I Creating a Cookies 1111 Reading a Cookie with JavaScript
Cookie data is automatically transmitted between the web bro ser a n d web server , so server side
scripts can read and write cookie values that are stor ed on the clien t . • :~ ~:nr~:~~~=~h~~~ument.cookie wheneve_:_W,~W":_nt t_<? a~~ess the c_~~e. With JavaScript. cookies
When a web server has sent a web page to a browser. the connection is shut down. and the server
forgets everything about the user.
var x ; . document.cookie; *
/ ' Cooki es were invented to solve the problem "how to remembe r information ab out the user": Ex. akmple: In this example cookie will get created on "Set Cookie" button click and will read wh
c1ic on "Get Cookie" button. en u ser
1. When a user visits a web page, his/her name can be stored in a cookie. <html >
2. Next time the user visits the page. the c;;;ki~ "remembers" h is/her name.
<head >
/ Cookies are saved in name-value pairs like:
us erna me;Meena ks hi Thalor; <t itle > Cookies </ title>

/ . Every cookie has four parts namely. a name. an assignment operator, a value, and a semicolon(;).
When a browser request a web pag om a serv~r. coo 1es be ongmg to the page is a nded to the
request. This way the server gets the necessary data to "remember" in fo rmat ion about users. .
<script>
function writeCookie()
{
/ Creating a cookie is a very simple. You simply assign t he cookie to the window.d ocument.cookie with (document.myform)
object. {
/ JavaS cript can create cookies with the document.cookie property.
document.cookie; "Name;"+ person.value+" ·"
documen~ . cook ie; "usern ame;Men;i kshi";
If you set ·a n'e w c o ~ e r -;;;ok;s are not overwritten. The new cookie is added to alert( "Cookie Written")
document.cookie. so if you read document.cookie again you will get something like:
cook iel= val ue; cook i e2=va lue;
Coo • • a d Brow~ d• sen un Lan ue e
cu• t 5
~eadCoo 1e ( 00 c men: w'ite ( "coo ie eeo..tuenc18r_- ~
s no: • orio·,.
else 1,

0 cumen . wri e ( doc •J en


\- a, ..... : , COOqe ) ;
}
:f d c c :: . c ,: e ::: "'")
</ sc r i pt>
x ;
</ he ad>
e ls e <bod >
oc t . coo 1e , <f r m na e ="myform" ac· on. · · ,
c .. e,,~ . ..,- - e l Ente r your ame : <input t yJe =" 0 ..
"R • t,x t a e· "pe •
onput na e = eset al ue ="Se C • · r son l>< br ,
"R • oo i es , ype· "c •
<in put name= eset value . "Get Al 1 · unon onc lic k- ""'' lt eCoo<l e ( )" / ,
< sc-ip: > • Cookie s · t vp ·"b •
</ form > 'e . u, t on• on~ l. C< · " -eaoC <1e· ()"J,
ead >
</ body >
</ t ml >
• act on =" " >
a,- e : <i put e ="t ex " na . e=." perso n" /> <Or > output:~~ ~~==-=--~~=:==;::=::=::=:=::=--,
en "' e= " ResE,t " e; "Se t Coo ie " type =" but on " one i c ='"wr iteCoo ie ()" /> En er _·our name. meenakshi
not found
<1,tp a~e="Re s e • al e= "Ge t Coo 1e " type ="buno " onclic ="re adCookie O ."/> Se o o Gel II oo ies .
--- es
- -~ -

1111 Setting the Expiration Date of Cookie


Ou tput : • (1.n addi tion .to a nam e ~ d a value, each cookie has optioua.l a tributes hat contra its l! feume and
sco e)cook1es are t rans1en by default; the values they store last fo r the durat ion of the web browser
session bu t a re lost when the user exits the browser.
"ame=meer aksh1 You can extend th e life of a cookie beyond the current browser session by setting an expira ion date
and saVIn g the expiration date within the cookie.
11 • ~ expirat_ion da c is typ ically an increment of the current date.~ avaScript can create. read, a nd
delete cook ies WI h t he docu ment.cooki e property.)
11!1 Deleting a Cookie with JavaScript
Del.e in g a cpokie i~ ve ry sim ple. Jus se he e . ires pa:amete to a passed date :" /
ooc~ ,:,-. :.coo i e=" se rna e=Meena sni ; exp ir es= Thu, 18 Dec 2019 12 :00 :00 GMT " ; *
Yo•1 can a so add an expiry date (in UTC or GMT time). By defa ult. t he cookie is deleted when h!
/ doc u en .cook ie = "username=; e pires=Thu, 01 Jan 1970 00 : 00 : 00 GMT ";
o e tha t you do n t h ave to s peci fy a cookie value wh en you delete a cookie.
* b wser is closed.
Example 1:
Ex.ample: <h t l>
<heao >
<ti l e > Cood es </ ti t e>
<t ' t le > Coo ies </ t t l e> <script >
/' . fu ncti on wr ' te Coo kie()
<scrip > .
fu nc t ' on wri eCoo i e ()
va r d = new Da te (); // Cr ea e an aat e object
a r a= new Date (); // Crea e an da ~ obj ect d . setT 1me ( d . get Time () + ( 1000 • _60 " . 60 • ~41) ;
/ /Set he time to t he past . ieee mi ll 1 seonds = 1 s econd
d . se t Ti e ( d . ge Ti e () - ( 1000 • 60 • 60 • 24 ));
wit h (do cument. myform)
/ / Set te t ime o t he pas t . 1000 milli seonds 1 se cond
{
wi t h (doc men t . m f orm ) pe r son .vale + " ; expires=" • d.toGMTS tr i ng () ;
docume nt.cooki e = " a e= "

do cument .coo ie = "Name= " . pe r s on . va l ue • "; exp i res= " T d. t oG St rin g ();

fu nct ion readCookie()

f uncti on r ea dCoo i e ()
if (doc men t . cookie == "")
if ( doc ument. cooki e == " " ) document. wr ite (" cookie s not found" ) ;
Lan ua e

e ls e BROWSE.R
docume nt . wr ite ( oocument . cookie);
• A b! owser 1s an applicano.!l.J1roQr~m · ~- ;;:;;::;::-:-- - -- - - - - - - - - - - -
</ script , l'nformaoon on the World W•de-W ~ b run <'1.. rovides a way to look . L il
.----, ' e ., •'vW) a a na m eract w1tr1 a e
</ he ad >
A web browser {a browser) 15 - 1 - - - - -
t ' an applicauon sOftw
<body > inform a io n resou rces on the Internet and W . are fo r retrieving, presenting and traversing
<form name="myform " action="" > oefi nition of Web ~owser: orld Wide Web [WWW)
Enter your name : <inp ut t ype="text " name= " pe rson" />~ br > . .. . . .. "A browser 1s a software used to 1 .
<input name= "Reset .. va l ue= "Se t Cookies " type="bu t ton o ncl1ck= . writeCook1e ( ). / >
d' b\ ocate retrieve a d d' I
/ Web. me 1u mg we pages, images ·d ' !1 isp ay conten on the Inte rn et rnd World 1de
<i np ut· name= "Rese t" v a l u e = "Get All Cook ies" type="butto n" onclic k= "readCook1e()" / > A browser 1s an app ~ ·cauon prog'VJ eo and other fi les·.
</ for m> / , info rmation .
on the Wo Id W'de Web
ram that pr 'd
OVJ es a way to look at and interact with all the
</ body > There are five major bro, sers used on desk
</ html > / safari and Opera. top today namely, C:hrome, In ernet Explorer. Firefox,
Output: The ma in fun ct ion of a brow~er is to
--------- Server an d displaying it in the\'ro presen the web reso re you choose. by requesting 1t from the
En er \'O r name: Anurag
. .._ - - --------- Name=Anurag {
The resource is usually an HTML docu
I' wser window
b
s~ Coo~.?._ l_G_e~,:ll_~ook es , co n
tent The location of th I
·
ment. ut may also be a PDF . image, or some other type of
e rPsource is specifi d b th · ·
Iden tifier). The way the browser\ . e Y e user using a URJ (U mforrn Resource
speci fi cat ions. rterprets and displays HTML files is speci fied m the HTML and css

Example 2: Fig. 4 .2 shows structur~ of browser. The browser's high level structure consist of:
<html> 1 User Interface: Th is includes th dd b ·
· e a ress ar. back/ fo rward bu ton bookmarkin g menu. e-tc.
<body > Every part of the browser displa h · ' -
_ ·- ~ - __ . Y except t e window where you see he requested page
<scr ipt> ;i.. Browse~ Engm~: Marshals actions b~tw en the Ul and the renderi.!!&engine.
// Set a cook i e .
3. Rendermg Engme: Responsible for displaying requ~sted con ent. Fo example. if the requested
doc me nt . codki e = "u se rname =Mee nakshi Tha l e r ; expires= Thu , 18De c 2019 1 2 : 00 : 00 GMT "
co ntent is H1:'1L, he rendering engine parses HTML nd CSS. and displays the parsed content on
II Get a cookie.
the screen. Different browsers use different rendering engines as well. These are some of the
if ( document. cook le )
popular ones. Gecko - {Firefox) , WebKit - (Safar i). Blink . {Chrome. Opera {from vernon
{
15 onwards1 ). The first step of the rendering engine 1s parsing the HTM L document and
do cum e nt . write ( "Created Coo ki e i s: " + document. cookie) ; co •,. g -he parsed elements to actual DOMnodes in a DOM tree.
cooki Str i ng=doc ument. cookie 4 . Networking: For network calls such as HTIP requests, using different im plemen aticns for
var li s t = cook ieStr ing . s plit ( " =" 1fferent plat fo rm behind a plat form-independent interface.
doc ume nt . write ( " <br >Split List : + list ) ; 5. U! Backend: Used fo r drawin g basic
Ussr lmertac:e (UT)
if ( li st[ 0 J == "use rn ame" ) widgets like combo boxes and windows.
{ Th is backe nd expose a generi c interface
var da ta = l i s t [ l ] .s plit("," ) ; th at 1s not plat form specific. Underneath it
ooc urnent . wr i t e ( " <br >Data : " + data); use operating system · user interface
methods.
6. JavaScript Interpreter: Used to parse and
</ scri pt > execu te Ja vaScript code.
</ body > 7. Dat a Storage: This is a persistence layer.
The browser may need to save all sorts of
data locally, such as cookies. Browsers also lJl bael<er>a
support storage mechanisms such as
localStorage, IndexedDB, WebSQJ. and Fi.g. 4 .2: Com ponents of rowser
FileSystem. ",}
.:; local Co~ept of Docume nt Object Model (DOM):
t it!· \ke • · ,n _ CJ ,mp ' LThe DOM is a World Wide Web Consortium s andard. It is a standar for cce sing docume
W3c Document Object Model {DOM) is a platform and languag -neu al interface) h · au~
Created Cookie is u.semame=Mecoakshi Thruor Programs and scripts to dynamically access and update the content, structure . a ,d sty! o, a
plit use·
u cmame~\ i!ecaaks!Ji Thalos document.
Data : ~r.cnalcshi Thalor
/ Every web page reside} inside a browser window which can be consider ed as an obJ ~ A )oc.imer.~
0
bJect represents the HT ML document that· s displayed in that window

I •.
4.8 Cookies and Brows cuont Sid& Seri
Cl ent Side Scripting Language ~
. roperties that refer to other objects which all ow access t WindoW Object: . Cool<IQ anct e row- o.ra
The Docu men object has vanotu snf The way that document content is accessed and modi; adnd The window object is at the top Of the DO .
m odificat ion of docu ment con e · le is
ca ed the Document Object Mod el. or DOM. . . The wind ow object contains pro M hierarchy Thi Ob
. . th t common programming language used m accessing the DOM . This all / of the browser is a property of t?erties that apply to the s )ect represents the browser wmdow
The Javasc.i:1ptb sh e mo~ DOM It provides the functionaliti es of showing/hid ing elements ( Ows ndoW ob ject provide d ff IS 0 bJect. entire W1_ndow For example , the status ba:
the dynamic e av1 or o · t ovin 1 t d text W1 . 1 erent pr .
,ma es and whole divi sions. et c.), animating e 1emen s , m g e emen s . an so on. . / runctionallt1es. opert1es and methods t di
·Fig. g4 .3 'shows 1s
· a s1mp
· le:.:.;~~.;::'.I...:.:.:..:~:....:.:.:...,..
h ierarchy of few important _ _ _objec ts (DO M)
___,:..__..:._, . . o sp1ay dialog box and for other
)(ethods of Window Ob ect:
Vi nao.....
a rent se,r top
sr. HO , Methods
rame ale r t Str i n
confi r m(St ring ) Dis la alert wi
Pop
. !al~ .
. ndow d1Sola m tne iven Strin value.
up a wmdow
I contains th di
tw at splays the given String value and
,story document tocat,on na gator I indicatin . o bu~ s labeled Q!{ \l,lld Cancel. Return B an..\I
g which button was pressed (true im nlies that OK was
, ressed . ---- er -

+ 3. prompt ( String, String )


hn. anchor Pop ~p a window that displays the first Strin g value and I
contains a text field and two buttons labeled OK and Cancel
I Second String argument is initial value that will be displayed \
in the text field. Return String representing final value of text \
radJO tex:area on te cheCKOOX
I field if OK 1· s presse d. or nuJl/u ndefined (browser-pendent) 1f.
Cancel button is ressed.
passwor
iI reset .,-,,.. ope n ( String, String)
Open a new browser window and load the URI specifi ed by t he
first String argument into this window. The second String
op!Jon specifies a name for this window suitable for use as the value
of a target attribute in an h1ML anchor or form element.
Fig . 4 .3
Optional String third argument is comma-separ ated list of
rr:e Objects a r e organized in a hierarchy Th is hi era rch ical srructure applies to the organizati~ of
bject in a e d ocu.me :H.
I "features ," such as the window width and height . Returns an
object that is a refere.."lce t the global object fo r the new •
/ · Window Obj ect : It is top f the DOM hi erar..chy !t is the outmost eleme nt of the object hierarchy window.
- he •Nin ow je re p resen ts ar. pe n win d ow in a browser. An object of window is created clos e ()
a • ma ti ca.11, by the bro ser Close the browser window executing this method.
,,,£,. focus () Give the browser window executing this method the focus.
Navigator Objec t : The JavaS cn pt n avi gator object is the object representation of t he client
internet ro ser or web n avi gator program that is being used. Navigator object is the toE level 7. J ol ur ( ) Cause the browser window executing this method to lose the

/3·
~
ject to all o ers he n aviga r object co n ai ns informati on about the browser.
Documen t Objec : Each H L d ocume nt th at gets load ed in to a wi nd ow becomes a document
- he 9cu me n co n a m s th e cont ent o f the age. The d ocu m en obje is itself a properfy of
e '#Ul ' ow obJec -:-hi s makes se nse , oeca use all a ocumen ts in a Web browser are displayed in a
8. I mo,e To ( Nombec , Noabec)
I focus. The window that pins the focus is determ ined by the
operating system.
Move the upper left corner of the browser window executing 1
I

wiJ OW
this method to the (x, y) screen location (in pixels) specified by \
the argument values, which should be integers. The upper left \
/ Form Obje<:t: -E• e:,, l).i.::lg-e!l.C}~ed m th e <~orm> .. </ form> ~ sets the form objec:_!. The form
o je-ct c m21ns a !l t h e ele :n e nts j e :fn e for t h at object such as textfields, burt onS:-radio bu ttons. corner of the screen is at (0 , 0).
an c.h eckboxe.s. 9. I mov eBy ( Nu mber , Number ) Move the upper left corner of the browser window executing \
s. History Object : The his o r '/ obJect in DO M lets you send the user to same w herein the h istory list Ithis method right and down by the number of pixels specified
from wi~n a JavaScri _ prograrr. by the first and second respectively . argument values. These
I
_.,,-6 . Location Object : The Joe.a ion object ·s a pan of a Wind ow object wh ich reference to the current values should be integers. 1
URL I can b e r eferenced y win ow loca ' on. 10. resizeTo(Numbe r , Number ) Resize the browser window executing this method so that it has
Th!:m commonly us DO M objects are:-\-vi ndow , loca no n , history, navigator, docu ment, images. width and height in pixels as specified by the first and second, I
links, forms . elements, X."1 HrrpRequest.
Applications of DOM, 11.
I res ectivel a ument values. These values should be inte ers.
resize By ( Numoer,Number ) Resize the browser window executing this method so that its
l. To ren e.r a ocumen su ch as an HTML page, most web browsers use an internal model similar to I width and h eight are changed by the number of pixels \
he es o f eve r / ocument are organ ized in a tree st ructure , called he DOM tree . specifi ed by th e first and second, respectively. argumen ;
.m n e nam ed as • ocum en object". When an HTML page is rendered in values. These values should b e inte ers.
rowsers. : e browser dov-mloads the HTML into ioca m em ory a n d au omatica lly parses it to 12. print () I Pr int the document contained in the window executing this '
display e page on screen . L_ \ method as if the b rowser's Print button had been clicked .
2 en a we . age is loaded, the browser creates a Docume nt Object Model of the page, which is an
.i\s window object is a top-level object and some properties are defmed for window object. F
o Ject orien ed representan on o f an HTI.lfL docu me n t , that a cts as an interface between
Properties of window object refer to Section 1.2.6 .
Ja vaScri _ and t, e docu m en itse.f a n d allows th e creatio n of dyn am ic web pages.
,• - ~~

~
Client Side Scripting Language 4.10 Cookies ond Browser Data 4 11
' idaSc~~p:tln~g~
La~n:g:u:a;ge::~::--:-~~~~~~....!.!1__~
' ~ ~ ~ ~ ~ ~~ ~~__.!~~~~~~~_Q!:!!_
Cook.le i and B row _.. Dllta
,nple 1 , open a new window.
Example: Us ing metho d s t o d isp lay dialog box. ,1..- ml
<html > / J1euoJ1t
<head > <html >
<script > <tiodY >
window.alert ( "Here ' s a s imple me s sage" ) ; <scri pt >
document.w r ite ( "Confirm : " + wind ow. co nfirm ( "Go or Stop ?" ll , ctocument . write(" Hello everybody ! I I ! ")
documen t . write ( " <br > Prompt : " + window. pr ompt ( "Yes or No ?" , " Ye s" ) ) ;
</ script>
</ script >
</ head > </ body >
</ html >
saJ11ple,htrnl
<html >
<body >
<sc r ipt >
va r winOb window . open ( "hello .html", "win dowName",
"top=200, left=l00, width =250 , height=l 00, statu s" ) ;
</ script >
</ body >
</html >
Opening a Window save the HTML d ocume nts and open the sample.htm l page in your b r owser t o see the followi n g
The w indow object , which 1s a top -level object in Clien t Side JavaS crip t , represents a window or a output:
/ frame (within a framese t) . 0 ....- ~ - - - ..
Since, w indow object is a top -level object , it contains other objects like 'document' , 'history' etc. ~ C: ._: ~ lfl tr(f"" ..')s~,·l•" r" ) . ~ .....Hl•O
/ w ithin it. F ~ .,. _ . ,...v w "'.'_.. :'. ,... __ .iw-.
::; •

For example, window.document.frames[i ]. where i 1s 1,2,3 ..... . refers to the index of the frame
r esi ding in the current wi n dow. .
The open method of window object is used to open a new w indow and loads the document specified
by a g iven URL
-.: var retval = window.open ('.:,!: ! , na~e , f eatures );
where,
url is string that specifies the URL of the d ocument t o d is play. If n o URL is specified , a new
window with about:blank is displayed. Example 2: Open a new window on button click.
" nam e is string that specifies the name of the window. . . <htm l>
feat ures is string that contains a list of ite_ms separated b y ..co mmas. Each nem cons1s~.s of an
option an d a value, separated by an e quals sign (for exam ple, fullscreen=yes, to olbar=yes ). <head >
Following features (styles can be used . <title > wind ow </ title >
Sr.No. Stvle Description I Values (on=1, off=Ol I <script >
A: status The status bar. sta tus - 1, status-0 funct i on OpenNewWiMow ()
too l bar The stan dard browser toolbar. I t oolbar-1, toolhar-0 I {
...2: I
3. l ocatio n Th e locat ion ent ry field . I location-1. location= O I
var winObj = win dow . open (" https : //www . google . com", "windowName ",
I m enubar-1. menubar-0
.,A. I men ubar The me nu bar. "to p=200, left=100 , width=250, height=100, status " ) ;
5. di rectories The standard b rowser directory directories =l, direct ories -0
J

buttons. JI
</s cr i pt >
6. r esiza ble Allow/ dis allow the w indow t o be I resizable=l, resizable=O
resized. </ head >
I
,::,. sc rollba rs Enable the scrollbars . i scrollb ars=l , s crollbars =O I <body >
•.-8. he i ght The hei ght of the wind ow in e ixe ls . hei ght=250 <form a ction="" method="post">
~ ,lid th The width of the wind ow in e ixels. width=250 1 <p>
Following exa mp les open a new window from the exi sting window us ing wind ow.openO method. In <input name =" Ope nWindow" value=" Open Window" type="b utton" onclick= "OpenNewWindow() " />
new wi nd ow the content of hello.html webpage wi ll be displayed. <I p >
The feature / dimensi ons(wid th , height ,top . left) of newly created window need to specify m openO </ form >
method of window. If features are not spec ified t h e browse r will display the co ntent of hello.h t m l in </body >
new tab rather th an crea ting a new wi ndow. </ html>
4 . 12 Coo ,es ana Br o w ~ c nerit 51de.-,S~c~rl ='""-====------
4. 13
f unct 1on ol..1r ()
Output:
, ~~
t ni s . val..Je = "Focu s Lost ";
GG..:.;o. -~ ~-- - -- -- · -0 X
</ scri pt >
</ body >

G
I.

Em Giving the New Window Focus C'. O(..:J .. - :, i l

/ The focus and blur events are u sed t o keep track of the elements the user focuses on . ~~~
1. Focus: Fires when a focusable element gains the focus.
2 . Blur: Fires when a focusable element loses the focus . Giving a Window Focus:
3 . focus in and focusout : Fire at the same time as focus and b lur, but bubble.
• In Exa mple 2 of Sec_tion 4 .2.1. two windows are displayed. The first window contain s a bu tton a nd
/ The blur e ve nt is fire d when an ele m ent has lost focus . The main d ifference between this event and your JavaScnpt sectwn. T~e second is a new window that the JavaScript opened. The second window
focus out is th at only the latter bubbles . The reason focus and blu r don 't bubble is that the events has focus unless and until the user selects a different window or JavaScript sets focus t o a n o h e r
mea n something qui te different on the window and on any other focusable element. wi ndow.
These t wo definiti ons should not be con fused . and therefore the events cannot be allowed to bubble You can give a new window focus by calling the focusQ method of the new w indow after the new
up to the docu m e nt. window opens. As shown next, the winObj variable receives a reference to the new window when
The following elements are focusable: window .openQ is called:
,.i-. Window: The focus is gained when the user brings the window forward , and lost when the user va r wi nOb J = wi ndow. open (" https :/ / www . google . com" , "wi na owName " ,
sends it back. "top=200, left=1 00, wiath=2 50, he ight =100, s t at us " );
2 . Links: Whethe r th e user uses a keyboard or a mouse. / We can use h e re the focusQ method of window object to set the newly created window as the active
element. ·
/ 3 . Form Fields: Whet her the user uses a keyboard or a mouse. ¥ win Ooj. focus ()
/ · Elements with Tabindex: Whether the user uses a keyboard or a mouse.
The focus method sets the element as the active element in the current documen t. Only one eleme n t
Giving a Form Element Focus : can be a ctive at a time in a document. The focus method not only sets an element as the active
Following example is us ing onfocusQ and onblurQ event handlers t o handle focus and blur events on element, but also tries to bring the application window into the foreground .
<in p ut> element respectively. Example: Giving focus to newly created window.
Example: <ht ml >
<htm l > <h ead >
<boely > <t i t le > window </ title >
<scrip t >
<inpu t type =· t ext' i d=' t xtl' /> fu ncti on Open Newwindow()
<inpu t typ e = ' text ' id= ' txt2 ' / > {
<sc r i pt> var winObj = window.open ( "https : / / www.google . com", "windowName " ,
var fiel dl = document. getElementByid( "txtl" ); "top=200, left=100 , width =250, he i ght =l 00 , st atu s" ) ;
winOoj.focus ();
fiel d l .onfocus = focu s; }
fieldl. onblur = blur; </script >
var field2 = document.getElementByid ( "t xt2"); </ heacJ >
f ield2 . onf ocu s = f ocus; <body >
field2. onblur = blur ; <f orm acti on="" met hod="post ">
<p>
fiel dl. fo c us ();
<input n;ime= "OpenWindow" value= "Open Window" type=" button" onc li ck="Open Ne>Mi ndow () " I>
function focus() <I p>
</ form >
this . value = " In Focu s "; </ body >
</ html>
Go 2. -

.. 3.
1111 Window Posi tion
,,r A new v. · den, always displayed on e scree~ at th e location which is specified by use r and loca
is spe · .ed by sertin2_ e left anj oo propernes of e new window as shown below:
;1 a r w· Ooje ctl = wi noow.ope ( " ,tp s ://www .google.co ", "w 1noow ame", 5.
6.
" top=200,lef =100 , wid h=250,heign, =100 , sta s");
/ user can make change in the fea tures or dimensions of window as pe r the requ irement but a new 7. too Retrieves
YI ·, dow is always created on top of the cu rrent window after the button is clicked.
rela . . th"- vern·caI o. f set of the top-left comer of the curren
· . e to the top-left comer of the rnai screen in pi.xl:ls
Example: Retrievin g vrindow properties. 8. ~ld~n Returns the hori zontal resolution of he dis play screen in ixe:S.
<h tml > Exampl e : Retn evmg screen properties
<heaa > <nead >
<script > <scr ip t t ype =" t ext / javas c ript ">
var myWin = wind ow. open ("", "MyWindow", "width =500, hei gnt =300,top =50,
fun ctio GetDime ns ion s () {
left=75 , s tat us =no"),
aoc umen t . ge tEleme ntByi d ( .. sc rLeft ") . innerHTML = screen. left;
myWin. docu ment .w rite ( "Screen widt h= " + myWi n . oute rWidth) ;
aoc ument. getElementByid (" scrTop"). inn e rHT ML = sc r ee n. t op;
myWin . document.write (" <br>Screen height= " + my~in.outerHeight );
myWin . document . writ e ( "cbr>Screen X =" T myWin . s cree nX) ; do c ument . get Element Byld ( "sc rW idt h") . innerHHIL = screen .1,;idth;
myWin.document.write ( "<br >Sc reen Y =" + myWin. s c reenY ) ; aoc umen t . ge tEleme ntBy l d (" scrHeight "). innerHT ML = screen. he i g t ;
myWin.document.write( "cbr>Window Name : " + myW i n . name ); documen t . get Eleme ntBy l d ( .. avai l left ") . inne rHTML = s cr een . avai l Left ;
myWin . stat us="status is o k " ao cume nt . get ElementB yl d ( "availT op"). inne rHTML = screen . availT oo ;
myWin . document.w rite ( " c br >Window stat us : " + myWin . status ) ; docume nt. get El emen tByld ( "av ailWi dth" ) . i nnerHTML = scree n . availlol idt ,
</ sc ri pt > aocument . ge tElementB yl o ( " availHeig ht " ) . innerHTML = scr ee n. a vai lHeight ;
</h ead > }
</ html> </ scr ipt >
Output: </ head >
<bod y onload=" GetDimensions () ; ">
<h3 >Di mensions of the screen :< / h3 >
Sae<n \\idl!!= SOO
ct.:) b".e.1eJ,t .::: lOO
Left : <label id="scr l eft "> </ label ><br / >
Sere.ea X =-~ Top : <labe l id="sc r Top" ></ label ><br />
Screen Y -
\\-ir. Name ~· \ l/ n' c!ol: • lolidth : <l abel id =" scrWidth" ></ label >< br / >
-11ldo sum · stat:J.S is ok Heig ht : <l abel 1d =" scrHeight"> </label> <br />

It is important to note that because of different screen resolution settings, positioning of new <h3 >Di mens i on s of the available area : </h3>
wind ow on screen may vary. For example. you specified upper left corner of window to appear at left : < l abel id=" avai Left "> </l abel ><br I>
To p : <la bel 1d="availTop" ></ la be l> <br / >
pixel 160 and your computer resolution is set as 640 pixels wide, then the left corner of the new
Width ; <label i d =" avai lWidt h "> </l a bel> <br / >
window a ppears about a quarter of the screen whereas if the resolution is set as 1024 pixels wide,
He ight : <la bel id= " ava ilHeight "> </ la be l >< br />
then the left corner of the new window appears about 15 percent of the screen. </ boay >
..-,:

,,., t
;.

,.,,

», 4~"'!.· ,.,,.,:-,~,. ,: , ,, ;:.: ........... -:: ~ .. .,,,. . :' ~: :,::;_;. n:- ..::. ~--...:.. ::~ .. ,,...... :,;:~.~.o;.-;-_:-g 1:../ ·m.-.-:,....r.; :- :::. .~
/'.,1.i:J ...... i!"4'!. '~ ~-· ~ "':/~...,~- . . . ":4:: .... 'Z
/ K r, ti~ 7 ht.,,!
·:t ~ Y "',,._,. . "/ :'.. ~: "./.'.: '.,f "fl.:_.-;,,,•_,, %fa,4:_.. " ' A ~ .. . ':'. "R): "; ,:,,'"',r .. ..... :..:::. .... ;~.;;".,·/~ •,., "'; '::: - ....··.,,:,.--;"' :....:;·.,...J.:":
;//!...•,,.,: -c,'l •'"',t-:~.-: '. ~ / ~ . .,_~ J ;;d~. ,,f!~
/ ,,.,. ;. ,;;77.-U .r. ~f "'/.: ·..... ~I :·~:..'ht--~ ::..;. f', .. 'll'F"'!

/ . .. ;( •"1;":'.': •:A ... -.;,,,:. .. . ' c:: ..... : . . : . . . •v . . .· •..;,- xr-:..._ ~--ff~ .r. -;, . / 2..:, ;,":,~.- .. 1<: ,~, .... '::":, ":./:.': ', .... ........ ': -,,.;_-; ..~,,
: ,;.: ... ~,,; ...~~~· ' "" ,;; ..... ~ Y..,;',,.... J. . . ~ ' "

J ,:, :.•~i~,· ",_;.,o/, ,f. t:":. "."~ J ~


'>• .:;• 'A'. /'.,"".,,._. '_,ff~ • '"' ~ / :.; • f''h, ", ;': '/::S4.,;<.::: ;/,;:'u.,. ........~ •,r, ;_-; ..,~
--;,,,~,,,, ~: ": : 1:"""l6"' 14: 1:, .... ~ ' l.. , ..,.. , • ,_ ;,
••: "':,'',K°' 'l:;..'.,.r~.-;~ •;.o;:4., ... : ·. :._,..h~ '/:.,.~n:....c; .·:v . . .-r:;" H:"i..:.T;:;;:;:-r"..." ,:..~~
,-

,;,;~::~f·::. ·~; ,,:_~rf:::.:;,~· :_


:: ~:::,;~:::~~-~-;,:;/.,;;;/:i :;;,~~·t;;/'/,;·.:~/:-i;:t;; 4 ,,,,.., ... ... ' ., " ·.,::,:.. , 'r~./ . .. ~...... ,. , ~:: , .

·,. ~ ' ' t:: i · .. 1:...-.;JI.,' 2:~ . .. :._,:- .. • '-'~


~-~" '.;i,~ / ~:-:I / /',,,,.p';.' '
• . ' ~ Jl'"i • • " ::..~ ~ ~~ . .. ~ .z ~ . .. ~ . _ ~ - :r

/ --, :.,. 17:. .. .. / ,,,f {:,._',.~1"!7".,, :: ,,,.,.,.!~ .:. ~~ f,N·'Il t'",


,,,,, .. ,:.,,,,-• , ,, .. - ,. , . ",'/i,t .... ,. , . ,d, . . ',, ' f , I ,, 1"'
,1,.,.,,. ... ·. , .·:.,;..~· ·:,.,
'.:,;- "•. ~/ "', , ""!:''Ill'" :., ,- .. ....,,.
.. "?,'4• .. , .. ~
/ . . . r ·~·· • ·-4• ~;,-,'" f ·~ • · .. ,.,~ 'A. v r-,..,.. ',"~~ .. • ;,. / •.:. ·.- ~ ·,:,
. v;,~ •,,..
_,,#- "A: "..1 ... •,•r.'"':'; VA 1", P: ';: ~ ,....
' /'l/, j ,
•_, • ',..,.r t' l! :'.,:.,~ , .,'"; ',14 /' • : -;. ·, // , .. . :,." -1~.r: ... :. • ~-'.;.. ':,,'

• ,.~ t •.,,... , </.: .. "/~~ ;. .•:.-., ·: ... ': l"J.Y '~.. ,. ,,...,:-n,~ ... ,,,,..,..,·.. ~, ~E.~·1:...·:•:r·,:"//.."'

,,. ' f ' , ,

, ~1
. ;,. .. ,
; • "/ , ; , · ~ · . ,.., .., , ~ .. fl , ... / .. · , ; · . , -~· · : . . ~/ , , f ( , , ~ .. 1--:~~
G
,,,. , . ,.,,,,: ,;..,.,,• ...ri..s.-· .. ,,., .. _.,,, ':.,,,,·· : ~ ••• ' ' / : ""/,,n "/~,,, ,,
l ,f' '+",,,."- "'/ ;""!,.J ;,••r::, · ' ;., .. _., ",:,"","," •,'' ',- ,, ,,, , ,; -'/ /C•

.. ', - ~- ..
''/A , • ..;_,,, ';." • •,. ,',/'~ . 1./4°1-1 ,
'lf•j , • , ; ,; ,, ,:",',.,,J,, ·"' 1, ' '1( .-,,,~•,, ' ' "',,,,..<I

tJ f. ; ·.-: ·, .. ,,, , .. •.,'",?~ .. J :.,'1 ,,


'"/ ;,,:,.., ,:,, ,_.~•,1:- , ,. ,.,,,•, I A :·~'l~"'1 1fr.t; I
. .. .

sing a Window f .,.::: ~r sc-·c ! .: .. , 1

( -:-.... : > 500 ;

< s -i p- >
<: ::e >-:r:~~ < ti :: E>
<s: ~:J: ~) Oe =· : eY~ :a, a; r _;: •> < 1,ea >
, ood Y>
b t non lie ="sere ,Or ()"> C ic,
-:e t scr-o ..
... i ..,1:jo .... . o~e .. i e".::: ea , , o:i tt n onc . 1c ="sc r 11 eq) ">Cl ic ~ r izont al ) ! </ butt,n >< br >< br>
e t o scr·)
< ' bOC > e ! ica 1 '<, cu : "', ><b,...><br >
: ::=:a2
<I t n - >
f,.,.rici:i or c:cse output:
~to~t
w1 ~dow. close r),
I~ e to saol Ve.~r
</ scno > I
</ e2c >
<ooay >
<:Jut O'l o c icK ="Ooe (); ">Open a .ew .. 1 oo,. </ but- o~>
<o I on nc 1c k=· c1 se f) ;. >Cl ose :1e Jr~e t ~ ncc~< 1J tton>
<i bod y >
Opening Multiple Windows at Once
<I l> A5 we have seen in "change the content 0 , windoi ecti (R f
· d b' • · s on e er to Seen n 4 2.4) ·t b ·ng
Output: s=e ' n ow o Ject we can change the content of eadi a e but there · - · . · ·
keep ch anges its con en n click. P g exist " smgle window wh1cn
Open a new window Close the / Creation of multi ole windows is possible by creatin
· · O : . . · g an d opening · · d ·
wm o v m a 1 p uslllg
WU1aow.o,,e. me , · The only t.lung need to take care is to pass p per dimensio for w in w S<O
a a 1 net,·ly created wi ndow will not appear one upon another.
In f llowrng exa m_ple, we are creating 5 windows and dimension of each window depe. d on the
iiiJ Scrolling a Web Page

(A JavaScript is used o scroll the web page auwm an cally by calling the scrollToO method. of the
Ve.~e of the I van ab e: The x vanable is ass ign ed to t p dimension of \~indow d y vanabie is
assigned to !ef di mens ion of window. Both x and y changes as i variable changes.

X
-:S;
v "ndov.' o Ject] or a li nk Jed directly o a re la ive link m he page
The scroll- oO method requires two arame ers. which are the x and y coordinates o" the top-left
corner of the vi ewable area of the web page har you wanr ro dis play Each parameter is an mt~ger
and represen s the coord inate in pixels.
? ample:
<ht
< Ea O>
<t :tle > winoo w </ t it le >
In fo llowing example we a re usmg two bun ons to scroll the window horizonrally and vemcally. One
<scr i pt t y~e ="t ext / j avas cr i pt ">
im portant thing to n ote here is in <style> tag first you have o s cify the width and height of th e
functi on show ()
screen then only the win dow.scroll method will show you the chan ge m the scroll pos inon either {
honzonrally or vertically as clicked by use r.
for ( i
J'Xample:
l>
var X= iTSe;
<h e O> var Y=1 T50 ;
< i le > i ndow </ title >
wi Obj = window . open ( ' ' , ' wi n ' + i , ' t op= ' +x+ ', left =' Ty+ ' , width=50 , ei g 0');
<S yle> }
b y { }
1d n. 5000px; </ scri p- >
hei ght. 5000px; </ head>
} <body>
<Is l e> <input name="m ltiple" val e="ShO'~ Mu ltiple Windows " t ype ="butt on " oncl ic k="s'K'w(
<scri p > </body>
</ht ml)
·V
4 20

Ou tput;

., -- . - ;... .... ~ ---- -


1 ,_,...................~

_J I ~-

',,,_ ::.

l!!J Cr eating a Webpag e in New Window


·1,y,~ ,:a:; ;,.a'lf: tJ 1r.':.:r, ~ r;-:,r.•tn• 1r.--:,;;, r """ ·11.r.'Y:r11 tr; .r ng the (1r ~ l..:tlill::i rr. ~ nc,,J /., J n·rr..
/ "'"'9 ,:ar.. .:..~ ·, rr. :~:~ lr.:.i""'': :n1: tj,:,~Jm':: r. ·11n?r: m~ fiC;{'f but n'::td fJ pass a-; a r.: nng, fen cJr.,:,«;.d ir,
~ir,g;t- vr 1':J ... t ..e ~·... './' a~i'.;;.,
?. :T11~; · rr;::;r :,::w;,,,; ~.,,:r. a ~;,<::ci;;J -:.:,rr,,z, ar·tJ na~ a ;;p!:Clal mi:anmg in ;;,;ni:;t1r,g -i.-,
1
11 ;::
·nr..er. ~-,~; J".I J ·1:; ; . " 'r" · r~-:: 7/ Tr:b-oi 1n:.d{: aV-1.. rn~r/· ·,1nt..F:!(J h~r. ;;rr:f'l:d': h~. . t with ;
~'== ;,
'2-:J.:...a:..:-.' J, ·, 1L, : ;-j :':.-.:: .. :-)': ":J:'Y11~; !~ ign':>re tn~ ;p~..a rnt:ar,Jng

.Ex.amp "

7'r.!r.1r.if , ar. '-".q>~e wm 1r


~hr:-.:;:,, .. th o: n-:,ant<:~ w:ie-eff
1~ rr ; : /~.1 ~)

,1., ~~: -~~:~-e· . . r ! · ~( ,r,~~, / By 1.l!i, ng J~·,ascnp •,oid(OJ. yo c.;;,n e 1mma btu •• .1·nil r~l!m n~ unddi.r.J:C. ;:,r.rr ;,• 1~ ·«. , l!
.?..a ner .. ,. ;:;r. fJaS:.1ne Q a~ a arg rn~r. o vm w~ can al:io 'lmt'! h~ jd'rasc:i i"' t -:.'".>C': a:. : ;,:,,;,'. :A~.-,
"- ·~~: -~~ =~··~,: .~· !· ~ ,~!:.~, h'! ... !rg C~· -~rPr / !it~, 1 ,
J:::1-:: ':."'' ... ~. ,,: Ql,Jr;( .,.,...ent. . !'./>1 J l"1ri~r ... - V.L• "' ': ~~" J
,11t 0
' ',';,
0
".: '.,.',.'":::- "'• ,lf'!,..t',, / '"~;;;,; , I,
~ ,· IT,I. r: .:;i:,l.ay a ·nr:lcr,m~ m. sage c, r,;, dr,a.;m <: n 1n;, '-J r'YH'k: ;,~ f,,..L·,n
l,1,_ ;-_:p.

I ,

.- 1 ... ".,.!;;,: :;,.... J. .. "::,. .. t11' - ... ::,. I , ~,, ,

"' ·>:..: ~:,.:. ·' "'': . ,ir.": ~' Cr':~...-•1~"'': '! ';...;• .... .., .... ': r" lr~·, ,-:,,....." :;r;;" • • t- / !. /., ,;

I., , ,
L_____
/ ' If e Java (rip r.ode in URL u, r. ;;ins rn u ip e , aterr.en tt hi:n i,ach 1't1U::r,1:r.t 1r,-::· .i~ - '*"_,..wj
by, mlwlor,:.{as :ho-n n oelow:
., .......... ::.: ,:: . . . ~ .. -~,... : -) ... ""' e;f • ., / r;,,1,; J ... ), j a , .::,:.cr .. r, t. ,c1r n0 11 ~ ne ;, D.;:ti:dJ , '",n1 , P 1e · t r<'" ': is · "/'"·l., • ... "t:M
., ... .,..,_,,:,; ,: .......... " ' : ,,,. ~ ~ ( , / t":"~ -' /, '/ ou •11111 ; i,i; the fo Jowm g c,,; pu on ;our brows-er
J;
111 1 '',.",,,. , ,.. ,. . : '
!The time i:

,v. . ~, . .
-' 1".;..1~ ': J-;~.,,-~J .. ": "," • ~" ': , ,._ _.. ,"' ( ~,/. j,.,'!~n f J• I~
~ "'"" "'"""""...,,. ,...,...,, 'I
" w • ha ve open ed n , wi ndow m javascni:, code ~1m11;,r'J we can apt:i a ..e-.
... ~-..,,,.,," . ' .
· ~
, / ",/ /. j ,
U ll To open a new window ,mth some v1Eb contents,
, I .,_ .,
java: crl p :void wi no o .. . open( "h ~ -// ,M11 . goog l f:.co-.i " I
.,.•
,'i c11en1SldeScn ti n _L~ uo~ - --

Th is will open a new win dow as follows : 7 A Ja vaScrip t prog ra m can close~ b ---- - Coo .,. •no s,ow_ Do.a
close other w111dows wnhout rowser windows th . --- -- - - -
c Ii .,,~ "'"W"" 9C09if ~ 'Q
avaScript cannot read Wh user confi rrnation ' a, 1t opened itself. but 1t 1s not allow d to
• "'-'O"· ·~~ D ..... ·~ ... · ._ r , 8 J ar loca r1o
object. a lt hough It can tell ·h b ns a User has visi
browser hi story It cannot ' e rowser to Jump back ted' by reading them fr om the loutlon
0
. Script cannot a see what other Web pa r for;,,.ard any number of steps through the
9 Ja, a ccess the cook i ges t11e user has open
10 tt cannot see when the user inrera;s or variables from other sites .
ann ot open wind ts Wah or her prog
11 It c ows ou r of sight f . rams. or other pans of the browse· window
browse rs. It ca nn ot close Windows th rom tne user or too small for th e use r to see a~d In mo<'
at It did not O • - '
Different browsers have different s pen
ecunty policies a d
s ome browsers may also allow restr ct n may implement diffe rent AP! rest n cn ons
More comm on ly, a JavaScript UR L will co ntain Java Script sta tem ent s that perfor m acuons but preferen ces. . I !Ons to be streng the ned or weakened through user
return no value. For exampl e: client side JavaScript Security Issues:
javas cript · alert ( "Hello world !") JavaS crip t vu ln erabi lities can be both client-side
When this sort of URL is "loaded ," t he browser executes the JavaScrip t code, bur. because the re 15 no to stea l se rve r side data and infect the . problem s and server si de as well as ha ckers are a ble
val ue ro disp lay as the new doc ument, it does not modify the currently d isplayed document. users With malware
Hacke rs ca n pote ntia lly harm your busi ness b . :
CfJi••JavaScript Security hrea ts n eed to be eva luated and dealt . h Y taking various paths through your applicati on Thes e
t . . . Wit . one way or the oth er
/ JavaScrip t has its own security model , bu t this is not designed to protect th e Web site owner or the DOM Based Cross Site Scnptmg Vulnerability:
data passed betwee n the browse r a nd th e server DOM Based XSS sim ply means a Cross-site scnpnng vulnerab ility that appea rs 1n the DOM
• Q-h e security model is designed ro protect the use r from ma licious Web sires, a n d as a result, it (Document Object Model) instead of part of the HTML.
enforces strict limits on wha t the page author is allowed to do . DOM Based Cross Site Scripting Attack Example:
/ They may ha ve control over thelf own page inside the browser, but that is where their ab ilities end. Imagine the following page hrtp:t t www.example.com / test.html contains the below code:
/ As in many fields, Ja va Script secunty has evolved through an in teractive and ongoing process of , scri pt >
exploits and patches . document . wri te ( "< b>Curr ent URL </ b> " • document . baseUR I ! ;
/ In th e early days of the Web. browsers added features like th e a bility to open, m ove, and resize </ sc ri pt >
windows and to script the browser's status line .
If you send an HTTP request like this http:t/www.example.com / test .htmlii <scri pt>alert(l)<lscrip >.
~ When un ethica l advert isers and scam m ers started abusing these features , browser makers had to sim ple en oug h your Java Script code will get executed, because the page is wnting whatever you
restric or d isable those APls. typed in ,n-
URL to th e page with document.write fu nction.
Today, rn the process of standardizing HTMLS , browser vendors are carefully (an d openly and If you look a t t he sou rce of the page, you won't see <script>alert(lj </scnpt> because its all
collaboratively) lifting certa in long -stand ing security restri ctions and adding quite a bit of power to happem ng in the DO M and done by the executed JavaScript code.
client-side Java Scr ipt whi le (hopefu lly) n or introducing any new security h oles.
After the m alicious code 1s executed by page. you can simply exploit this DOM based cross- si te
The followi ng are some restricted features :
scriptm g vulnerability ro steal the cookies of the user or change the page's behaviou r as you li ke
1. A JavaScript progra m can open new browser wi ndows, bu t, to prevent pop-up abuse by
Fixing DO M Cross -s ite Scripting Vulnerabilities:
advertisers , m ost browsers restrict thi s feature so tha t it can happen on ly in respon se to a user-
in iriated event, s uch as a mouse click. The best way to fix DOM based cross- site scripting 1s to use the right out put me thod (sink) For
2. Th e value prop erty of HTML File Upload elements cannot be set. If thi s property could be set. a examp le if you want to use user input to write in a <d tv> element don't use inner Ht ml. instead use
scr ipt could set it t o a ny desi red filen a me a nd cause the fonn ro upload the contents of any innerText/rextContenr. This will solve the problem . an d it is the right way to remed1are DO M based
specifi ed fie (such as a password file) to th e server. XSS vulne rbilities.
3. A script cannot rea d th e cont ent of documents loaded from d ifferen t servers tha n the docume nt Fi nally, to fix the p roblem in ou r initial code, we would sim ply use element textContent to wnte ll in
tha t conta ins the script. Si milarly, a script ca nn o t regis ter event listeners on docu ments from a content li ke th is :
different servers. This prevents s cripts from snooping on rh e user's input (su ch as t he keys trokes
<b>Cu r r e nt URL:</ b> cspan i a=" cont entho oer "> </ span >
th a t constitute a password entry) to other pages. Th is restriction is known as the sa me -ong in
policy. <scr i pt >
4. Ja va Scri pts ca nnot read or wri te files o n us ers ' compu ters . though they can cause th e browser to doc ume nt .get El emen tByi d( "content holder ") .te xtC ontent documen: .bas e0RI;
load remote pag es a n d resources like scripts or images, wh ich th e browser m ay choose to cache </ s cr i pt>
locally. They ca nn ot create fi les on the server (except by commu m cating with a server si de script It does the same thing but th is time it 1s not vuln erable to DOM base cross-site scn ptm g
tha t creates files for th em) . The only thing they can store on the user's co mp ut er are cookies ·
VUinerabilities
5. They are all owed t o interact w 'th other pages in a frameset, 1f those fra mes or iginate from the
same Web site, bu t nor if they origin ate from an other Web site . Some browsers will even treat ll!Drimers
different p ort n umbers on the same server a s a d ifferent Web site. ;r Window obje cts provid es different timer fu nmo ns which all ow you to register a functw n t::i ,e
6. Java Scrip t cannot be used to se the value a ttrib ute of a file input, and will nor be all owed to use invoked o nce or repea tedly after a specified amount o f time has elapsed.
them to up load files with o ut per mi ss io n .
cn•nt Side Serl tin Lan ua e
4.24 Cookies and Brow .. ~
Cl ient Side ScnpUng Lo guage . 4.25
~ample 2: Rota t m g Images using setrim Cook11s anc1 e,ow- Data
,,.I With JavaScript. it is possible to execute some code at specified t ime-intervals. Thi s 1s called timing . g setTimeoutO method images ·u eouto method F ll .
l)stn WJ be r · o ow1ng e · .
<ht ml > otated after 1 sec. xamp 1e is using an array of images
events .
.> var id = setTimeout f unc ti on, de l a ; Initiates a single time r wh ich will call the specified <nead >
function after the delay . The funcu n returns a u nique ID with which the timer can be canceled <sc ri pt>
a a later um e. var i 1 1mgs, pie ;
/ · ar 10 = secincen al (f unc n on, del ay ); Sim ilar to setTimeout Q method but continually calls fun cti on init ()
the fum:tion (with a de ay every tim e) un til it is ca nceled. It starts a timer that penodicaU
repeats the execunon of the specified ~ ress1on. Th is m ethod is useful if you want to execute a~
action aga.m and again. f r exa mple m case f ammauons. If a n action needs to be executed only pie = document . get El ementBy!o ( .
"pie " )
img s = [ "q uery . png " .. •
once and afters me delay. use t he setTl meout m ethod. ' warn . png" ' "st op . png"
/!. cle arI t~r a 1 10 );, c !ear i meout ( 1 ) ; Accepts a nmer ID (returned by enher of the 1
= 0 ; , "i nfo . png" ] ,

a f re.mentioned fan 10ns) and st ps the tim er callback from occurring. rota t e ( );
/ By usmg set ·meou r.ieth of w111dow object we can rotate images. The setTi m eoutQ me thod calls a
:unctl . r e\'a.lua tes an express1 n a ft er a specifi ed num ber of milliseconds. funct i on rota te ( )
Example 1; Wri ng . umber a fc e r a dela y usmg se .ntervalQ method. In this exam ple we writing
:1· :;€..."""S n a u.-i:c....-,e~ ~:t-er a speci fi ed .nterna pic . src = imgs[ i J ;
I <r : -: > ( i == ( imgs . le ngth . 1 ) ) , i =0 : i++
>E se tT imeout ( rotate , 1000 )

oo cument . aa a Event Li stener ( "DOMcontent Loaded "


</ script> , i nit , fa lse ) ;

</ hea d >


<Dody >
=== -.1: 1p e reg1st ra ion <img i a ="pic" wiath= "120 " height= "120" src="Javascri pt . jpg">
= s e:: , : e-. 2: 1"01s:i :ay ,. , 500 ), </ boay >
</ ht ml>
Output:
•_ · : ::~~ .: sola , 1: ."
;: ii
Ar•..,.._,

: p t ") .i ne"n L nu oer ,

K ?sing ti m ing events we are moving an image (car.jpg) from left to right. And operation is controlled
oy two b unons i. e. start and stop button.
< s .. i:r: > • Here, we are using position and left property of style object to move the element.
< 1 ~2ac > Example 3: Moving a car using setTimeoutQand clear TimeoutO methods.
<:>oc y> < ·ml>
<o o c ie< ="-,ag1c ();"> CllcK r.e '</ o tto > <head>
<t itle >Anim ation </ title >
<: e a ea 1: =· :>..:: ;tlft .></ t extar ea >
<script t ype ="text / javascript ">
</ ,:; y> va r obj = null ;
<I - var animate ;
Outp t.: function i ni t ()
{
012345678910111213141 ob j = document.get ElementBy! d(' car ');
5 obj. style . position= ' relat ive ';
ob j . style . left = · epx ';
-_-._-.. :._ _-· ~~-

.o"- - ~ = ~- - - _!'.. - --..:-

...... -_-::::i. - _.:3.:: -: - • - -

-::=.:-

_---.;:- --= -
=-
~= =~
- - -~ - -::=- ~= -=-=-=
-- ~ : ..

- .. - =:- :
--:.,... :_:- - ,~

:.: :.~-: ... : :.:: :· -cs:


- ::-: =-:.:.._.,- : • __:<\.:.,
:: :.i-::,.:""' "C::l-:
.. -:::-=-
: : : .....-~- : .- : : .:-"
_:_·.:...:- _:-

_€' · ~ - - .:.- ~ - - -

/ - ! ,... _ -- :T' i;.,-- - ·- -- - "' --...::::c=::::...:,:.. - - :::: ~-~ - --:. -


/ ~ =L::>-: r ::-::-~ 7 -:: : v ---:._-y _ ,::._ ~ ::::- ..::r~:.. :: ~ --=~· :..:,:: --- - ~ !::CC

;r : . : .=-.ex :r.i - - .:: ::;.:-- :;,: = ·::.:..: :,y i;,:-


!.1=7~
4.28
Client Side Scri pting Language
. . . . lso use met hods of History object which are s.h011.'t

---
• In addit ion to properties of History obJect we can a .
below: Descriotion
Sr. No. Methods Loads the previou s URL in the h istorv list.
1. bac k () Loads the next URL in the h is torv list .
2.
3.
for1~a rd ()
go ()
Loads a specific URL fro m the historv list .
-
Example:
html >
<body>
<sc ript
doc ument .1vrite ( "a href=' he ll o. html '> Page 1</ a > I ");
doc ume nt. ,vrite ( "<a hr ef= 'we l come . html '> Pa ge 2</ a > I");
document . 1vr i t e ( "<bl'>Hi st ory Lengt h : " + hi story. lengt h ) ;
doc ument . write ("< br >C ur re nt Loc ation : " + l oc ation . pathn ame + "< br >") ;
docume nt. 1vl'i te (" <butt on oncl i ck= ' hi story . back () ' >Ba ek</ button> ")
doc ument . 1vr ite ( " but ton oncl i ck= · hi story . forw a r d ()· >Forwa rd </ bu ton >" ) ;
</ s cript >
</ body>
</ ht ml >
Create hello.html and welcome.html page on same location with som e con t e n ts .

Here. we have created two hyperlinks name as page1 a n d page2. W h en u ser will click on that fut
• corresponding page will be opened. w e have also created two b uttons names as Back and Foniard
When user click on Back button, history. ba ckQ m et h od will takes place and when click on Fon•r<L--:
button, history forwardO meth od will be called.
Save the HTML document and open the page in your browser to see the followi n g output :

- tJ
~ localhost:8000 "

c localho>t

~ 1Pag(:!
Histcm· Lt'tigth. J
Cunt'tlt Location dl'Illo samplt' b!IUI
I B_:i~k_. L ".:_or~

1. What is cookie?
2. How to create cookie in JavaScript? Explai n w ith example
3. What is browser? ·
4. H~w to reading a cookie value and writing a cookie value ? Explain with 1
5. With the help of example describe deleting a cookies examp e.
6. Explain block diagram of browser. ·
/J. Describe the ~erm JavaScript security in detail.
8. How t.o creatmg a web page in new window ?
_,,9. Explam the term timers in detail
,...A:{). Expla~n the te~m browser location and h istory in detail
11. Describe workmg of cookies with exam 1 .
12. How to scrolling a web p a ge? Expla · ?the.
1.q E 1· · m WI example
,,,,.._, . xp am the term JavaScr ipt URL in detail. ·
14. . wit
How t o r ead and delete query in JavaScript'?· Exp 1a m . h example .
I •••
... . -
\/

5...
Regular Expression
Rollover and Frame~
§pter Outcomes .. .
I Co m pose , e l va nt 1eg ular ex p r e s.<, ion for th · h
. . e give n c a , aoer p a tt e111 sea rc h.
'il Develop Java c , 1pt to impl e ment va lidati on s using the . .
given reg u 1a r expression.
I' Crea te fr a m es based on th e g ive n proble m .
@ Create wmd ow o bjec t a s per th e g iven prob le m .
fil Develop JavaSc , 1pt for c r e at ing roll over e ffec t fo , th e given
· · · n.
s1tuat1o

[earning Objectives ...


'il To learn Reg ul a r Exp r ess ion in JavaScript
I' To s tud y Roll O ve r in JavaScript
~ To und e r s t a nd Frames a nd its Basic Con ce pts

II INTRODUCTION
• In JavaScript, regular expressions are also objects. A regular expression is a sequence of characters
that forms a search pattern . The search pattern can be used for text search and text replace
operations.
• Rollover is a JavaScript technique used by Web developers to produce an effect in which the
appearance of a graphical image changes when the user rolls the mouse pointer over it.
• Rollover also refers to a button on a Web page that allows interactivity between the user and the Web
?age. It causes the button to react by e ither replacing the source image at the button with another
lrriage or redirecti ng it to a different Web page.
' Frames are used to divide the browser window into multiple sections/regions where each section can
load or represent a separate HTML document. ln short, frames enable you present multiple HTML
documents within the same window.

IJI REGULAR EXPRESSION


• A regular expression is a pattern of characters. JavaScript regular expression are objects. When you
• create a regular expression, you test the regular expression against a string.
Regular expression is a series of characters between two forward slashes(/ ..... /) .
• : 0 r example, tbe regular expression / green/ might be matched against the string, "The green grass"
~een is contained in the string, then there is a successful match .
~ Language of Regular Expressions .
regular expression is an object that describes a pattern of characters. A regular express10n (also
called regex) is a way t o work with strings, ma
· very e ff.1c1ent
· way.
[5.11
t JC you can:
Client Si de Serl tin Lan ua e . . th a special syn a '
2.
lar expression W1
By formulating a regu . ndFramu

1. Search text in~ string. ·n . .


2 Replace subsmngs ma stn ~ring. R gExp objects. A regular expression is a
3. Extract information from~ s e represented by e onstructor or written as a literal Valutype
. . lar expressions ar .th the RegExp c e by \t
ln Javascnpt , regu ·ther constn1cted W1 ters.
of object. lt can be e1 forward slash (/} charac . constructor \d
enclosing a pattern m "aoc") ; II us i ng \D
var rel = new RegE xp(
\W

OR // u
s ing 11.te ra l
essions. There are small differences betw ,w
r re2 = I abc 1, t regular ex:pr h een \S
va l nguage implemen s ly almost everywhere. T e 1anguage of Regu1•.
Every P rogramming a 1 ncepts app l4f \S
. but the genera co d Character classes.
each implementanon. . Meta characters, an \
. n consist of Quant1f1ers.
~~ . .
n, tifiers: . .th ·n a pattern how many times a particular charac:t \ matches a backslash.
1. ....uan . l way t o specify w1 I er s
Quantifiers provide _a s1mp ed peat itself.
or set of characters is allowe to re
There are three non-explicit quannfiers: ..
(i} • which describes "O or more occurrences ,
..} +, which describes "1 or more occurrences" and
(II ' "
•• "} 7 which describes "O or 1 occurrence . . . .
( 111
•• h tt immediately preceding (to the left of) the quant1f1er, which is
Quantifiers always refer tot elpa pe:~entheses are used to create a pattern group. abcS in else
normally a smgle character un ess abc, 123abc, an strin endin with abc
tt ms and inputs they would match : abc 2 ,3 abcabc, abcabcabc
• Beloware some samp1e pa e
Inputs (Matches) 1.3 123, lz3, 133
Pattern 1.· 3 13, 123, 1zdfl( 3
fo• f, fo, fg , foo , fog , food
\ d \d 01, 02, 99, ..
go' gle ggle, gogle, google
\ w+ @ w+ email@com an .com, a@a
fo+ fo , foo , fog, food (not t) 3. Character Classes:
go+gle gogle, google (not ggle) • You can group characters by putting them between square brackets. This way any character in the
fo7 f, fo, foo , food class W1 ll mate h one character in the input. '

colou?r color, colour(not colouur)


r [abcl Match anv of a , band c.
Explicit quantifiers are positioned following the pattern they apply to, just like regular quantifiers.
I [a-z) Match any character between a and z. (ASCII order}
Explicit quantifiers use curly braces {} and number values for upper and lower occurrence limits \ [" abc] A caret " at the beginning indicates "not". In this case. match anything other than a, b or c.
within the braces
Explicit Q.uantifiers
I
I
[+·? .] Most special characters have no meaning inside the square brackets. This expression
Meaning matches any of .+, · . ? or the dot.
{n} Repeat n times • Here, are so me sample uses
{n ,m }
Repeat at least n , but no more than m times Pattern Inputs tMatcha) .: rr
{n,} ~ \·.·, ·;
Repeat at least n times Matches the contents of a C-style comment I" ... • I
For examdple, hx{S} would match exactly five x characters (XXXXX) When only one number is specified. J" ab] Match for other than a,b (C,d,z)
It 1s use as t e upper bou d l · · · ch ny
number of x characters ;e;:re~~ it is followed by a comma, such as x{S,} , whic~ would mat :uld ._'.'(\d{S}) l(\d{S}- \ d{ 4 }$ s numeric digits or 5 digits-dash-4 digits. (JCXJCXJC}l ( =·xxxx}
match. an 5· Below are some sample patterns and mputs they w
~ \ d \ d-[A· Z][a· z][a-z]-\d\d$ Match for a date format (2002-Nov-14}
Pattern ~ d{3} ~ Validate a seven-digit phone number (xxx-x:xxx}
ab{2}c
Inputs (Matches)
abbc, aaabbccc ~ \ w{S ,6)\b I Find all five and six letter words
ab{.2}c J Find ten digit phone numbers ( xxx xxx-xxxx)
ac, abc, abbc, aabbcc ' \ b \ d {3}\ s\d {3)-\ d{4}
ab{2 ,3}c \ A simple IP address finder 132.128.10.10
abbc,abbbc, aabbcc , aabbbcc (\ d{l ,3 }\ .){3 }\ d{l ,3}
R ular Ex ress lon Roll ov er • M Frarn,i CJJen $1d9 Sen un Lan WI •
5.4
function c ec:,. r
Regtxp Flags: . 1 1
. . ca also specify add rional flags to contr l h a,.. regc.. .< .~
en crea g a new regular expression obJect, you . o ow • : l <OC /
th pa em wi be used when ma ch·ng a gains other stnngs. . . ar s r=doc u ,
T e gs are e1 ' er appended a er the regular expression in the litera n otan on . or passed in o t e ar r Ps . ·€~tE
• - regex.
cons ctor in th e normal notation. Regular expressions m ay have flags that affeet the search . ooc J ent . ge E e
There are only 5 of them in JavaScript:
1: With his fla g th e search is case -i nsensi ·ve: no differen ce between A a n d a . '/ Ser p >
g. With this flag the search looks for all matches. without it - only the first one. En e tex :< "np t
YP€= " •r ·
m: M tili ne mode (is necessa ry if your inpu strin g has newline charact':rs \\ n), thts flag allows the <1nput ype= "button· - , i,: · t~: · I ,
start and end metachara cter (h and S respectively) to match at the begmnmg a n d end of each lin d .. one icl:= "c
<p l = OEmO " ><f p> ~C<{) " Vo'. ~, "( h • r ••
instead of at the beginning and end of the whole input string). e </ body > · ·' >
s. "Dotall" mode , allows t o m atch newlines. </ ht mi >
u: Enables full unicode support. The flag enables correct processing of surrogate p airs.
output:
y· S icky mod e.
Example:
II Fi ne a ll a cnes ( global at chi g) and si ng case insensiti ve matchin g Emer ~ ~-- -- -
ar r e = / r egul ar expre ssion/ gi ; \: ' a ------- --..:._
If Co st r ctor not ation of t e same r eg lar expression obj ec t wit n t he two fl a gs
ar r e = ne-., Reg Exp (" regu ar expr ession", "gi ");
str.search Q Met hod:
Methods used in Regular Expressions:
There are two sets of methods to deal with regular expressions: str .searchQ m ethod t akes a regular exp .
L RegExp class a nd its methods (test Q and execO).
2. Strin g class and its methods (matchQ. search Q. rep aceO).
regular expression in th e tri
Example:
. ress1on/pattem as argum
s ng. This method return the index whe;;~~!. sf~:! for the speafied

Sr. No. j Purpose \ Flag ' Method Description <ht ml >


<h eaa >
L To search for a g str. matc h( reg ) Get a fla t array of m atches.
m atch es: .----=--------:-'-:-:-::..c..______.:...:.:....:.=.:....:.:..:.:'.!..:.~:.::.::::'..'..'.::.... <title > re gex </ title >
g str .matchAll ( reg ) Get an arra y or m atches
with det a ils. <sc ript >

2. f net i on cnec k( ) {
To search for the fi rst str .matc h(r eg) Get the full first m atch.
match only: var r ege x = / abc t gmi;
str . search ( reg) Get t h e string position of
va r st r=aocument . getE lementByla ( "t xt .) val ue;
th e fi rst m atch .
var res = str . sea rch (regex);
re gexp . tes t ( st r ). I Check if there's a match . ooc men t · get Eleme nt Byl d( "oemol · ) . innerHT"IL = r es ;

I regexp. exec ( st r) ( s et rege Fin d the match fr om the I </ scrip t >
xp. la st lndex t o posi t ion) given posit ion. </ he aa>
3. To repla ce all m atches: st r. re pla ce ( r eg , str \ fu nc ) Replace with another I <bo dy >
string or a funct ion result. Enter text : <te xta r ea id ="t xt " >< / textarea >
RegExp.testQ Method: <i np ut t ype ="butto n" oncl i ck="cnec k()" value="Chec k">
RegExp.t es tQ method t akes a strin g a rgume nt and . . <p id="demol "> </ p>
s rin g con a ins a mat ch of the n . h .t will return a Boolean telling you whether the
p a em m t e expression. </ bod y >
</ ht ml>
Example:
<ntml>
Output:
<nead >
<title > r egex </ t i tl e >
En te:r tcict · a_ab_ili !ll£g }
__ _ _ _ _.a.al
</ head >
<body>
s
<sc rip t >
57
cueot Sld scr !1£!.'
tl~nlL!:L~a~n~u~a="-e- ~ ~ ~ ~ ~ ~ ~ ~ ~~ ~~ ~ ~ ~ ~ ~-B~~~~~~~~~
A ular Ex reaslon Rollover:.!!!~:!!'~!
9
· •nd Fram••

output: ja ab i l l ms! ~ !
. 1
client Side sen '"
Lan ua e
n as argument a
nd searches a string for a
bJ·ect. The str. matchO Enter tcXf: lS~~
ssion/paner as an Array o
str.matchO Method: thod takes a regular e~;:urns the matches . abe,abc,abc
• The str.searchO me lar expression. and the g f]ag . the firs t match string.
match against a reg\ havior correspond to . n then it returns fall matches fo und.
method h as different _e d ir the regular express1~t returns the array o - Finding Non Matching Characters
If g flag is not s_pec1r:~ re~ular expression then
~ Jf g flag is spec.1f_1_
e_d_ _ for example yo_u want _to ~nd a special character(/, ·, ., *)in the text as all these special character
Exa:nple: Match without g flag. • having a specifi~ meanmg m regu_lar express so to find all these speci.tl character you have to escape
its special meamng _so that they will be treated as normal content.
<Mml > consider the followmg regular expression:
<nea::i-cle > regex </ dt l e > var rege x = / [ -] /
<sc ript > var res =regex.test( 0 123·456");
f nci:ion cneck ( ) { .
u var rege x = / abc /; ementByia ( "t xt").va l ue, Whenever, we pass a_ string in R_e gExp.test method then browser look for the specified
var str=document.getEl ). +" "+ res . ind ex ; attern(r egu lar express10n) m the strmg. If browser didn't find the pattern in the string then the
var r es = str .matc h( rege~ ' mol ") . in nerHTML = res[0]
oocument . getE lementByio ( de ~rowser responds with a false • and if the pattern appears then the browser would respond with a
true. .
Above regular expression is looking for occurrence of hypen in string so you will get true value in res
</ script >
variable. However, by placing a caret in the regular expression, as shown next,
</ head >
,booy > var rege x = / [ "\ -]/
Ente r t:e xt: <tex:i:a re a ia="txt" ></ text ~r ea > -"Check" >
var re s=regex . test ( "123·456");
oncl ic k="check () value -
<input t ype="button"
The caret sign [" ) at the beginning in square bracket indicates "not". The browser responds with a
<P id="aemol" ></ P>
true if the "." is not found in the text. This is because you are telling the browser to determ ine
</ body>
whether the pattern does not appear in the text.
</ html >
Out put: Example:
a ab l l i ~ <html >
Ent~ text:L.- - - - - - - - 4', \ Chee\< j <head >
<tit le> re gex </ title >
abc 5 <scri pt >
funct i o n check() {
~ Example: Match with g flag. v ar re gex= / [ "\ •]/;
c/\ . <html > var res= regex . test(document . getElementBy!d("txt") .v alue );
\
0
<head > document . getElementByld ( "demol"). innerHTML = res ;
,:- l <titl e> r ege x </ titl e>
<script >
</sc ript >
function chec k() {
var rege x = I abc / g; </head >
var str =c ocument. get Eleme ntByio ( "txt" ). val ue ; <body >
var res = str.match ( regex ); Enter text : <textarea id="txt" ></ textarea >
document. getElementB yi a ( "aemol "). innerHTML = re s <i n put t ype ="button" one lic k=" check ()" value="Check" >
<p id="demol" ></ p >
</ sc ript> </ boay >
</ he ad > </ html>
<body> Output:
Ent e r text: <texta r ea id="txt" >< / tex tarea >
<i nput type=" butto n" oncli ck ="check () " va lue= "Check" > r.. b I
<p id= "aem ol "></p> Entcrtc,ct:l ----- - - - - =' [Cbadt ]
</ body >
</ html>
·descrrtl~~~"-"'==<=----~
c11en1 s, 5.9
re ssi on . Ro ll over and Frames . checking for any two consecuf . . - - - - - - . !R~u~l~arc_!E~x~,e~s~si~on~R~o~l~lo~v:!er~an~d!_F:Fra~m~e!.!.s
£l".a.J11P1e . ive d1g1t in input.
<ntrn l >
<nead >
. of characte rs . b. c. d. e in the text . f or m atch ing any o f these <title > regex </ title >
1l!!Pl!I Entering a Range hara cters like a . <scr ipt >
·~ . , oraU of the c
• You can also matcn an, reoular exp ress ion : . f u nction c hec k ( ) {
. racter use follovnng " ca n men non as foll ows:
cn a . en es then you v a r r ege x= / \ d \ d/ ;
. [ abcde l . er ou want to find are ins
Alternatively 1f cnaract Y t rs in a ra n ge of charact ers usin g t he v ar res = regex . test ( aoc ument
,r a-e] / ot to match anY charac_e f ront o f the fi rst charact er, as shown document getEl .getElementByld (" txt") 1 ).
· ll the browser n the caret in · ementByid ("' demoi " . . va ue ,
1 ) . inne r HTML = res;
Likewise. you can te ression . except you p ace
same kind of regu lar exp
</ sc ript >
here h haracters ·a · t hrough 'e ' were found .
[' a-e l Id return true if none oft e c </ head >
In this case. the browser wou <body >
Example: En t er te xt : <textarea id="txt " ></text area ,
<n t ml > <i npu t type="button" one 1 ic
· k=" chec k() " value="Check" >
<neac1> <P id="demol" ></p >
<title > reg ex </ title >
</ body >
<script >
func tion cneck () { </ html >
var regex = I [A abc] /; output:
var str=document. ge tEl ement Byl d ( "txt" ). val ue;
var res = r ege x. test ( str ); 13456asd I
document get ElementB yi d( "d emol" ) . inne rHTML = res; 4 \ Cbedt
Enter tcxt: . ~ - -- - -- -..m I
</ scr ipt >
</ head >
<body> Follow ir:g (2.ble shows the test cases on above code iffollo · · t l ·
Ent er text ·< te xta rea 1o="txt" ></ te xtarea > then co r responding output will be generated. . wmg mpu va ues are specified a t run t i me
<inpu t type="button" onclick="check() " value= "C heck">
Pattern Code Input Output
<p 1a="cemo l ">< / p> I
/\ d \ d / v ar regex= I \ d d / ; \I D34 I Tru e \
</ OoOy>
v ar Output : rege x. test ( Input ); I D3 I False
</h t ml >
Output:
lili_________ .....,
~
I
I
34
34d
I

I I
True
True
l
I
I Enter tcx:t:._ _ _____/,: Clte'c I I Entc:i- tc:r.r: II 3 I False l
raise true
I A1b2 I False I
/\ d{4} v ar regex= / \d{4}; I a1b2c3d \ False
va r Output= regex.test(Input); II a1b2c3d4 I False
, Matching Digits and Nondigits
If you want to work on di gits rather tha t I a1b2c3d4567 \ True
\d and \ D.

ar least one digit a poears in the


n ext, then in your regular expression you can make use of

The \ d symbol tells he browser to find h h


wh _et er the text contains d ig ' t s . The brows er returns a u ue if
Bil Matching Punctuation and Symbols
• The
an \w special
. symbol tells the browser to determine whether the text contai ns a letter, number, or
f . text. T is regular ex . .
irsr name has any digi ts . p ress1on 1s generally used to check whether a \ Underscore , ". It always matches the ASCII characters (A-Za-z0-9j .
The \D sym bol is u s ed t o tell he bro wser to search for w stands for "word character.
. . . d]
Th browser re t urns a rue i a nond · . . any n ond1g1t m th e t ext.This is similar to [A\ · \ W sp
cont ·
. ecial symbol reverses this request by telling the browser to determine whether th e t ext
whether a teleph o ne numbe r has 1g1t is found. This r egular expres si o n is generally used to cheC~ [" q ains a character other than a letter. number , or underscore . Using \Wis equivalent t o using
any non d1gns .
-z A.-2 0-9_] .
s tdo Serl ti n Lan ua o
cuen•
5.10 R ular Ex reaslon, Rollover and F~
output=- -- . - - - -~~~~~-
Client Side Serl tlng_!,.aa,n~u~a ~e,__ _ _ __
1~ t ts-aU.co.1n l
Example 1: Enter teJtl . - - - -4! ~
<html >
<hea : ~1tle > regex </ tit:le >
<s cript >
functi on che ck ()
{
.. ") 1 e) ·
dD Matching Words
var regex= /\ w{i} /; t getElemen tByld( -ext · va u ' you m ight want the browser to search t: .
var res= regex.test ( doc~men o~ " ). innerHTML = re s ; d that · · h or a particular d
word b oun ary -. is. t e space between two wo wor within the text . A word is defined b a
documen(. get El ementByid ( aem
expressio n by usmg _the \b special symbol. rds. You define a word boundary within a reg uiar
Think of th e b special symbol as a spac b
</ scr i pt > · ·r
in a r egular expression I you want the br
e etween two w d
or s. You need to use two \b special b Is
· · f th d owser to search fo sym o
, / head > at the begmnmg O e wor and the second repres r a word: the first \b represents the space
<oody > i d= "t xt " ></ textarea > .. le· ents the spa ce at the end of the word
Examp · ·
Enter te xt : <text ar ea onclic k="c heck( ) .. value="ChecK >
<i nput t ype ="button " <html >
<p i d= "demol "></ P> <head >
</ bod y> <tit l e> re ge x </ tit l e >
</ html > . 1
f d length of exact 2 but it gives the true when word <sc ript >
The above code sh ould give true obn Y or :~r have not specifying the w ord b oundary w ith word
length is 2. 3 or higher number ecause fu n ction chec k() {
character. v ar regex= / \b \ w{ 2 }\b/ ;

i: =:'
'l!!SL
Enter textL - - - - - - - var res = regex . test (document . getElementBy!d ( "t xt " ) . value );
doc ment . getElementByid ( "Oemol " ) . innerHTML = res;
true
</ sc r iot >
Following example validate the e-mail id provided by the user m the textbox . Following a re the valid </r.c~c<,
e-mail ids: <Do y >
1. abc@gmail.com
Ent er tex t : <tex tarea id="txt " ></ textarea >
2. abc.xyz@gmail.com
3. abc@yahoo.co.in <inpu t t ype= " outton" onclicK="cneck()" value= "Che ck">
/" Example 2: <p id = "demo l " ></ p>
<ht:ml > </ body >
<ne ad > </ html >
<titl e > r egex </ ti tle > Output:
<scr ipt >
function check () {
i!I 3 ---1
Enter text _______ _ _ _ _ j
var r egex= /' \ w+ ( [ - . J?\ w+ ) • @\w+ ( [ - . ]? \ w+ )' \ . \ w+ ( [ _. ] \ w+) •$ / ;
var re s= regex . te st (document.getElememByld("t xt" ) . value);
document.get El ementBy l d("demo l ") .innerHTML = re s;
</ script >
</ heaa , iii'"~======================:=!_~~~~~~~~~~~~
<body > • Replace Text using a Regular Expression
You can I
Ent e r tex t : <tex ta r ea ld;"t xt" ></ textarea > • Th a so use a regular expression to replace portions of the text by using the replaceQ method .
<inpu t t ype ="b tton" onclic k="check()" value="Check" > co e repla ce() m e thod requires two parameters: a regular expression and the r eplacemen t text. A
<p ia =" demo l " >< / p> y rnrnon Problem is to replace all occurrences of one or more characters o f a string.
</ body > ou do th · b
</ html > Pia is Y creating a regular expression and calling the replaceQ method: h oweve r . you 'll n eed to
au ce the g special character at the end of the regular expression, which tells the browser to r eplace
occurrenc es o f t h e regular expression
. m . th e strmg.
.
ua e
5.13
Re ular Ex re 5slon Rollover and Fra"'-a
d ocu ment . getEleme ntB yi o • A ular Ex re1Rlon RoUov.,. and Frames

5-' 2 ttern w it h anothe r e x pression do cument . ge tE lementa I ( .. demo1" l. inne rHTML ,..e s;
· g the p a ·
Cl\en, S\de Serl "" Lan ua e t ern a nd reptacin y d ( demo2" ) . i nn e rHTML
re s . index;
we are finding t he pat </ scr ipt >
•___1~n~f~o~ll~o~W~1·~
n~g~e_x_a m
_.~p_le~ ~
c / head >
Example:
c bo oy >
<html >
Enter t ext : <textarea d ,
<h ead > l = 'txt" ></ te xtarea ,
<t i tl e > r ege x </ t i de > <in p ut type= " button"
onclic k=" Check () ..
<s crip't > <P i d=" demol "></ p > val ue= "Che ck">
function cne ck() l
c p i d = "demo2 " ></ p >
var r egex• / - / g; etEl ementByl d ( .'t xt") .va l ue
var st r• aocument . g .. . .. ) . c/ bod y >
pla ce ( r ege x , . , res ;
var r es• st r . re d (" demol" ). i nne r HTML c / htm l >
docume ni: getE l ementBYl
o utput :
j~ !.1!.f. ab-;----i
</ sc ripi:> Enter tex t L- - - - ---- - A [CheqtJ
</ hea a>
abc
<oody> i d• " xt " ></ textarea > .. ..
Enter 1: ex t : <-ce xt.a r ea onclic k=" check () " va lue :: Ch eck >
0
< i npu-r typ e= "out t o n

</ boay>
<P id= " oemo l " ></ P> l!II Regular Expression Object Properties
In additio n to methods, the regular expression ob·ect has . . .
</ html > your Java Script by referencing the name of th l propert_ies that you can access from W1th m
name. e regular expression obJect followed by the property
o utput:
Table 5.1: Properties of the Regular Express·ion ob·JeCt
11 -12-2019
- ---------"'A Check f I I Sr.No. Properties Description-
1. $1 ( th r o ug h $9 ) Parenthesized substring matches .
11 12 .2019 I 2. $ Same as input.
i
1!11 Return the Matched Characters _ . .
3.
4.
$•
$&
Same as multiline.
Same as lastMatch.
• Upto now we h ave only test that whether a panern exists in a text o r n ot but Java Sc npt provides
method to retrieve char acters that match a regular expression. 5. $+ Same as lastParen.
Your browser can retu rn the characters that match the patte r n by calling the execQ method of the 6. $ Sarne as leftContent.
regular expression object.
The execO method retu rns null if n o match is found and return an object with information about
I 7. $' Same as rightContent.

the m atch oth erwise. An obiect r eturned from exec has an index proper ty that tells us where in the l 8. cons tr u ct o r Specifies the function that creates an obje ct's prototype.
I 9. Search globally (g modifier in use) .
string t he su ccessful mat ch begins. L g l ooal I
Oth er than that , t he object looks like (and in fa ct is) a n array o f strings, whose fi rst ele ment is the 10. ignore Case Search case-insensitive (i modifier in u se).
string that was m atched . 11. input The string to search if no string is passed.
Example:
<ht ml>
~ last ln d e x The index at which to start the next match.
I 13. l astMa t c h The last match characters.
<ne a a >
14. l 2 st Pa r en The last parenthesized substring match.
<title > r ege x </ title >
15. The substrin g t o the left o f the m ost recen t m at ch . I
< scr i pt > I l e ftCon t e xt
functi on check () { 16.
mu l ti lin e Whether strings are searched across multiple lines. I
var rege x • / abc /; I 17. I p roto t y pe Allows the addition of properties to all objects. I
va r st r • document. get Eleme ntBy i d( "t xt "). val ue ; 18. The substring to the right of t he most recent mat ch .
var res • rege x .exec ( str ); r igh t Context
I 19 . The regular expression pattern itself. I
sou r ce
tin Lan ua e
R_!gular Expression. Rollover and Fra

~~~<!!:~!E!'~!:!!~~!...----
_s:1ient Side Scripting Language - - - - - -~5.~14:!._--- - - ~ ~ FRAMES R ular Ex rustOn Roffovw and Framu

Example: Using multiline property frames are used to display mor th


<html > re t an one d
::;;--;u;;~::-::::-:----:-------
wmdow ca n b e u se d to display moe han one document in th
. e same wind Th b
The w indow can b e divided into rectan ocument at a time. · ow e rowser display
<head > displaying its own document. guIarareas.eachofwhich . fra
<t1t,e > regex ,/ title > is a me Each fram · b
frames can be used for a number of d'f · e IS capa le of
<scr1ot > . bl f i ferent di la .
is havmg a t a e o contents displayed . sp Ysituations Amo th
fun ction he« ( J
var regex l
• ('"dear ')·//" means here beginning of the string
new Regcxp '
new RegExp("dear '' ' m'); /Im i s flag nere
lll!WI
nother. in one frame and parts . f th ng . e most common of these
O
e mam document displayed in
, ar ·egex2 gal Create a Frame
t line prope rty 1s fa l se here HTML frames define the display into mult'1 1
var al= regex1 .mult il1 ne ;/ / mu 1 is t rue here . d' h'
windows accor mg to 1s urgency and rel
P e regions ·. The designer
·
can arrange the data into several
var a2= regex2 .mult1line ;// mutiline propert y evance. It gives him li .
text an d images. exp cit control over the placement of
var s: r l= document. getElementByl d("txt l ").value; using frames. the table of contents can b d' 1
e 1sp ayed while th d
t (strl ) '/ / expected output : false displaye d . Th e num b er of frames and their la . e vanous ocuments are being
res-= regex l . te s , <frameset> tag. yout m the browser wmdow are specified with the
var str2 • document .getElement Byld (" txt2").value ; A frameset element takes the place of the body l
e ement ·m a document A do th ·th
r es2 • regex2 .t est (st r2 );{{ expected output : t rue body or a frameset but cannot have both. · cumen as ei er a
document . getElenent Byld ( "demol.) . innerHTML al ; In HTML. frames do not work with the <body> tag but with the <html> tag.
oocument . getElementByl d( "oemo2" ). i nnerHTML = a2 ; Other
. than <frameset> 1avascnpt . also.provides <iirame> tag. When you use f rameset you split · the
oocument . getE l ementByl o ( "demo3 " ) . 1nnerHTML res l ; visual real estate of a browser wmdow mto multiple frames. Each frame has it's own contents.
• An iframe . on the other hand, embeds a frame directly inline with the other elements of a webpage.
oocument . getE lement Bylo ( "demo4") . innerHTML res2 ;
<frameset> Tag:
• The <frameset> t ag must have either a rows or a cols attribute, and often they have both. The cols
</ scriot > attribute spec1fies the size of, and number of columns m the frameset. The rows attribute specifies
</ head > the size of, and number of columns in the frameset.
<oody > <frameset rows=" 33%, 33%, 33%" cols="25%, •",
Enter textl :< texta rea id="t xtl " ></ textarea > In above t ag the entire screen will be divided into three rows and me of each row is same i.e. 33 % of
Enter text2 :< textarea io= "t xt 2" ></ textarea > ennre screen.
<input type= "button" oncl ick="check ()" val e= "Chec "><br > <frames et cols="25%, •" ,
In above tag the entire screen will be divided into two columns and size of first column is 33% of
Muti line property on textl :< p 1d="demol " > <p>
screen and remain ing area is for column2. .
Muti l1 ne property on text2 :< p 1d="demo2 ">< / p> The sequence of <frame> tags in a frameset is important because the order dictates which frame
Test on te xtl :< p 1a="oemo3"></ p> gets which content. The frames in the frameset appear by rows. For example, if the frameset has
Test on text2 :< p i d="demo4" ></ P> two rows and two columns the first two frames fill the two columns of the first row of frames. The
</ body > content of a frame is specified as the value of the src attribute in the <frame> tag.
</ html > Using Columns with Frameset:
F JI · . f mes of different size. Each frame shows a different
Output: o owing example creates four vert1ca1 ra
htm l page.
!•dlo
Enrcr rcxcl ~
-
~
\ Eater ICXL'~cic
\••llo
= ••_ _ _ ___..:l Example: For vertical frames.
1. Create a sample.html file with following code.
Muulmc property oc text! <ht ml,
<nead >
<title> Fr ame Example </ tit le >
</ head >
<frames et c e ls= "40%, 20%, 20%, 20%"'
<f r ame src= "webpagel . html " / >
Test on too l <frame src="webpage2 . ntml " / >
<frame s rc =".,ebpage3.html " / >
<frame src= "webpage4 . nt ml " />
<I frames et >
</ htm l,
.,
_):,,.. -
5.16 Re ular Ex resslon, Rollover and Frall'l,s I
2 Create webpagel.html w1th foll owing code.
<html>
II using Columns and Rows With F
I
<head > • columns and rows of fram l'illleset: u1a, Ex ,
<title >web Page l </ t itle> of another To do this We ~scan both app '"10"· Aono- Ind Fram"
</ head > element. ' irst create a fr:: on the sallle w b
<body > l 1
eset and th e Page by ne t
<hl > wee page l </ hl > [xamp e : en nest a chi! 5 1ng one frameset inside
</ body > 1. create a sample htrnJ file With i d frameset Within the paren:
. \,.. <html > 0 11owing code.
'""" , hea d>
3 </ ht 1similar
Write > code for webpage2.htm 1, webpage3.html and t· webpage4.html with some contents. /~ <tit le > Frame Ex
Open the sample.htm l fi le in browser for followin g outpu . ( :\ </ head> ample</t it Je,
<frameset rows-" ,_
We b page l Web page Web page Web p11ge 40
' <frame src= "webp ,30%,20%, 10%' >
3 4 <fr ameset cols=~~e!;, ht ml " ;,
<frame src="wet, >
<frame src="web Page2 .htm l " I>
</ frameset> Page3 .html ' ,
1
<fra me src="webpa
<frame src="web &e4 ,html" />
</ fram e s et > Pages · ntml" ; >
</ html >
Using Rows with Frameset: . . 2. Write code fo r webpagel.htnil b
• Following example creates four horizontal frames of different size. Each frame shows a different with some con tents. 'we Page2.html, webpage3.html Web
h ml a e. Ooen the sample.html file in browser f · page4.htm1 and webpage5 html
\V,r,b (l"~'" I
Example: For horizontal frames . or fo!JoWing output:
1. Create a sample.html file with following code.
<h tm l>
<heaa >
<title > Frame Example </ tit l e>
\\ll"h l •n,: .. .? -
- j"'•b •.•. J
</ head >
" 'vb (lM t,:y 4
<frame set rows ="40%, 30%, 20%, 10%" >
<frame src= "webpagel.html" />
<frame src= "webpage2 . html" / >
<frame src= "webpage3 . htm l " / >
\\'c,b ..... " •.

Example 2:
!(,.
-
<frame src ="webpage4. html" / > 1. C1eate a sa mple.html file With folloWing code
</ frameset > <html> ·
</ html >
{ <heaa >
<t itle > Frame Example< / title >
Write code for webpagel.html, webpage2.html, webpage3.html and webpage4.html with some
2. contents. </ head ,
<framese t co ls="40%,30%,20%,l0%">
Open the sample.html file in browser for following output: <frame set rows="• J•" >
Wt'b pug._. I <frame src= "webpagel.ntml" / >
<fr ame src="webpage2 . ntml" / >
</ fram es et >
<fram e src="web page3 . html" />
<fram e s rc="weopage4 . html" />
<fr ame src="webpageS.html " / >
</ frameset>
</ htm l,
2
Web page 2
· : 1-~~esomecodeco
for webpagel.html, webpage2.html, webpage3.html. webpage4.html and webpageS.htmJ
ntents.
0
en the sam le.html file in browser for following output:
lie!, pagt I \\'eh page J lltb Jll:t lltb

I ~ p,g
I
I 1

1

/web page4 i
I
I

i
l
i
Ro ular Ex rosslon Rollover and Fram,,
5.10
Clie nt Side Ser\ tin Lan ua e
Example:
Attributes of Frameset Tag: . d . s of the columns and r ows in a fram <framese t row «
t the quantity an size . eset. S= 20%, 30% "'>
1 . cols and rows: Cols and Rows se ted by a list of sizes (m percentage) . , frame src= "pagel.html;,
ch rt "b te is a comma ( l separa
The value for ea a n u s ~hether there should be 30 borders between the frames . <f r ame src== rr , narne- u
Page2. ntmJ., - Pagel" s
2. frameborder: Frameborder determine , f r ame src= " name= " croll1 ng-
page3 . ntml" Page2" scr 0 11 · -yes nore size/ >
It takes up t\'IO values - 1 or O. . nd borders are one and the same thing. It sets th </ fram e set > name= "page 3,, ing=no/ >
scrollin
'3 . framespacing and border: Framespacmgh~w big the borders should be. Internet explore: 5. frame b or d er: Framebord g=auto/ >
space between the frames _ indicdatm~ cape understands only b order. Yes sets the border to on aenrdsets the border aro d
understands only framespacmg an ne s h f t no sets th un the fr
Example: e border to off Th arnes. lt takes up two val
of the border m t e r amese .
4 bordercolor· Bordercolor sets th e coIor <framese t r ows="le%, •", · edefaultvalueisyes. ues-yesandno.
· · t e of people on the web that use browsers that cannot read
5. noframes: There are a large pherlcdenthagtext that is to be displayed for browsers , which do not have <f r ame src= "pagel. html"
frames. The <noframes > tag o s e <f r ame src= "page2 ht l " name= "pagel" fram b
frames . It should be the outerm ost frameset element. </ fr ameset > . m name= "page2" f e order="l" I >
rameborder="0" I>
6. border color: bordercolor set 5 th
Example: . ecolorofth b
1. create a sample.html file with following code. Example: e orders around the frame.
<html > <f rames et rows="2S%J "">
<he ad> <fr ame src= "pagel. html"
name= "pagel" b
, ti "Cle >< / title > <f r am e s re= " page2 . html" name- " oroer color=reo/ >
</ f r ameset > - page2"/>
</ heaa >
d ameset rows ="20%, • " co l s='"40%, •" frameborder=" l " borde rco lor= "rea " > 7. marginwidth: Marginwidth sets th .
, frame src="webpagel. html "
<fr ame src ="webpage2 . html "
I>
I>
attribute specifies the top mar in be internal left and nght margins of a frame Th
pixel. Refer following exampleg
<f rame s et rows="20%, ~">
etween the content and the left and right slde ~/:;~~=:~~
. .

<fr ame src= "webpage 3 . ntml " I> <f r ame src= " pagel.html" nam - "
<frame src= "webpage4 . html " I> <f r ame src= " page2 html" n e- }age!" marginwioth=2 / >
</ f r ame set > . ame= pagei"/ >
<; frameset >
</ html > 8. marg~nheight: Marginheight sets the internal to .
2. Write code for webpagel.html, webpage2.html, webpage3.html and webpage4 .html with some margmheight attribute specifies the top mar in b p an~ b~ttom margins of a frame. The
contents. the frame in pixels. Refer following example: g etween e content and the top and bottom of
Open the sample.html file in browser for following output: <frames et rows="20%, "">
<f rame src= " pagel.html" name= "pagel"/ >
Web page 1 Web page 2
<f rame sr c= " page2.html" name= "page2" marginheight=30/>
</fr ameset >
Web pRge 3 Web page 4 <iframe> Tag:
' HTfML 5 doesnot support <frameset> and <frame> tag. It is recommended to make use of
<I rame> instead of <frameset>.
' The <iframe> tag creates a web page which has an inline frame that contains another document. It
<frame> Tag: creates a fra me that sits in the middle of a regular non-framed page.
The <frame> tag sets a single frame in t he framed page. The frame tag is contained in a <frameset> ' :: Works like the <img> tag, the only difference being that instead of inserting a picture on the page,
ta g. It has various attributes, including src attribute that indicates the URL of the page that goes in _puts up another web page.
the fra me. ~ample: For <i frame> tag.
In the following example, two frames are being made of a web page. · Create a sample.html file with following code.
Attributes of Frame Tag: <html,

1. src: src indicates the URL of the page or image that has to be put into the frame . <he aa ,
2 . name: name defines a unique name for the frames . It works like the name attribute of other tag\ <t i tl e> </ t it le >
</ heaa >
3 . scrolling: scrolling means that there should be a scrollbar on the right and/or on the bottom\
n when I <boa y,
the screen . It h as three values - yes, no and auto. Yes means there will be a scrollb ar eve lt
is n ot needed . No means there will not be a scrollbar even when it is needed . Auto is the defau <if rame s rc="webpagel .html ">
d not understand l f ra11es .
If you can see this then your browser oes
va lue that indicates there will be scroll bars as and when required .
. . ~~ </ iframe >
4 . nor es1ze: n ores1ze means that the user cannot make the frame bigger or smaller bys . . </ body >
borders . Normally the user can resize the border with a mouse. Noresize disables this ability. </ ht ml,
Regulllr E, prnum. Rollo-,er and Fr ~
5.2D ~ , .1 5-1,01 Scn
~

·nr te •he code for webpage h l w1 h some contents EXJ!mple: Calling a chi ' .nd.cr,131- ~
·1~ -
rJ ~r n e sa pl~.hirnl fi ~ in browser for follo"NJn g output: rnaiJl-html '~i.C. J
, vd ,
'\Veb page 1

</h l,
Invisible Borders of Frame webpagel .h tml
Ey defa 1 •llhen a fra me 15 created inside a frameset its border will be visible but you can hide he en l>
bord er from o hers c eao ,
The border can be hidden by set mg the frameborder and border a ribu tes of the <fra me> tag to <t 1tle , ~e b Pag e 1• / ti l e,
<sc 1pt lan guage= " Ja , a;cr tlt "
zero (0) fu c ion CnangeCcmt ~ ( J
Example: {
1 Crea ea sample.html file with following code. doCJme
}
< ri:ml,, </sc ript ,
'"nea d> </head ,
<boa y )
< itle ></ le >
<inp ut name• " WebPa gel . value= "\,• b ? • •
'/hE-aC , ' abel i d="labe ll ">• /labe l> · ag_ l YPe• "bo on" I >'or,
, framese rows= "20X, • " cols=" 40%, • " > </ body >
, frame src= "framel.ntml " fram eboraer• "0"/, ' /n tm l>
webpage2.html
cf ra e src=" frame2 .html " f r ameboraer= "0"/ > <b ml>
• f r ame s rc ="f r ame3.ht l " fra mebo rde r ="0"/> <head ,
• frame src= "frame4 .h ml " frameoorder =" 0"/ > <ti le,</ t l e)
,, / f r ame se ., </ heac .
, /html> <inp ut r.a me=" WebPage 2" value• "WeD Page 2· type• "button"
2 Wnte code for frame l .html, frame2.h ml frame 3.html and frame4 .html with some contents. </h tm l> oncli ck:"parent . opPag~ .C a ge<: 0 ,,t~ · 1

Open the sample.html file in browser for following output: O en the m am


· .h tm I m
· browser to see following output:
!'!_ p I
I\\ eb page I Web page 2 F""'°""' alkd 6or., wwpot, l

\\ e b pa ge 3 Web page 4

Calling a Child Window's JavaScript Function

~ Changing the Content of a Child Window


Using fram in th e frameset means creating child windows inside the parent window. Here each
fra mer pr s nt a chi d window and frameset re present the parent window.
lo ca n refer to another child window and its elements by referencing the parent You can change the content of a child window from a JavaScnpt funcuon by modifying e source
window( ramese ). To do so use following notation: Web page for the child window. To do th is, you must assi gn the new source to the child w1 dow 'I hrtf
Parent . f ame_w1 naownam . f unc on_name() • attribute. . .
Following I child wi.ndaws. First child wind.ow (name= opPageJ consist of a
r ollowmg exam ple creates two child windows. First child window (name=topPage) consist of a bu t exam p e creates two sist of a bu on. from second chlld wmdow ym:
can on. Second child window (name~bottomPage) con of aren hence when you click o . bu on c,f
bu tton and l.abeL Second child window (name= bottomPage) consIBt of a button .
se refer the first child window usmg the refer~nce t p ts of first child nndow via he referenCf
conct h 'Jd
ram second child window you can call the method of th e firs t child window usin g the referen ce. of
. . runct1on of c 1 window then you can .make change .
m con en ...
f child window (fram~) to anotm,r pag,
paren hence wh en you clJ ck, on butt on of second ch ild window then you can call 1avascnpt Parent. Here we are replacing the source O
of fi rs ch ild window via the ref r nc of pa rent. (Webpage3 .html).'
c ri ptln L 11 n9~0
Aflg_ul nr E )( e_roS!l lo n , Ro ll o vor onct FrRi~ ell'!!'~ " - 5.2.3
~ changing the Focus of a Chil ' Ro ular Ex ruolon , R llov'!!:_ d_ r@mH
s.z_g_ - n t o f a ch ild w ind ow .
_ - e th e co nt ~ f yo u r c 1· a t ing m ulu ple h 1' ld . d Window
c1111,1 Sid• S<;!:lplln
Lo!'_gu•.9• - - F n cnon c1nd chang I . Wtndo h
- s cnpt u h ow e ver. y o u a n p rovid e the focus t ws t en the last ch ild
Ex.ample : Calling a Child Wind ows Java ages h ave loaded ln th e ir correspo d O any child window b h win dow has th e focus by d efau lt ·
m ain .h t m l p
To g 1v
e a fo us to a p a rticul h . n lng chfld w ndows
ar c ild wi d .
y c anging the focus a ft er a ll the w b
,ht ml ' window as s h ow n b e low : n ow need to refer t ha t h I.ld
...rieao ) a Fr an1e <.. / ti cle " par·e nt . bottomPage . foc us ( j; c window w ith help o f pa re nt
<title >( rea t e
, / head .. OX 50%" > .. rameb roer ="0" /> ~~pile;:~~~~--~~~-=.:~~~~~~~~~~~~~~~-~~--~~
,f ,~ameset rm... s:: 5 , ml " name="topPage ra meborder s "0" I>
<frame src ="webpage 1. ht J" name ="bot t omPage main.html
<frame s ,·c • "webpage2 . ht m <htm l >
< I frame set> <head >
, / ntml > <t i tl e> fra me </ titl e>
webpagel.html ,; nead >
, htm l > <frame set ro ws= "20X, 40%, 40%" >
<hea~:itJ e, i.eb Page 1< / n t l e> t pe =" text / javascript " > <frame s r c ="we bpage l . ht ml "
<Scr ipt language = 'Javas cd pt name= ··t op" fr amebord er • " l "/ >
<frame s r c= "webpa ge 2 . ht ml "
function Ch angeC ontent (). h ef="webpage3 . html" ; name="miadle" fr amebor der • " l "/>
<f ra me s r c= "web page3 . ht ml ..
paren t . topPage. l oca tion . r name="bot tom " f ra mebor der =" l . !>
</ frameset >
</ htm l>
</ script>
</ nead ) webpage1.h tml
/ ><br> <htm l >
<boo~:nput name= "WebPagel " val ue="Web Page 1" type ="b utt on"
<he a d >
</ body > <ti tle >We b Page l </ tit l e >
</ html > </ head >
webpage2 .html
<ntml > <body onc lick= "parent . middl e . f ocu s ( J; ">
<head > <hl >We b pa ge l </ hl >
<ti t l e></ tit le > </ body >
</ head > </ htm l >
<inpu t name="WebPage2" val ue=" Web Page 2" type= "butt on"
oncl1ck =" parent . t opP age .Chan geCon tent () " /> Crea te w ebpage 2 .html and webpage3.html with some content.
</ htm l > Open main htm l i n browser to see follow ing output:
webpage3 .html ~ eh p a ge 1
<ntm1 >
<head >
Web p nge 2
<tit l e ></ t i t l e >
</ head >
<in put name=" WebPage3" val ue="Web Page 3" ty pe="button" />
</ html > ~~~~~~--~
Open ma in .ht ml in Browser to see followinr::g=o=u::-:t::::p=u:::t=:, , - - - - - - - - Web p age 3
~~ ~ P•g;}J

• Writing to a Child Window from a JavaScript


• In the p . . . . .
pr r evi o us s e c tions we have shown som e static pages/dynamic mto frame of frameset us ing src
~Perty. Ja vascr ipt a llows us to create the content dynamically while d e fi ning the fra m eset .
er lie creat ing t he frameset you can use onload event and can call a java scr ipt fu n ction w hich will
eate th e co nte nt o f child w indow (frame) dynamically.
B <fr amese t r ows =" 50% 50%" onload: "ChangeContent() " >
efore w · . '
the h . rit1ng the content in ch ild window make sure that the child window is opened. You can ope n
Wr1tc lld Wi ndow by calling the openO method for that frame. Once, ch.ild window is opened, ca ll the
e Q rn e thod t o write HTML content t o the child wi ndow to create the web page.
Re ular Ex resslon, Rollover and F ' Side Serl !In La n ua e
:'!~~!!.!=~e!!!!ll!~~.a!.~~~~~~~~~_25~·2!4~~~~~~~~~~~~~~-::~~
~ lien\ Side Seri tin Lan ua e ra~e, ell•"'
thod to close the window. In the followi . 'ti Y specify th f
you m ust exp !1c1 5·25
Once the content writing is over, call the closheO metent for the topPage child window, assurni·ng
' , where the JavaScript
e ample ' writes t e con
· func t 10n ng the ele ment, and it must be fr~rnuuthPath to the elem . R Ultr "hlon Rollovor111d Fr111n
e sarn d ent in th 1 ..
the child is from the same domain. ---- occurs. e omafn as th e avascnpt statem
In following example, we are d'lrn e Web page; otherwise ent tha_t references
Example: • 1 .. arnicaU · a secunty violatt
dynam ic content creation a teictbox Y creating the co . on
<ht ml > can access these elements and can (T~xtl) and a butto (Wntent in child Window l(t P .
man1pulat h
<head> pa rent. to pPage . Form1. Tex t i et em. n ebPagel) ls · op age).Du nng
created. Using full th
<ti tle >frame </ title > . va ue _ • pa we
. • t ype="text / Javas cript" > parent . topPage . Form1 ,WebPa - Meenaksh1 Thaler".
<script language=" Javascr1pt ~ - - - - ------..:~:.::::.~1&el.value - "A ,
Example: - ccessed";
functio n ChangeContent ( }
main.html
window . topPage .doc ument . open( ); chtml >
window . to pPage .do cument . writeln( '< html ' ); cnead >
wi ndow . topPage .document . wr iteln( ' <head >' ); <tit le > frame </ t itle >
wi ndow . top Page .document . writeln ('< title >Web Page l </ ti tle >' ); <s cript language="Javascri pt"
window . topPage .doc ume nt . writeln (' </ hea d>'); f type="text/ javascript ">
unction ChangeContent ()
wind ow. topPage . docume nt . writeln ( ' <boa y>'); {
window . topPage .doc ument . writeln ( 'c form acti on•"" method• "post" > ' );
wi ndow . topPag e .oocument.writel n(' <p>'); w~ndow. topPage . document . open ();
window . topPage . doc ument . wri te ln (' <in put name= "textl" t ype • "text" / > ' ); window. topPage . document. writeln ( , <html . ) .
window . t opPage .doc ument . writeln ( ' <i nput name= "WebPagel" valu e= winaow. topPage . document. wri t eln (. <head> ,; ;
"Web Page l " type = "button" / > ' ); window . topPage . document . wr 1tel n(, <ti tle >keb Page l </ ti tle> . ).
window . topPage.oocumen t . writeln( '</ p>') ; window. topPage. document. writeln( , </head>,); ,
window. t opPage .document . writeln ( '< / form >' ) ; window. topPage . document . wri teln ( ·<body >, );
wind ow.topPage .document . writeln ( '</ bod y>' ); window . topPage .document .writeln ( ' <form name •" Forml " action•""
window . topPage .document .wri teln ( '< / html >');
method • "post " > · );
window . topPage . document.clo se (); window . topPage . document . wri teln( · <p>· J;
window .topPage .document .writeln ( ' <input name•" Textl" type= "te xt "/> ' );
</ script >
window. top Page . document . wri teln( ·<input name• "WebPagel"
</ head >
value•"Web Page l " type • "button" / > ');
<frameset rows="50%, 50%" onl oad•"C hangeContent ( ) " >
window. topPage . document . wri teln( '< I p> ' );
<fr ame name=" t opPage" />
window . topPage. document . ~ri teln ( '< / form>' );
<frame src ="webpage2 . html " na me="b ottomPage " />
window. topPage . document. write In ( '< /body> ' );
/ f r ameset>
</ html > window . topPage . document . wri teln ( ·</html >· J;
Output: window . topPage . document . close ();

</ scri pt >


</ head>
<frame s et rows =" 50%, 50%" onload="ChangeContent ( )" >
<fra me name="topPage" />
'
<f r ame src='webpage 2 · htm l " name=" bottomPage " />
Web page 2 </ frame set >
</ht ml>
iiiiiiiiiiiii~=================::!~~~~ ~~~~~~~~~~-------
l!D Accessing Elements of another Child Window
Webpage2.html
<htm l>
You can access a n d change the value of elements of another child window by directly referencing <h ead >
the ele ment from with in your JavaScript.
<title > Web Page 2</title >
,c;,·

r
R ular Ex resslon, Rollover and Fr!'n., Sen tin Lan ua e
Cl' enl Side Set, Im La ~ca 5.26 cuent side

<Se r io: >


f unc ion accessE l ement t) ,,-,. Roll.,.. and Fra..,...

= "Mee na kshi Thale r ";


parent .t opPage . Fo rm 1.Tex t1 .va1ue
1 e = "Accessed " ;
pa ent .t opPage . Fo"ml .WebPa~e1.va u

<' script >


</ head>
<oooy>
< 1> Weo oage 2 </ hl >
<1 nput name="WebPage2 "' val ue ="Acce ss Element of Another winaow"
t ype= "button " onclick="accessElement () "/ > In above example we have seen
</ body >
</ ntm l >
Output:

Example 2: Change image (Rollover and RollBack).


<ht ml >
<neaa>
<title> Rollov er </ title >
</heaa>
Web poge 2 <booy>
<I MG he ig nt ="92 " src= "DSA . jpg" alt=' no image" width="70'
onmouseover='src=' WT . jpg ·" onmouseout= "src =·OSI>. . jpg ' • >
</ body >
pl ROLLOVER </ ht m:. ,
A rollover occurs when the content of a web page changes as the mouse cursor moves over and away Output:
from an object on the page. Any object on a web page can be changed with a rollover.
Sometimes we have seen image of advertisement on a webpage frequently changes when we move
mouse over the image or some pop up window created to describe the object.
ml Creating Rollover
A rollover is caused by an event called onmouseover and occurs when a visitor to your web site
moves the mouse over an object that appears on the page. An object can be an image, text, or any
element of a form .
In the following example, the <img> tag is used to define the image object. The value assigned to the
src attribute of the <img> tag identifies the image itself. Now using onmouseover event you can
change the image . ll!'IN
lilliU Text Rollovers . 1s
d ollback on the <tmg> element. We can a o create a
Example 1: Change image (Rollover). ' In previous section we have seen rollover an r attn·bute of the <a> tag( anchor tag). You assign
r 11 · the onmouseover
o over and rollback for text using_ e way as you do with an <img> tag.
~.,,.... <ntml> the action to the onmouseover attnbute the sambl ·ng the <table> tag to display the image and the
, <head > In the following example, We have created a ta e us1 h
bl onsi·sts of one row which is defined by t e <tr> tag,
. .
descnpt1on . b age The ta e c
<tit le> Rollove r </ title > of image on the we P · e <td> tag. . ·
</ head> rand three columns which are defined by th
. . · e The secon
d column is used separate the image from its
he first column contains the imag · . a e description.
<boay> description. The third colum_n contain_s ~seeio ~efine the image object. The value assigned to the src
15
<I MG src='"DSA. jpg"' height= "l50" wiath="100" alt="No image"
. •' / )
onmou seover=" s rc= ' WT · )Pg
In addition to <table>, the <1mg> tag ·
attribute of the <img> tag ide_ntifie:
When first time the pages will be O
::r:::n itself.

f the three titles m thir co u


•· 0
· f th
a image will be disp~ayef :n!ll~;~rst~~ \~:~e~ get:
</ body > table. As we move mouse over the any 'O

--
</ html > changed.

.. .
un Lan :ua
-·~"·~
~
"
e folloWlng examp •'
lfl th 1
on of 1mag on the
deScriP e colu mns which are
d dire
Client SW Scrlpt1n.9 u ~ an firs t col umn con ins ~ ~ e. The
rMe non. The third column ontams the ·
Example: descrJP define th e image object. . val e iissi
used t o
,>i tml > . a e itself.
<head > le > ,rn g nt to change the image as w . ·
, otle> frame </ tit AS we wa th . as ts escnp o • on the web page whenever the vis_1tor
rnoves the mouse cu~or ~ver. e un~ge. \' e r the onn1ouseover even occurs, we need o
, / head > .. oorder= "0" >
, table .,1dth= " 100% change the value of the src " ttribute O iden ·fy the new image Here's how this is done:
documen t . getE lement By! d ( "i gl ' ). src. " l<T .J g";
oo~t; vAJ ign =" t op"> .. wi dt h="70" .. .. ~ change image and its description.
< o ,. 1otn="50 "> "92" src="DSA.jpg alt= " No image" name = cover ><l a>
txaJJlP e ·
, a,omg neight= <html >
<heaCl >
<tit le> Ro llover </ title >
i mage " wid th=" 10 .' ></ td >
</ td > < sc ripl: Jang age= · Javascript " type= "text / javascnpt " >
. - " 1 " src=" " alt= ·· No
he1ght- func ti o n di splay ()
, to>d mg
cover . src= ' DSA. jpg , .. > {
<td > - "document docu ent. getEl~e nt B Id (" imgl " ) . s c s "WT . jpg· ;
<a onmouseover- us i ng "C"</u></b>
<b>< , Data Str uc t ures docu e nt . getEler.tentByld (" detail ") . i nne rHTML = " <h3>1.eb
ech ology </ h3>< br >Meena kshi Th alor<or> Publishe r : Ni rah
</ a > P blication <br> Pages : 298 <or>ISBN : 9789388 93457< br>Publishing e ar :Oct
• WT. J pg ' "> 2018 <br>~eblink : https : / ; ..-ww . pragat io nlin e. com/ e ngineering / we e·
<b r> -"docume nt .cover. src
on mouseover- technology /";
<a rn ><u»•eb Technology< / u></ b >

</ a > </ scrip t >


B NET . jpg ' "> </ eaa>
<b r > - "doc ument . cover . src
<a onmouseover- <boa y>
<o >< u>VB. NET </ u ></ b> <table 1c= " tab l el " wi dt h= "1001" boraer= · a ·,
<tboo >
</ a > <tr va li gn="t op">
</ td > <td widt h="50 " >
</ tr > a>
<img id="imgl " heigllt= " ls~ · src ="d.sa . jpg·· wi d tn: ·· 1ae·
</ tbody >
alt= · no image ·· onmouseover= display ( ) I>
</ table >
</ boay > </ a>
</ td >
</ html >
Output: <td > alt= "No Image · height =" l " src= widtn• " l0 .. / >
<img
Dm SttJmm u ~ Pm Srrucrum uiui..::.C.:: / td>
~ · <td id= · detail "> .. C"< ' h 3 >
Web Technolo&:-: <h3 >Data str uctures using ,
~
IB_,lil <br >Meenaks hi Thalor •
<br >Publisner : Nira l i Puolica ,ion
<br >Pages : 239
<br >ISBN 97 893 876 86915
. Yea r . June 201 8
<br>Publ s h1ng .· ragationline . c , / eng i ,eeri ng 1
<br >Web L nk : https . / / ........., . p da t a - st ruc tur-es-using-c /
P.1!1!11 Multiple Actions for a Rollover .
~
In previous sections we have implemented rollover by performing an onmouseover e~en
rwh1ch 15
tbod </ tel >
directly associa ted wi th the HTM.L tag hence no need of javascript code. Th is di rect(lntnnsic) me </ tr')
enables you to perform one act ion in response to an onmouseover event. </ tbody>
</ able>
But sometime you may find that ou want more than one act ion to occur in response to an
</ bo ay >
onmouseover event m that case we can use JavaScript code. </ h ml >
~ iar Ex pre ssion, Rollover and Fr~
<img
<l a >
~ </ td >
Src="DSA .jpg•
W1dth=" 70" name="cover " >
SC~ll~en~tjS~ld~e~S~c~rl~pl~ln~g~L~a n9~u~e~9~•~~ ~ ~ ~~ ~ <t d >
</ td : img height= "l" src= ··
Width:" 10" >
<td >
~~Thtl:t <a onmouseover=" o en
~~lllh~- <b> <u>Data P neww1ndow (l )"
Pi:11 )9! </ a > Structures using ·c· onmouseautz"mywind0w . close ().>
3~9it9:1t19;i;· <br) </ U></b >
~Y11-0.t llll! <a onmouseover="openn .
i·tH.utttpl. ,r~cxm~-:!»l l!CU4~ <b>< U>Web Te h ewwinaow( 2)" o
</ a > c nolagy< / U></b> nmouseout ="myw indow. clos e ( ) " >
<br ,
· te with <3> t ag : . <a onmouseover-"o
. example, two events are associ a . ked which will ch ange the source of ~1mg> tag <b - Pennewwindow( 3 )"
</ a > >< U> . NET</U></b> on1110useout="mywindow. close ( ) " >
In the following . vascript function will mvo . d write some extra information about
1. onmouseover event a. Ja with specified dimensions an </ td >
and creates a new window </ tr >
the book. !ready opened new window get closed. </ tbody>
2 on mouseout event the a
</ ta ble >
Exa~ple 2: Multiple rollover and rollback. (/ bod y >
<html > </ htm l >
<head > out ut
<title >frame </ ti~~e > " type= "t ext / Javascr1pt " >
<scri pt l anguage= p vasc r 1pt ~
functio n open ne•.....,indow ( book )
if ( book == 1 )

aocume nt . cover . src = ' DSA . jpg '; . ,


. d - window open (, . , ' myadw1n ,
mywin ow - · , height=50,w idth=l50 , left=50 0, top=200 ' );
. · te ( · 10%discount for data stru ct ure sing "c " ! ' );
myw indow . aocument . wri

if ( book == 2)
{
Li!i More Efficient Rollover
In all previous examples of rollover, whenever an image is referred either it is first time, second time
document . cov er.s r c = ' WT . jpg ' ;
or nth time then each time browser loads the image because of that a significan t delay is noticeable
mywindow = window . open ( " , ' myadwin ' , , .
' height=50 , widt h=150,left=500 , top=200 ), to visitor
mywindow.do cument . write (' 20% discount for web tecnnology ! ') ; We can avoid this delay by loading all images once when they are referred first time on web page
because of thi s next t i me when same image will be referred the browser will get it in its cache and
the time t o d o wnload from the web server will save.
if (book == 3 )
Example:
aocument. cover. src = · VB_NET . j pg ' ; <htm l>
mywindow =wi ndow . open ( ' ' , ' myadwin ' , ' height=50 , width=150 , <hea o >
left=500 , t op=Z00 ' );
<tit le > frame </ title >
myw indow . ao cument .write ( ' 15% aiscount for .net ! '); <script language= "j avas cript" type="t ext / javas cript" >
ds a = new Image ;
wt = new Image ;
</ script > ne t = new Image ;
</n eaa > if ( document . images )
<t able wiatn= " l 00%" boraer ="0" > {
<tb O > ds a .src = ' DSA . jpg' ;
<t r vali gn= "top "> wt.sr c = ' WT . jpg ' ;
<td ..i1ath=" 50 " > net . src 'VB_NET · jpg ';
<a > else {
Re ular Ex resslon Rollover and Fram,,
5.32
Client Side Serl tin

dsa.src ...,
wt.src = '';
net.src = '';
document.cover
...,
}
</script>
</head>
<body>
<table width="100%" border= 0 >
<tbody>
<tr vAlign="top" >
<td width="50">
<a> · g" width=" 70 " bor der= "0" name-"co
-"DSA ,JP - ver " >
<img height= "92" src -
</ a>
</td>
<td>
<img height="l" src='"' width="10">
</ td>
<td>
<a onmouseover="document.cover.src =
dsa .src">< b>< u>Data Structures using "C"</u></b></A>
<br>
<a onmouseover= "document.cover.src =
wt. src" >< b>< u>Web Technology< /u></b></ A>
<br>
<a onmouseover="document. cove r.src
net. src" >< b> <u> .NET</u></b></A>
</td>
</tr >
</tbody>
</table>
</body>
</html>
Output:

I. .

.
'
,

Practice Questions:
f

1. What is meant by regular expression?


2. How to finding non matching characters in regular expressions? Explain with example.
3. Enlist regular expression object properties.
4. What is frame? How to create it? Explain with example.
s. With the help of example explain how to writing to a child window.
6. What is rollover?
7. How to create rollover? Describe with example.
a. How to find non-matching characters? Explain with example.
9. Explain the term matching sy~bols and punctuations in.detail.
10. With the help of example describe h?w to replace text usmg a regular expression.
11. Explain the term matching words with example.
•••
6...
Menus, Navigation and
Web Page Protection
§apter Outcomes...
l
00 Develop JavaScript to manage status bar.
@ Develop JavaSc ript to create the given banner.
00 Develop Ja,·aScript to create the given slide show.
00 Develop JavaSc rip t to create the given menu.
I Write JavaSc ript to protect a web page in the given mann er.

~earning Objectives... I
[!) To learn Sta tu s Bar Concept in JavaScript
• To und er s tand Co n cepts of Banner and Slide Show in Ja vaScript
[!) To stud y Me nu in JavaScript
00 To und er sta nd Protecting Web Page and Frameworks of Java Script

' The status bar is found at the bottom of the window. It normally displays the current status of the
document being loaded. JavaScript can be used to display messages in the status bar.
' Displaying banners ads is a common practice for showing advertisements on web pages to the
visitors. Banners take highest usage ratio in digital advertisements.
' In this chapter we also study slide show, menus etc., in JavaScript.

• STATUSBAR
' Status bar is the message bar at the bottom of your window.
' When you move your mouse over an HTML link, the URL.appears in the status bar. You may have
seen pages that use JavaScript to turn this status bar into a scrolling marquee.
' The status property belongs to window object and this property does not work in default
, configuration of IE (Internt:!t Explorer), Firefox, Chrome, Safari or Opera 15+.
Most (newer) major browsers disable status bar messages by default. If your status bar doesn't
• change when you hover over the link, it's probably because of default settings.
0
: display some text on status bar, we can create a child window inside main window for
, ltnplementation of showing static text, showing moving text etc.
In follo wing
· sections we have create a chi'Id wm · d ow msi
· 'd e mam · wm · d ow to show the status bar as
rnost of browser don't allow to change status bar message through program.
[6.1J
.'
51de serf ton Lan ua e
cuenl
Protection

. d is used t o display a short message


ll!fR Builds a Static Message browser window an
UY 1 cated at the bottom of the essage t o the status property of
• The stat us bar 1s o d to assign the m
to visitors of web page t tus bar. you will nee
essage on the s a
To d1sp lay a m ert of child wmdow
the window ob1ect set the status prop Y
w1naow. st atus ="he llou dow inside the main windo~:: status o f ch ild wmdow as follows ·
hl
As we are creating child wrn ess,e~n~t~ch
Let Win Obj is object which repr .
WinOo .. s tatu s ="hello"
: 1l:d~w
: 1~n=d=o~w~t~h-e_n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __ __
dJ1 Moving the Message along the Status Bar
• you c an show any message on the status b b . .
Example:
messag e a movement. To give a movem ar Y displaying letters individually and giving the
<htm l > · ent to message need t ·
where we c an sett h e time after which individ o use wmdow.setTimeout() method
<he ad> . ua 11etter should ap lib
<s c rip t> The message looks to ripple across the stat b . pear on scro ar.
us ar connnuously h th · ·
func tion showStat us () a"e.
P o Movem ent of the message doesn 't stop d . w en e visitor looks around the web
"toolbar=0, status=l, menubar=l , _ even unng rollovers.
wi nObj = wi noow.open ( "U RL" , "W1ndowNa me "' innerHe ignt= 100, i nne rW idth= l00" ); Example:
<html >
winObj. st at us="nello" ; <bo ay o n Load = "scrollin ( )" >
<scr ip t >
</ scr ip t>
</ he ad> .. , Wi nObj = window . open ( "UR L" , "W1ndowName ", "toolbar=0, status=l ,
<Cody on Lo ad= "s howStatus () menubar=l , innerHeight = 100, innerWidth 100");
</ body>
</ htm l > var Message = "Text is moving ! ";
Output: var place= 1;
f unction scroll!n ()
WinObj. status = Message . substring (0, place ) ;
i f ( place >= Message . length ) {
place = 1;
window . setTimeout ( "sc r ollOut () ", 300 );
r!!J Changing the Message using Rollover else {
place++;
In earlier example we had set the static status message whenever the new ch ild wi ndow will be
loaded . We can also change the message of status bar on any specific e vent like onclick, window . setTimeout ( "scroll!n ()", 50 ) ;
onmouseover event.
In fo llowing example, we have create a child window with one button and when user will move
m ou se over the button then the status message of window get changed. function scrollOut () {
Example: WinObj. status = Message. substring(place, Message. length);
<ht ml>
i f ( place >= Message. length) {
<body>
<s cri pt > place = l ;
WinOb j = winoow . open ( "URL ", "WinoowName ", "toolbar=0, st atu s=l, window. set Timeout ( "scrollin ( ) ", 100 );
menubar =l , widt h = 100 , height = 100 ") ; else {
Wi nObj. s tatus= "hell o"; place+-t- ;
WinObj . document . write (' <input type= "button" name=" a Button " val ue ="Clic k Me" window . setTimeout ( "scrollOut ( ) ", 50 );
onMous eOve r=" WinObj. s tat us =" hl" ; return t r ue ; " I >· ) .
</ script:> '
</ body>
</ html> </ sc ript >
</ boay >
</ htm l,
I Un La n ua e
cuenl Sid9 5!!:C'!c'==--====----

document - img1 . src = Ba Menus, Nav, ation and Web Pa e Protec tion
set Timeou t (.. nne" s [ count J·
rotate () ", 1000); '

</ s cript >


</ head >
<body on l o aa="rotate () " >
<ce nte r >
<img src="DSA . Jpg·• width="300" h .
</ cen ter> eight ="400 " name= "i mgl • >
1
</ body >
</ html >
Te
BANNER . osed to text-only advertising ). The purpose
output:
___ - ..
.......
..__ .,..,o,i.,.......... ~----...._ __ Ill

c.olll#UTtllt &G.U ! NC. AJ(O L...0-lfflUIUNO a11Q1Jp

WfB TECHNOLOG~

Linking Banner Advertisements to URLs


Yo~ ca n link a banner advertisement to a web page l>Y inserting a hyperlinl< into your web pag e that
ca s a Java Sc ript function rather than the URL of a web page.
The JavaS cript then determines the URL that is associated with the current banner and loads rhe web
page th at 1s a s sociated with the URL.
In next example we are extending the previous example where <img> tag is used inside <a > tag
which creat_es image as hyperlink. when user click on one of the rotating image then corresponding
web pag e will open which provides the extra information about the book.
Example:
<html >
Example:
<he ad >
< html>
<heao > <ti tle >Banner Ads </ title >
<tit l e >Ba nner Ads </ ti t l e > <s cri pt language =" Javascript" ty pe= "text t javascr i pt " >
<script la nguage ="J a vascript" t y pe= "text / ja vas cr ipt" > Banners = new Array ( ' DSA . jpg ' , ' WT . jpg ', ' VB_NET. j pg ' )
Ba nners= new Arr ay(" DSA. jpg ' , ' WT . j pg ' , ' VB NET . · ') co un t = 0
co unt = 0 - Jpg
Banner Link = new Ar r ay ( ' data-structures- usi ng- cl' , ' web-t ech nology , · ,
function ro t ate() {
· gui-app l icat io n- de velo pment - .JSing -vb - set /· , ) ;
if ( document. i ma ge s )
coun t:+"' ; function LinkBanner( )
if ( count == Ba nne r s . l e ngt h )
{ document . location . href "http : I / WWW . pragat i o nll ne. c om/engin eering/"
cou nt:= 0 ; • Ba nne r l1 nk [cou,1t!
P,,,~ ..,:

VJ rrrp I~ .
,, ,, .. ;,
, .. ,..,~,
, ' ~ t.• , ~.,, , l•I', ·., /I j •
,·,•,. . ~~ ·"'i!1c%
4- ·•,
i :,,.~·,,, ..,.,r
:, ) ; ';, • I b' .# /., , .• • ,-.·,~ • ; ~.. 4
I ~
r •u• ,.. .. ~ 1,.J, :~ • •, ,~,•~·J'l" "
·:-t. ltid r: ~

;i r,;,,, ,..,..,.,.
·"'·~~.
·, .

: ~ ', ', ...,.,


· =-;.: ,,
. ; . •: ..... t'.

, '/,,~I'

' .. ·-. ,, I',',." J,.

.. --
·- -

.. .; .. ~ ~.!
.:·,.:. .(.. ~ u .: · ..
::..·"'~, ". .,.r "'r. ::,..,_ .. ........- .... . .. .... ~ ~· J. ,.,,.;,::".. ! '".>f'~-
Side scri tin La n ua e
~C~ll~en~t~S~,d~e~S~c~rl~p~tm~g~L
~a~n~gu
~a~g~e~ ~ ~ ~ ~ ~ ~ ~ ~ ~~6~
.a~ ~ ~ ~ ~ ~~
M~•n~u~•~·N
_a_v~lg~al_io_n_a_n_d_W
_e_b_P~ag~e~P~r~o ~ cuent
le: Followi ng example p &.a
l!ll Creating a Pull-Down Menu tia Jllp
the 1
fi resents
v1s1tor. Visitor irst select on two drop d
e of th own
..,nus N
· av1 au
The most common form of menu ·s pull-down menu or dro -down _m.e nu Clicking a menu title content of Emp oyees will be chang d e Options fr lllenus ( nal!Jed on Ind Web Po • Pro1oc11on
e Ynal!J· Ol!J De as De
causes the menu items to appear to drop down frorruha.tposit1on and be displayed. , ntml > IcaUy Partll!ent menu, t : :ent and Employees) to
Example: Following example creates a Pull-down menu with three options [G.oggle, MSBTE. Yahoo] . a;; <nead > on histher choice the
the user will select the one of the opnons then user will red irected to that site. ~or redirection purpose <title >Menu </title>
the window.location.href property is used that tell you the current URL location of the browser anct <script language="]
avascript" t
changing the value of the property will redirect the page. compemp = new A YPe="text /j
1 t rray( •Meena ksh .. avascript" >
<html > e ec emp = new Array ( ' D· l ' ' Sakshi ' ' R
m ead > fun ction getEmp (b lPali ·, 'Rupali • '. .um shi ' );
{ ranc h) , AnJali · );
<t1tle >Menu </ title >
<script lang ua ge ="Jav ascr1pt " t ype="t ext / javascri pt" > I / clear out the
current o
function getPage (Choi ce ) for ( i = do Ptions
cument. Form1 . Emplo
Yees ,Options l
. ength . l ; i > e; i . • )
Page= Cho1 ce .opt1ons(Cho1ce.se lectedindex]. val ue; document . Forml E 1
· mp oyees O t ·
1f (Page ' = "" ) · P lons .remove (i );
Dept = branch.options[branch sel
window . l oc ati on Page ; if (Dept != "" ) · ectedindexl. value

if ( Dept == •l · )
</ sc r ipt >
</ heaa> for
{ (i -- 1,· 1· <= compemp.length; i++ )
<oody>
<f orm action= "" name ="Forml" > } document. Forml · Employ ees .optlons
· [1. =new Option (compemp[i -1 ));
1
Select you r fa vour ite webs it e :
<select name="MenuChoice " onchange="get Page (t his ) ">
if ( Dept == ' 2' )
<opti on value= "https :// www.google.com" >Goog le </option >
<optio n value= "https: // www .msbte . org.i n" >MSBT E</ option >
for (i = l; i <= electemp .length ; i++ )
<option va lue= "ntt ps : // WWI,. yahoo . com" >Yahoo< / opt ion >
</ select>
document . Forml. Emp loyees .options [1] =new Option (elect emp[ i - 1] );
</ for m>
</ boay>
</ htm l >
Output:

</ script>
MSBTE </head >
Yahoo <boay ,
<fo rm action="" name="Forml"> . ..
.. change="getEmp(th1s) >
<select name="Department on
. 1 - "0">Departmeots< /option>
<o ption va ue- .
. 1 - "l " , computer</opuon >
Dynamically Changing a Menu <option va ue- .
value="2" >Electronics< /option>
Rather than presentmg the user some fix set ofoptions. It is always better ro present some on the fly <option
conten r. </ select>
We can chan ge the set of options dynamically based on choices made by visitor on the webpage <select name="Employees"> /option >
e="e" >Employees<
because of this one menu can be used to display different sets of options hence reduce the need to <option Valu
show too many m enus on a web page. </ select>
idB SE!£' '" La n ua e
~ <option
6.11
Menus Nav, tllo,, and Web p Pro tection
value•" l "

-
>Banana< / opt1on ,
<option
value •" 2" >Or ange</ opti on>
<Option
va l ue= "3" >Man go, / option>
<option
<Or > va l uea" 4 .. >Papaya </ option ,
<P> .. va lue• "Submit" / > </ se lect>
, 1np· •t rype• "s uom1 t et" / > <br >
' v val ue=" Res
onput t ype•"re et' <p >
<. Ip>
<in pu t ty pe="submit" value •" Subm it " / >
< l fO l'ffl J
<i np ut type=" r es et" val ue •" Re set " />
</ body > </ p >
/ 11tml >
Out put:
Employee! "
- -C OJT'IJ>Y1ef
·~
R•"-'- Me•n•~• </ body >
</ f orm>

Departments _., s,10.mh


S•Qhl
Rup~t..5,h l </ htm l >

..
I Sub~ ~ esetj solution:
Sti t , our fa, o uu1c fnut Frutt.s Name 1
loc• lhosr SOOO soys

11!1 Floating Menu


s ometim es the cont e nts on webpages are too long that to read enti re conten t visitor has to s croll up
. I presents drop- own men or d own ma ny t im es because of that menu placed at top or bottom of the page gets h ide .
Example: Followmg examp e . h hether visitor has selected o n e of the five opt ions or
I
and reset operau ons. Here we are va!Jdaun_g a; w"t will be popped up an d form will n ot be sub m itt ed to The javascript allows us to create dynamic menus wh ich move along with scrolling. Such floati n g
not. If user not selected any of the opuons tnen a e1 menu will be a lways v is ible on screen. Creating a float ing menu is very si mple and quite pai nless .
the server The o pe r ative cod e is position 'fixed '. The effect is achieved my moving an absolutely-p ositioned or
<html > relat ivP:v-p osi t io ned <div> container which containing the menu.
<nead>
Following exam ples creates a floating menu where the menu stays fixed in same p osi t ion on th e
<ti tle >Men u< / title > web page wh ile visi tor scroll down the page. The style is applied on <d iV> contain er w here the
, scr ipt language=" Javascript" t ype ="tex t / ja ascript" >
position , wi dth , h ei ght, background and z-index property are specified. An eleme nt w ith g reater
fun ct i on Valiaate Form( choi ce )
z-index is a lw ays placed in front of another element with lower z-index.
Example:
en choice . Fr uit s. selectedindex ;
1f (c ho1ce . Fruit s .options[ch) . va l ue "" ) <htm l>
<neaa,
alert ( Pl ease select a frui t · ) ; <tit l e> Menu </ t i t l e >
return false; </ heaa >
<body >
return true; <div s t y le="
posi t1on : fixe d ;
</ scr ipt > wi dth : 200px; height : 50px; top : iepx; r ig ht iep x;
</ head >
b a ck grouna : blue ;
<body>
z - ind ex : 100 ">
<form onsuom it ="ret urn Valida t eForm ( this ) " actio n=" " name =" For ml" > Fl oa t i ng Men u.
Sel ect your favouri t e fruit :
</ div>
<selec t name ="Fr uits" > <b r >< b r >< br > <br ><br >< br> <br >< br ><b r > <br >< br >< br > <br >< br >< br >
<option value="" >Fru i t s Name </o ption >
This is a l ong we b page b b
<Optio n value= "0" >App l e</ optio n, <br >< br ><br > <br >< br >< br> <br >< br >< br > <b r >< br >< br > <br >< r >< r >
Side sc ri tin Lan ua e
Menus. Navi ation and Web Pa e Protection ell•"'
6.12 ----- ion ...., W.i, p P rotec:Uon
compemp -l engt h,·
i-.+ )
Thi s is a l ong weo page <br >< or >< br > <br ><br ><br >
Clocume nt . For
<or >< br> <br > <br> <br> <br > <br >< br >< Dr> <br >< or >< br > <br >< br >< br > 1 . Emplo
< br >< b r >< br > <br >< br >< br > <b r >< or >< or>
}'ees . options[ i]

</ body> = new Opt ion ( c Offlpe 111p [ i - 1 ]);


</ html > i f (D ept == . . )
Output: 2

for (i = 1; i
{ <= electemp . lenDT h,·
... i++ )

aocument. Form1 . Emplo


yees · 0 Ptions [ 1 J

= new Option (electemp[i _ l ]);

1111 Chain Select Menu


Xin Yang developed a chain of pull-down menus in which the option selected from the first pulJ-
down menu determines the options that are a vailable m the second pull-down menu. </ script>
Likewise. the second pull-down menu selection determines options t hat are shown in the third pull- </ head>
down menu . <bo ay >
The purpose of chain select menu is dyn a mically cha nging the list of options in the menu. As we
have already seen t he example of "dynamically chang ing a menu" where we have create two menus <fo rm action='"' name="Forml" >
in sequence. The selection of item in first menu d etermines what cont ent to be presented to visitor in <select name="Department"
<option val _.. .. onchange= "getEmp ( this ) " >
next menu. ue- 0 >Departments< / option >
Chained Selects lets you "chain " multiple form select lists together so that the selection in a "parent" <option value="l" >Computer </option >
list can tailor the options available in a "child" list.
<option value="2" >Electronics </ option >
Chained Selects supports unlimited number of form select lists in a "ch ain" , as well as unlim 1"t d </ select>
number of "chains" in a page. e
<select name="Employees">
Example:
<option value="0" >Employees </ option>
<ht ml>
</ select >
<h ead >
<Or >
<title >Menu </ title>
<p>
<sc r ipt la nguage ="Ja vascript" t ype="te xt / j a vas c r i pt " >
compemp = new Array( ' Meena kshi ' ' • Sa ks hi . ' . Rupaks hi • ) ; <input type="submit" value="Submit " / >
e lectemp = new Arra y( ' Dipali .' • Rupali •' . Anja li • ) . <i nput type="reset" value="Reset "/ >
functi on getEmp(branch ) ' </ p >
{ </ form>
I/ clear out the current options </ boa y >
for ( i = aoc ume t F </ htm l>
{ n . orml . Employees . options.le ngt h - l; i > 0 ; i-- ) Out~ut:
document. Form1 Em 1 .
· P oyees . opt1ons.remove (i); 9epartments y ~ mplo ees .--1
Dept = bran c h. options [branch
if ( Dept != "" ) .selec tedinde x] . value ; ~ LReseil
_ 1_
i f ( Dept == • l , )
llb----:;ab Menu
• T
d:~ rnen_us display a one- or two-word description oft'1e menu option within a tab . A more complete
cription is displayed below the tab bar as the visitor moves the mouse cursor over the tab.
Lan u1:1 · 1::1

ell•"' side Serl un


<label f or="chec &1
.s
t,len~s. Navl at1on end Web Pe e Protection
<div class=" kbox1 • >Tab
6.14 Th . . content "> l</label>
15 15 th
</div> e content
There are following
t . Using two ways
a.dio Button,, ofone
OnlY creating
radio tabbed
button area:
can be selected from a ,ame g,oup of cadio butt 0 </ div> of tab
We can ,ak,> ,he Qme idea and""" ,abbed " " using cadio buttons " <abs. Usin g 1his m ~n,
<div class="tab"
wee~ avoid Ja.ascripl comple,ely. " d . >
2. Using target selector: This is the most preferred way of_creating tabbed area. In this method <1nput name-"
- checkbo x-tabs-gro "
h-" <o ma ke use of]awse<ip< code fo< bell" usec e,q,enence. we
<1 b up
Ex=P~ t, Tab menu osing rndiobnttons In ,he following code we have used ,adio buttons bul be a el for= "c type-"
<div 1 heckbox2" T - radio" id="checkbox2" class= "checkboxta b " >
of dopl,ycnone scyle rnno buttons w,ll no< apP"' bu< con""' and label placed afle< 1he checked cause c . ass-"
button u scyled ,cconlingly. The fi~l checkbo> is checked by defaull. The 1abs appm h . <ad10 - content" > > ab 2</1 abeh
beanse of floa, lefi wh,ch ,,u 1h• hori,onlal alignmenl of an element. onwnt~ This is th
</div> e content Of tab 2
<h t:ml > </ div >
<St yle >
<di v class="tab" >
. ta os . tab
< input name= "che ckbox-tab s-group"
flo at : l eft ;
<label for="che k t ype="ractio" id= " checkbox3" class="checkboxtab">
d. c box3" >T b
· ta os . tab . content < iv class="content" a 3< / label>
This is th >
position : abs olute ; < I div> e content of tab 3
bac kground-color : white ;
</ div>
left : 0px; </ d iv >
widtn : 60% ; </ bod y>
border : lpx bla ck solia;
</html>
Output:
. checkboxtao
{
display : none ;

· tab label
Exa I
mple2 : Tab
{ applying styli ng menu
<html> using Targets e 1ector. In the following code w e are usmg
and content. .
anchor
margin - right : 10px; <st y le , lag " mge, =d

{. checkboxtab: checked - label


· tabs . tab
color: purple . {
border : lpx b~ack solid ; float: left ·
margin-right' ·. 10px;
{. checkboxtab.. ch ec ked - . content
.content
z~inoex : l; {
position : absolute ·
</ s t y le > background-color·. white;
'
<Dody> width : 100%·
<di v class="tabs" > left : 0 px; '
<div class="tab" >
<input name =" ch eckbox-tab {-tabs · tab : nth-of-type(l) . content
t s-group"
ype= " radio" id=" checkbo xl"
class="checkboxtab " chec ked > z-index: 1;
. ' uent 5
,de scri 111' -

. ,
6.17
Menus, Nav, Ion and Web Pn>tectlon
c le > section. the .hover selector is ed
alien and Wob Pa e Protection
111 <'. StY ver the drop d own button. us to show th
e popup menu when the user moves the
use o
rn° d opdown class uses position:relative which 15.
rne · r d r ig ht below the dropdown butte~ ( . n~ed when we want the dropd.own content to
b e p lace down-content class holds the actual using posmon·absolut )
· e·
rne .dr ~ on hover.
O
. tab : t arge ,: a dropd O'..vn menu. It is hidden by de fault. and will be
-- sp\aye
f ont -weignt : bold ; ell d of usin g a border, we have used the b h
• 1nste~. d ". we have used z-index to lac ox-s adow ~roperty to make the dropdown menu look
u1<e a car P e the dropdown m front of other elements.
) ontent ~ u p menu onmouseoverQ event.
. tab : target . c
i;,carnPl ·
<ntml >
<head >
<s ty le >
</ style > . drop otn
<bOOY> background-color : Green ;
<dl v class ="'tab s" > .. - "tao l ">
-" t ao 10- color : .ihite ;
, ai v cl as s- l " >Tab l </ a >
, a href= "#"Ca b .. , padding : 16px ;
<dlv cla ss ="coni:ent
Cont eni: of Tab l fon t-size : 16px ;
border : none ;
</ di v>
,1 01v> .. b" i d=" ,:ab2 " >
<. oi v c lass= ,:a . d ropaown {
, a href= "#tab2 " , Tab 2</ a > po s ition : relative;
<div cla ss="coni:ent " >
d isplay : i nline-blocK ;
Cont ent of Tab2
</ di v>
.dropdown-content {
</ ai v>l - ",:ao" ia =",: ao 3" > ais play : none;
<div c ass-
, a href ="#tab3" >Tab 3</ a > positio n : absolute ;
<div c la ss=" c ontent" >
back ground - color : wnite;
Content of Tab3
min-wiOth : 160px;
</ div >
oox-shaoow : 0px Sp x 16px 0px rgoa (0,0,0 ,0 . 2);
</ OiV >
</ Oiv > z-i ndex : l ;
</ boOy >
</ html > . oropdow n- content a {
Output: color: black ;
TuU Tul2_l fil_.J padeling : 12px 16px;
Content ofTab3 text- de cora tion : none ;
a i splay : oloc k;
rm Popup Menu
A popup m enu displays several parent (top level) menu items.
}
. dro paown-content a : hover
{background-c ol or: gray;}
1 . bl ock · }
d wn -content {oisp ay · '
A popup menu appears as the visitor moves the mouse cursor over a parent menu it em. The popup . aropaown : nover . arop o d color · Blue;}
. a ropaown : hove r . dropotn {backgroun - .
menu contains chi ld menu Items that are associated with the parent menu item.
An 11em in menu can be activated either onmouseover or onclick event. Th is is an extremely versatile </ s tyl e>
drop down m e nu script for ordinary links on your page. </ he ad >
Popup menu allows you to associate a dynamic menu with regular links o n you r page including <bo dy >
image links. As the mouse m oves over the specified link. a menu pops up containing "sub links". <h 2 >Pop up Menu</n2 > th e outt on t o open t he aropaown me nu .</ P>
In foll owing exa mple we are using a container element (<d iv>) which consist o f a button and when <p >Move the mou se over
user wiU perfo r m onm ouseoverQ event on the b utton then a popup menu appears . one can use anY <Oiv class= "aropaown"> / button >
<button c l as s ="dropotn">Dropdown <
eie ment to ope n the d ropdown menu , for example. a <button> . <a > or <p > element.
Menus, Navigallon and Web Page P r ~ Sid• Serl tin Lan ua e
Cllent Side Scrt pllng Language 6.18 c11t11 1
. menu {
<di v class= "dropdown-content ">
width : 240px ·
<a href= "#" >Lin k l </ a>
height : 100%;
<a href= "#"> Link 2</ a >
<a href="#" >Link 3< / a> position : absol ute ·
</ di v> backgrouna : Blue . '
</ di v> left : -240px ; '
</ body >
</ htm l > .menu - icon
Output: padding : 10px 20 Px ;
Pop up J\fraa backgrouna : blue ·

-
color : black; '
cursor : pointer ·
float : right; '
L cl I
margin: 6px 6px 0 .
0
Lir..k !
border-radius: Spx;'

#me nu Toggle { display : none;


#m e nuToggle : checked ~ .menu { positi .
r!l!I Sliding Menu </ st yle > on . absolute; left : 0; }
The slide-in menu appears as a vertical block that floats on the left side of the web page. It seems to </ head >
come alive when the visitor moves the mouse cursor over the block or on a specific control over the <body>
page. <input type="checkbox" id="menuToggle" >
In following example, the block pulls to the right, dragging along with it the hidden menu, when the <la be 1 for= "menuToggle" class="menu-icon" >&#9776; </label>
user clicks on a menu toggle button on right side of page. The hidden menu can contain menu names <na v class="menu" >
and options. <ul>
Menu names describe a group of menu options. Menu options are selectable by the visitor. The block <li >< a href="#">FILE< / a></li>
pulls to the left, closing the menu. whenever user again click on menu toggle button on right side of <li ><a href="#">EDIT< / a>< / li>
page. <li> <a href="#" >VIEW</ a> </11>
Example: <li> <a href="#">ABOUT< / a></li>
<head > </ ul>
<title > </ title > </ na v>
</ body >
<Style >
</ html>
• { ~adding : 0; margin : 0; } Output:


body { font-family : sans-serif ;

1
a { text - decoration : none; color : black;
li { list-style-type : none; }
nav { width : 100%; text-align : center; }
na v a {
display : block;
padding : 15px 0;
la
' So
Highlighted Menu
·
.
'fl element then we could not able to figure out which
I met1mes when we move mouse of a speo IC th·s problem by highlighting the menu items
border-bottom: lpx solid #C3AA6E; e ement is triggering a specific funct10n we can soIve I
color : #F0EADC; When they get selected.
' We can highlight menu items by following two ways: menu item the browser displays a box
l Wh eoverO event over a •
nav a : ho ver { background : blue; color : black ; · en the visitor perfonn onmous f h box.
around the item with a shadow at the bottom o t e 'tern the highlight shadow appears at
na v li : last - child a { border-bottom : none ; } 2 Wh clickO event on the menu I •
en the visitor performs on fthe box
the top of the box rather than at the bottom O
id• scrl tin Lan ua e
Menus Nevi atlon and Web Pa e Protection cne~tS
Cllenl Side Serl lln Lan ua e 6.20 ul, #myUL
list-style-type :
Example: Highlighted menu. none;
<html>
#myUL {
<head >
margin : 0;
<St yle >
. lin k padding : 0;
text-dec oration : none ;
padding : 10px 16px; .c aret {
background- co l or : gray; cursor : pointer ;
font-size : 18px; user-select : none ;

. active , .l in k: hover . caret : : before {


bac kground -co l or : rea ;
content : "\ 2586";
color : white ;
color : black ;
display: inline-blocK;
</ style >
margin-right : 6px;
</ head>
<body >
. caret-down : :before {
<h l >Highlighted Menu </ hl >
<p>Move t he mouse ov er the menu items. </ p> transform : rotate (90deg );
<di v ia=" myDI V">
<a href="#file " class="l i nk ">File</ a > .nested
<a href= "#ed i t" cla ss=" l i nk" >Edit </ a > display : none ;
<a href= "#v iew" class= "link" >View</ a >
<a href= "#about " class="link" >About </ a > . active
</ di v> display : bloc k;
</ bod y>
</ htm l > </ style>
Output: </ he ad >
<body>
Highlighted Menu <h2 >Tree Menu </ h2>

···-
<ul id="myUL">
Mo'i.·c tht mouse OYet th~ menu 11ems
<li> <span class=" caret"> Topics </ span>
<ul class="nested" >
<li> Topicl </ li >

iiiuj Folding Tree Menu <li> Topic2</ li >


<li> <span c1ass-
- "caret" >Topic 3</ span>
The folding tree menu also called as cascading tree which look likes as a classic menu. Most of us <ul c1ass="nested'>
have seen such type of menu in desktop applications which help us to navigate file folders. <li >Topic3. l <fli>
The fold ing tree menu looks like a tree which consists of one or more closed folders, each of these · 3 2< /11 >
folders further consist of some menu items. <li>Topic . -"caret" >Topic3. 3< / span >
<li><span class- "
The tree expands when the visitor clicks on a closed folder, showing one or more menu options that <Ul class="nested >
are associated with the folder. <li >Topic3 . 3.1</ 11 >
Example: Folding tree menu. <li >Topic3. 3· 2</ li>
<html > <li >Topic3 . 3· 3</ ~l >
<head > <li> Topic3. 3.4</li>
<meta name= "vi ewp ort" content="width=device-width , initial -sc ale=l " > </ ul>
<Style >
5id• serf tin Lan ua a

Client Side Serl tin Lan ua e 6.22


Menus, Navl atlon and Web Pa e Protecuon c11"''
func ti on
</ 11 >
</ ul> var
• argument s [ 0
</l i > var top. arg J,tl ientx·
ument s(eJ •
</ ul> menuBox • wi nd -t lientY·
ow.docu~ '
</l i > menuBox. style -left - ent . queryselect or •
</ ul> menu Box . styl - left • "px•. ( · menu• J;
e . top _ t ,
<s c ri pt > menuBox , style .di - op • "px" ;
document . get ElementsByCla ssN ame( "car et " ) ; Sp1ay • "bl
var toggle r arguments[eJ Ock"·
· PreventDef '
var i ; menuDisplayed ault();
for ( i = 0 ; i < t ogg l er . l ength ; i++ ) { • t rue;
t oggle r[ i ). addE ve nt Liste ne r ( "c l i ck", fu nctio n ( ) {
function hide ()
t his . pa r ent Element . query Sel ect or (". nested ").c l ass l ist . t oggl e ( "act i ve") ;
{
t his . clas sL ist . t ogg le ( "c aret -down" );
i f (menuDisplayed •- t
}) ;
- rue ) {
menuBox . st yle .displa• - •
, - none";

</ sc r i pt >
</ body > </ script >
</ htm l > <St yle >
Output: . menu

Tree Menu
111idth : 150px; border-styl e: solid ; border-width :
y Top,c•
Topic ! lpx; border-color : grey ; posit i on: fi xed ; di splay: none; }
Top,<:2 .menu - item
• Toptc.3
Topdl
Topte3.1 height : 20px;
Y Top1c33
Topic.l .3 .1
Top,c33.2
T<>P1c3 .3.3 .menu-item : hover
Top,d .3.4

•¥111 Context Menu background-color : #6CBSFF ;


cursor : pointer;
The context menu appears on the web page when the vis itor clicks th e right mouse button on
anywhere on the screen.
The location of the con text menu on the screen is determin ed by t h e posit ion where visitor has </ st yle >
performed the right click operafrm on the screen. </ hea d >
The mouse cursor sets the position of the upper-left corner of the con text menu. Once the visitor <body >
takes the cursor away from t he context menu, it becomes h idden. · cont ext Henu</ h3 >
<h 3>Right click on screen to view
Example: In following example on mouse right click (known as contextmenu) we are showing context
<di v class="menu" >
m enu and on click event we are h iding it.
<div class= "menu-item", Facebook</div >
<html > <div class= "menu-item '> Twitter</div>
<head >
<hr >
<sc r ipt> . • Google</ div >
<div class="menu-item >
var men uDisplayed = fal s e ; "> Bing< / diV >
<di v class="menu-item
va r me nuBox = null ;
</ div >
wi ndow . addE ventli stener ( "conte xtmen u", show , false ) ;
</ body >
wi ndow .addE ven t l ist ener ( "cli ck " , hi de , f alse ); </ html,
Side Serl tin La n ua e
ci,,~t
Menus. Nevi atlon and Web Pa e Protection 6 25
6.24 <a href- " '
- llw1 ndo1o1s • >wi
<a href= "#help"> H ndows </ a> e Pr019ction
Output: elP<l a>
c / di v>
<h 2>ho r i zontal Scrollabl e M
cp> Re siz e t he b enuc / h2>
rowser wi ndo. to
c/ body > see the effect . </ p,
</ html >

outp:.:u.:_
t'- - - - - - -- - - -
F le Edn \ 'ie" About ;'\•'1gare Source ReE.c, o .._
m!J .Scrollable Menu . . .
I

Horizontal Scrollable Menu


Of '""' Deb,,@ l',ofil

Sometimes you want to presen t many opu ons to the visitors but
. the space
. on. webpage 1s li mned (for
example m . case o f se1ect your city from a dropdown menu) m such situ ation one can make use of
Rtuzc the brow,er wmdon· to s« th( etl'ect
scrollable menu . . .
Scrollbar is different from other menu as 1t provides two arrowheads whi ch appea r at t opnght and
bottomright ends of the visible menu. .
Initially, the scrollable menu displays a lim ited number of menu item across the web page but by
111!1 Side Bar Menu
, The side bar menu displays a menu on the side of th b
using two arrowheads which appears on right side of dropdown m enu we can select an appropnate to other web pages or to other menu options. ewe page. Options on this menu can be linked
menu item.
Side menu is different from other menus as the side bar m n · th . .
Example: . e u remains on e screen while movmg
the cursor a way f rom t h e menu item closes the popup menu and context menu.
<html >
• In followi ng example body of html page is divided into two <diV> containers where first container
<h ead > consists of s ide bar menu and second container consists of text.
<Style > , On first container, styling is applied on:
di v. s cr ollmen u
sidebar where he ight, width, position and background color are specified
bac kground-c ol or : yel low ;
<a>tag styled with no underline below the hyperlink, fontsize and color and direction
white - spa ce : nowrap ; what will be color when mouse will hover over the <a> tag is also specified
• On second container, left margin is specified which is equal to the width of the sidebar menu.
di v. scrollme nu a {
Example:
display: i nl1ne - bl ock; / •dis pl ay hori zontal• /
<htm l>
text-align : center ;
<head >
te xt-oecorati on : none ;
<Style >
</ st yle> . s i debar
</ head > height : 100%;
<body > wiath : 160px;
<di v class=" s crollmenu " > position : fixed ;
<a href="#file" >File </ a> background-color : olacK;
<a nref="#edit "> Edit </ a > padding-top : 16px;
<a href="#view " >View< / a>
<a href= "#about" >About </ a > . s i debar a {
<a href="#nav i gator" >Navigate </ a > text-decoration: none;
<a href= "#sou r ce" >Source c/ a > font-size : 20px;
<a href="#refactor "> Refa ctor </ a >
color : blue; . l *'
<a href="# run " >Run c/ a > 1•display vernca .
display : block ;
ca href= "#deb ug" >Debug </ a >
<a href= "#profile ">Profilec/ a>
.sidebar a :hover {
ca href= "#t eam " >Team </ a >
color: white ;
ca href= "ltt oo l s" >Tool s< / a >
Sid• scrl tm La n uo e
c11en1
Cllen\ Side Scripting Language 6.26 Menus, N1vlg1tlon and Web Page Protect1~
output:
.ma in { Jtlgll I cllc.k OD SCl'ttlJ., Coatttt 1'fta
margin-left : lG0px ; ; • same as the widt h of the sidebar• ; ~btaultd
padding : 0p x 10px;
you c1n ,itw Sourct or Wtbpact
</ style > I
</ heao > vou can place obstacles in thew
' . ay of an intrud
<body > 1. Disable n ght Mouse button on b . erby oneoftwo ways to:-;h:-:-.d: - - - -- - -- -
<di v class• "sidebar "> the context menu. This hidesbwthe site so the visitor can't aco• th 1 e source code:
O your HTML ""'ss e View sou
<a nref•"#home" >Home </ a> 2 You can store your JavaScript COde and Your Javas . rce menu option on
· COde on your w b cnpt from the visitor
ca nref• "~departments ">Departments c/ a> The browser calls the Javascn e server instead ofbuil•·- . ·
. pt Code from the b w.ug It into your web page
ca href• "#achievements ">Ach i evements </ a> L'sing this method. the Javascnpt od . we server when it is needed b• ·
ca href• "#c on tact ">Contact c/ a> source code for the web page c e IS not visible to the visitor even i' f theyyoutr w~b page.
VI.SI or views the

11!1 Disabling the Right MouseButton


• •
</ div >
cd1v class • "main "> , The followi ng example shows you how to d' bl h . .
<h2 >Sidebar Menu c/ h2 > 1sa et e VlSlt ,5 · h
displays your web page. or ng t mouse bunon while the browser
c/ oiv> , All the action occurs in the JavaScript that is defi d. h
</ body> me mt e <head> tag of the web page.
Example:
<html >
<head >
Sidebar Menu <sc r ipt >
wind ow. onload • function () (
document . addE ventListener{ "context1:1enu", function {e) {
e. prevent Defaul t {);
}, false );}

Ill PROTECTING WEB PAGE


</ sc ript >
<body >
As already we have seen security concerns of JavaScnpt and we are aware that anyone with a little cn 3>Right click on screen, Cont ext Menu is disabled</h3 >
computer knowledge can use a few mouse clicks to display your HTML code , including your </ Dody>
JavaScript code on the screen. </ htm l>
Although you cannot entirely prevent intruders to view our web page, but can take a few steps to
Output:
stop all but the best computer wizards from gain'ng access to your JavaScript.
ml Hiding Your Source Code Right click on scrttn, Contttt Menu Is dbabkd

rm
Every developer has to adm it that, on occasion , they have peeked at the code of a web page by using
right -clicking on webpage and choosing "View Source" option from the context menu.
Example:
Hiding JavaScript d JavaScript code internally in html
, . f d velopers. we have use
Here, in all chapters for convenience O e .
<ht ml > • . ·ry of web page.
file but this approach hampers the seC\Jn . fa web page then he/she would also
<head> . . .sable to view the source o
Lets consider by any mean if intruder i_ edded inside the page also.
<body> able to view the JavaScript code which is emb . ode In ext.emal file and save th;.t file with .js
ch3>Ri gnt click on screen , Context Menu is Enabled c/ h3 > . ·te JavaScnpt c f. der would able to see the
So 1t is always recommended to wn ebpage. In this case •1 mtru ~...;pt.
c':lr> e . al file In you w ce code for die Java=,
xtens1on and refer that extern d not be able·to see the sour . . t code and referring
ch 3>You can i ew Source of Webpage c/ 3> source code web page then he/she woul . file which consJ.St of 1avascnP
</ body> . a mycode.JS
In foUoWing example we are creating
</ h l> that fi1l e in
· our webpage in<
· script> rag.

. .,
~ . 6.~
Menus. Navl atlon and Web Pa e Protaellon ailtO link is a type of HTML link that . 11
"'"'· Nh, Ion and Web Pa
6.28 M ·1 a<:11va1es th d
an e-rna1 . e efa t man client th
web browser requires a defa on e romputer for sending
"Example: rne u1t e-mai di
webpage1.html ·vate the e-mail client. If O h en software install .
acu ·11 li k ·u y u ave Microsoft Out! ed on his/ her com puter in order to
<h t ml > ssi n g a ma1 o n w1 open a oo for exa l
<head > • type= "t ext / java sc ript " >
pre new ma·1 Window. · mp e as your de fault mail client.
. lang uage= " Ja va script El'amPle:
<s c r ipt s rc =" mycooe . J S '
</ sc ript> <html >
<body> Context Me nu is di sab l ed </ h3 > <hea o >
<h3>Right cli ck on s c re en ,
< s c r i pt language =Javascr i pt >
</ body >
</ ht ml > fu nction ma kelink ()
mycode.js
wind ow. onl oad = func t ion () v ar str= ' mailto : ;
fun ct i on ( e)
document . a od EventListene r ( .. context me nu ' str = str + St ring. fromCharCode (l09 , 97 , 105 , 108, 116 , 111, 58 );
I I first part of t he address
e . pre ventDef au l t () ; st r = str + St r ing .fr omCharCoae ( l 09, 101 ) ;
), fal se ) ;
I I t he at sign

Output: str = str + St rin g. fr omCharCod e(64 ) ;

IRigbt rHck on screen, Context Menu Is disabled \ I I the doma i n part


st r = str + St r ing . fromCharcoae ( l09 , 121 , 100 , 111 , 109 , 97 , 105, 110,
11!1 Concealing E-mail Address . 46, 99 , 111, 109 ) ;

we all receive spam mail in our inbox and we think that such ma_1ls are sent by merchants but how window. location . nr ef=st r;
did they get our e-mail address. The reason behind this is our email addresses are captured by Spam-
Crawlers and Span1-Bots.
some spammers create programs called spam-bots or spam-crawler that surf the internet and look </ script>
for email addresses which are embedded inside the webpages. </ he ad >
Your web site might be contributing in how much junk mail you receive, especially if you include an
<bo o y >
email address on your pages so we ourselves are the culprit who invites the spa m mer to steal our
email address from webpages. < in p ut ty pe =" button" value= "Send" onc li ck='"makel i nk() ">
The majority of spam bots crawl the net in search of e-mail addresses in plain text such as: </ body >
me@mydomain.com
</ htm l>
During surfing over the internet such bot or crawler look for two things:
Out put:
1. mailto: attribute that tells the browser the e-mail address to u se when the visitor wants to
respond to the web page.
2. the@ sign that is required for all e-mail addresses.
One way of making it more difficult for a spam bot to find your email address is to conceai your
email address within your page. This is where JavaScript comes in useful; being a client side
scri pting language your scripts are sent to the client and left t o their web browser t o execute. It is
possi ble to write a script that gets the browser to generate a m ailto lin k with you r e -ma il a ddress in
without sendi ng it in plain text.
Our job is to confuse the bots by using a JavaScript code to generat e th e e-m a il address dyn amically.
The solution to this common problem is to conceal your e-mail address in t he source code of your
web page so that bots can't fi nd it but so that it still appears on t he web page.
In following example r ather t han di rectly sendin g me@mydom ai n .com . we conceal the e-mail
-- ------- _.--
address using javascript and when user click on a button then a m ailto dialogbox will ap pear .
Sid• scrt t in Lan ua
cti•~1
Menus, Navigation and Web Page Protection
Cllem Slde 51:np "ll Lllnguage 6.30
pros: . .
(I.) virtual DOM which itnproves a
. , , FRAMEWORKS OF JAVASCRIPT AND rrs APPIJCATION . . . (ii) can be used on client and Pps llerfonnan
• A software framework 1s an abst rac. ion m which software providing generi c functionality can be
.
b e use d with server sid ce.
(iii) can other f . e.
rameworks
sele~Jvely changed by add ition al user-written code. (iV) Readable component and da .
· li t. framework written in JavaScript where the programmers ta Patterns.
JavaScript f ramework 1s an app ca 10n .
can manipula.e the func tions and use t hem for their convemenc_e . . . . cons:
· f rarn ewor k 1·s an applicati· on framework wr itten m JavaScript. JavaScript 1s a multi- (i) AS React uses only View la
A JavaScript . tf d Yerofthe
too 1m~ se or eveloprnent. app, You need to th '
paradigm language.
· funct ion al. and ob3·ect-orient ed and prototype-based (ii) sometimes feels awkward t d tnltofothertechnologyt0
It supports event -d nve n, . . programming . o evelopers as . get a complete
styles. JavaScript is used for cllent side programming as well as used as a server-side progra m ming ~ MeteorJS : it uses ;~"-
~· uu1.ue teinptat
language. • The application area of Meteor (M esandJSX.
As techno gy advances everyday, t here are variou s framework _ a vailable to work with covers almost the major portion /thteor.js or MeteorJS) serv th
0
javascripcFrameworks are more adaptable fo r the designing of webs ites and hence, they are . . e software d es e name itself · . .
Meteor ships with a variety of USeful. evelopment smce 1t IS vaned as it
preierred by most of the website developers. allows the inclusion of custom pack smart Packages' readily ·~" -
JavaScript fram ew rks are a type of tool that makes working with JavaScript easier and smoother. ages as Well t th a, ......b!e for all m
Back-e nd development, managem or osewhowishtocr th . annerofuses, and
Following are the most frequent and popularly used framework used by programmer to code the f h b . ent of the datab eate ell' own
part o t e we sites are a major are h ase, business logic d . ·
applicati n as device responsive aw ere Meteor framework . an rendenng of the front-end
PrOS : IS used.
1- AngularJS:
Angular s is a ne of the most powerful. efficient, and open-source JavaS cr ipt framework. (i) Very simple and easy to understand.
AngularJS fram ew rk is operated by the Google and is basically implemented to use fo r developing (ii) Meteor apps are real time by default.
Single Page Application (SPA). (iii) 0 fficial and community packages h .
. are uge time saver.
It extends the HTML mto the application and interprets the attributes in order to perform data (1v) Need only JavaScript for client and d
bind'n g. seiver evelopment
Cons:
Angular is full of useful features such as dependency injection, templates, forms , and m ore.
(i) Not suitable for large and complex applications.
Pros :
4. Node.js:
(l) tis fully extensible and works well with other libraries.
1i) Every feature can be modified r replaced to suit your u nique development workflow and • Node.js is a server-side JavaScript run-time environment, which works on cross p'atforms and is
open -source . •
feature needs.
(iii) Code production is omparatively fast. • The fram ework is capable of driving asynchronous 1/0 with its event-driven architecture.
(i v) Every piece f a ppli ti n was eas ily testable. • It works in t.he JavaScript Runtime environment and hence shows similar properties of JAVA Uk!
thread in g, packages, forming ofloops.
(v) Two wa y binding. It means changes in the backend are immediately reflected on the Ul.
Pros:
(vi) An ar JS improves server perf rm ance. It means that the server performs extremely well
thanks t reduced traffic and because it only serves static fields and responds to the AP! calls. (i) Asynchronous and event driven.
(vii) An ar JS is highly testable. By all wing unit testing and end-t o- end testing , it makes testing (ii) Very fast .
and debug ging much simpler than you can imagine. (iii) Single t hreaded but highly scalable.
Cons: (iv) No buffering .
(i) Poss ible ·m e consumption. Cons,
(ii Difiic t earning (i) Not suitable for CPU intensive applications, large and complicated web applications.
iii) JavaScript is mandatory. (ii) It is not consistent.
2. ReactJS: (iii) Does not support relational database. f d allb cks
React framework that was origi nally created, and is maintained, by Facebook. (iv) It is essential to use a callback end up every time with a bulk o neste c a .
Rea JS rovides a huge weight on the scales when choosing it for a project. It gives React a sense of
S. Backbon ·
e .Js: ks It . very easy to understand and learn. It can be
sta bility t.hat m a ny new frameworks lack. It is one of the most famous JavaScript framewor . is
In fa . it is used to develop and operate the dynamic User Interface of the web oages with high Used to create Single Page Applications. . th tall the sen·er-side functions must fl w
i hi f I ·n mind the idea a 'tl I cod
incoming traffi . · s ramework was made by keep ng 1 . • lex function lilies by wn ng ess e.
through an AP! which would help in achieving comp_ d minimalis m, but it is still a relevun
I! mak es the use fa vi ual DOM and hence, the integration of the same with any application is Ba kb ' haps due to its age an
easier c 0 ne is declining in popularity, per
and Powerful tool for the right needs.
Menus, Navigation and Web Page Protect!~
Client Side Scripting Language 6.32

Pros:
(i) Event driven communication between views and model. t' Uy updates the HTML of your
(ii) Syncing with back-end: When a model ch anges, it automa 1ca
application.
(iii) Maintainability by following convent~ons: . a lications in well-structured and an
(iv) Allows creating client side web appbcatwns or mobi1e pp
organized format.
Cons:
(i) Not suitable for complex applications.

1. What is status bar?


2. How to create status bar in JavaScript?
3. What is banner?
4. What is menu in JavaScript?
5. With the help of example explain following terms:
(i) Changing the message using rollover
(ii) Moving the message along the status bar.
6. How to load and display banner in JavaScript?
7. What is slideshow? Explain with example.
8. Describe the terms creating a pull down menu and dynamically changing a menu with example.
9. What is context menu? How to create it? Explain with example.
10. Describe pop-up menu in detail.
11. How to protecting web page?
12. Describe floating menu in detail.
13. How to hiding code in JavaScript?
14. Describe linking a banner advertisement to URL with example.
15. Explain validating menu selection in detail.
16. Compare pop-up menu and context menu.
17. Describe the term sliding menu in detail.
18. Enlist frameworks of JavaScript and its applications.

•••

r .

·,
I

You might also like