Professional Documents
Culture Documents
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 ('
Ii:~.
1
~ ~ ~~ ~
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
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 .
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,,
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 ~
~~~~!.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,
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 .
--<
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
,\.!.-f ""1.. n ,. _ _
Boslcs ol JovaSc~
1.22
Clle'2.!_Sloe Scripting Language Basics o t JavaScn t Pro remm,n
(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 =
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
~
1.30 -
~c~11~
,n~t~S~ld~e~S~cr~lp~l~ln~9ll•~n~g~ua~9~•-------------
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.
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~ ... - -
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>
~_ 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
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 />") ;
~~
. ( "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.
•••
,,
[ 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
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
""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
</ 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 ,
, _ #
~<
===========~==========-~ ~~~ ~~~~ ~:: : :-
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);
---
same va r iable name can be use m d ifferent functions without con fli ct.
/ 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 ·
-
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
< / 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 \
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 "
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
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"
..,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.
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
<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
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 );
;:· 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);
.... 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 )
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.
- ...... . :.,~ ·-:-~::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: ,
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 )
First · ame:,)nee---"a_kshi
_.,·- - - - - ~
I Fruiis j I Vegetables Last Name: ~
Email: L-- ' - ~ ~ ~ ~ ~ - - '
- -I
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,
...............
Client Side Sc ri p ti ng Langu n "
·
-----. 4 2
.
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,
do cument .coo ie = "Name= " . pe r s on . va l ue • "; exp i res= " T d. t oG St rin g ();
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·
~
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.
/ 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. . . ~ ' "
• ,.~ t •.,,... , </.: .. "/~~ ;. .•:.-., ·: ... ': l"J.Y '~.. ,. ,,...,:-n,~ ... ,,,,..,..,·.. ~, ~E.~·1:...·:•:r·,:"//.."'
, ~1
. ;,. .. ,
; • "/ , ; , · ~ · . ,.., .., , ~ .. fl , ... / .. · , ; · . , -~· · : . . ~/ , , f ( , , ~ .. 1--:~~
G
,,,. , . ,.,,,,: ,;..,.,,• ...ri..s.-· .. ,,., .. _.,,, ':.,,,,·· : ~ ••• ' ' / : ""/,,n "/~,,, ,,
l ,f' '+",,,."- "'/ ;""!,.J ;,••r::, · ' ;., .. _., ",:,"","," •,'' ',- ,, ,,, , ,; -'/ /C•
.. ', - ~- ..
''/A , • ..;_,,, ';." • •,. ,',/'~ . 1./4°1-1 ,
'lf•j , • , ; ,; ,, ,:",',.,,J,, ·"' 1, ' '1( .-,,,~•,, ' ' "',,,,..<I
< 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;
_J I ~-
',,,_ ::.
.Ex.amp "
,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 ,
"' ·>:..: ~:,.:. ·' "'': . ,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 )
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 ';
-_-._-.. :._ _-· ~~-
-::=.:-
_---.;:- --= -
=-
~= =~
- - -~ - -::=- ~= -=-=-=
-- ~ : ..
- .. - =:- :
--:.,... :_:- - ,~
_€' · ~ - - .:.- ~ - - -
---
• 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
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.
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. '
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.
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 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
1·
I ~ p,g
I
I 1
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
\\ e b pa ge 3 Web page 4
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
--
</ 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 >
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
~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
document - img1 . src = Ba Menus, Nav, ation and Web Pa e Protec tion
set Timeou t (.. nne" s [ count J·
rotate () ", 1000); '
WfB TECHNOLOG~
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,;,,, ,..,..,.,.
·"'·~~.
·, .
, '/,,~I'
.. --
·- -
.. .; .. ~ ~.!
.:·,.:. .(.. ~ 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>
..
I Sub~ ~ esetj solution:
Sti t , our fa, o uu1c fnut Frutt.s Name 1
loc• lhosr SOOO soys
for (i = 1; i
{ <= electemp . lenDT h,·
... i++ )
· 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
. ,
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;'
•
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 ;
···-
<ul id="myUL">
Mo'i.·c tht mouse OYet th~ menu 11ems
<li> <span class=" caret"> Topics </ span>
<ul class="nested" >
<li> Topicl </ li >
</ 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
outp:.:u.:_
t'- - - - - - -- - - -
F le Edn \ 'ie" About ;'\•'1gare Source ReE.c, o .._
m!J .Scrollable Menu . . .
I
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
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
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.
•••
r .
·,
I