Sunteți pe pagina 1din 116

Web Tech Notes FX Engineering

College, Tirunelveli
Unit1
List
HTML Unordered Lists
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
The list items are marked with bullets (tyically small black circles!.
<ul>
<li>"o##ee<$li>
<li>Milk<$li>
<$ul>
How the HTML code abo%e looks in a browser&
"o##ee
Milk
HTML 'rdered Lists
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items are marked with numbers.
<ol>
<li>"o##ee<$li>
<li>Milk<$li>
<$ol>
How the HTML code abo%e looks in a browser&
(. "o##ee
). Milk
HTML *e#inition Lists
A de#inition list is a list o# items+ with a descrition o# each item.
The <dl> tag de#ines a de#inition list.
The <dl> tag is used in con,unction with <dt> (de#ines the item in the list! and <dd> (describes the
item in the list!&
1
Web Tech Notes FX Engineering
College, Tirunelveli
<dl>
<dt>"o##ee<$dt>
<dd>- black hot drink<$dd>
<dt>Milk<$dt>
<dd>- white cold drink<$dd>
<$dl>
How the HTML code abo%e looks in a browser&
"o##ee
- black hot drink
Milk
- white cold drink
TABLE
HTML Tables
Tables are de#ined with the <table> tag.
A table is di%ided into rows (with the <tr> tag!+ and each row is di%ided into data cells (with the <td>
tag!. td stands #or .table data+. and holds the content o# a data cell. A <td> tag can contain te/t+
links+ images+ lists+ #orms+ other tables+ etc.
Table E/amle
<table border0.(.>
<tr>
<td>row (+ cell (<$td>
<td>row (+ cell )<$td>
<$tr>
<tr>
<td>row )+ cell (<$td>
<td>row )+ cell )<$td>
<$tr>
<$table>
How the HTML code abo%e looks in a browser&
row (+ cell ( row (+ cell )
row )+ cell ( row )+ cell )
HTML Tables and the 1order Attribute
2# you do not seci#y a border attribute+ the table will be dislayed without borders. 3ometimes this
can be use#ul+ but most o# the time+ we want the borders to show.
To dislay a table with borders+ seci#y the border attribute&
2
Web Tech Notes FX Engineering
College, Tirunelveli
<table border0.(.>
<tr>
<td>4ow (+ cell (<$td>
<td>4ow (+ cell )<$td>
<$tr>
<$table>
HTML Table Headers
Header in#ormation in a table are de#ined with the <th> tag.
All ma,or browsers will dislay the te/t in the <th> element as bold and centered.
<table border0.(.>
<tr>
<th>Header (<$th>
<th>Header )<$th>
<$tr>
<tr>
<td>row (+ cell (<$td>
<td>row (+ cell )<$td>
<$tr>
<tr>
<td>row )+ cell (<$td>
<td>row )+ cell )<$td>
<$tr>
<$table>
How the HTML code abo%e looks in your browser&
Header 1 Header 2
row (+ cell ( row (+ cell )
row )+ cell ( row )+ cell )
table backgrounds
adding color and graphics
its easy to add colors and graphics to tables
need help with colors? try this useful tool (new window)
my first
table
my first
table
3
Web Tech Notes FX Engineering
College, Tirunelveli
my first
table
my first
table
all we have to do is add the bgcolor attribute to our <TABLE> and <T> tags
my first table my first table

the code above gives us this
my first table my first table
the bac!ground color of the entire table is set to white ("######) in the table tag
<TABLE border$% bgcolor$"######>
it is e&ually si'ple to add a bac!ground i'age using the bac!ground attribute
<TABLE border$% bac!ground$(raindrop)*pg(>
my first table my first table
it+s *ust as si'ple to add color and graphics to the <T> tags
<T bac!ground$(raindrop)*pg(> <T bgcolor$",,##,,>
my first
table
my first
table
my first
table
my first
table
the raindro bac!ground
rightclic! on it and save it
"
Web Tech Notes FX Engineering
College, Tirunelveli
raindro#$g
FRAMES
HTML 5rames
6ith #rames+ you can dislay more than one HTML document in the same browser window. Each
HTML document is called a #rame+ and each #rame is indeendent o# the others.
The disad%antages o# using #rames are&
5rames are not e/ected to be suorted in #uture %ersions o# HTML
5rames are di##icult to use. (7rinting the entire age is di##icult!.
The web de%eloer must kee track o# more HTML documents
The HTML #rameset Element
The #rameset element holds one or more #rame elements. Each #rame element can hold a searate
document.
The #rameset element states H'6 MA89 columns or rows there will be in the #rameset+ and H'6
MU"H ercentage$i/els o# sace will occuy each o# them.
The HTML #rame Element
The <#rame> tag de#ines one articular window (#rame! within a #rameset.
2n the e/amle below we ha%e a #rameset with two columns.
The #irst column is set to ):; o# the width o# the browser window. The second column is set to <:;
o# the width o# the browser window. The document .#rame=a.htm. is ut into the #irst column+ and
the document .#rame=b.htm. is ut into the second column&
<#rameset cols0.):;+<:;.>
<#rame src0.#rame=a.htm. $>
<#rame src0.#rame=b.htm. $>
<$#rameset>
Note: The #rameset column si>e can also be set in i/els (cols0.)??+:??.!+ and one o# the columns
can be set to use the remaining sace+ with an asterisk (cols0.):;+@.!.
1asic 8otes - Use#ul Tis
%
Web Tech Notes FX Engineering
College, Tirunelveli
Tip: 2# a #rame has %isible borders+ the user can resi>e it by dragging the border. To re%ent a user
#rom doing this+ you can add noresi>e0.noresi>e. to the <#rame> tag.
Note: Add the <no#rames> tag #or browsers that do not suort #rames.
Important: 9ou cannot use the <body><$body> tags together with the <#rameset><$#rameset>
tagsA Howe%er+ i# you add a <no#rames> tag containing some te/t #or browsers that do not suort
#rames+ you will ha%e to enclose the te/t in <body><$body> tagsA 3ee how it is done in the #irst
e/amle below.
HTML frames allow authors to present documents in multiple views, which may be
independent windows or subwindows. Multiple views offer designers a way to keep
certain information visible, while other views are scrolled or replaced. For example,
within the same window, one frame might display a static banner, a second a
navigation menu, and a third the main document that can be scrolled through or
replaced by navigating in the second frame.
Here is a simple frame document
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Framese//E!"
""#$//%%%.%3.&r'/T(/"m)4/*ramese.++",
<HTML,
<HE-D,
<TITLE,- s.m#)e *ramese +&/0me1</TITLE,
</HE-D,
<F(-ME2ET /&)s3"4056 705",
<F(-ME2ET r&%s3"1006 400",
<F(-ME sr/3"/&1e1s8&*8*rame1."m)",
<F(-ME sr/3"/&1e1s8&*8*rame4.'.*",
</F(-ME2ET,
<F(-ME sr/3"/&1e1s8&*8*rame3."m)",
<!OF(-ME2,
<P,T".s *ramese +&/0me1 /&1a.1s$
<UL,
<LI,<- "re*3"/&1e1s8&*8*rame1."m)",2&me 1ea /&1e1s</-,
<LI,<IM9 sr/3"/&1e1s8&*8*rame4.'.*" a)3"- 1ea .ma'e",
<LI,<- "re*3"/&1e1s8&*8*rame3."m)",2&me &"er 1ea /&1e1s</-,
</UL,
</!OF(-ME2,
</F(-ME2ET,
</HTML,
that might create a frame layout something like this
---------------------------------------
: : :
: : :
: Frame 1 : :
: : :
: : :
&
Web Tech Notes FX Engineering
College, Tirunelveli
:---------: :
: : Frame 3 :
: : :
: : :
: : :
: Frame 4 : :
: : :
: : :
: : :
: : :
---------------------------------------
IFRAME
HTML Iframes
' (revious Ne)t Chater *
An i#rame is used to dislay a web age within a web age.
Syntax for adding an iframe:
<i#rame src0.URL.><$i#rame>
The U4L oints to the location o# the searate age.
2#rame - 3et Height and 6idth
The height and width attributes are used to seci#y the height and width o# the i#rame.
The attribute %alues are seci#ied in i/els by de#ault+ but they can also be in ercent (like .B?;.!.
E/amle
<i#rame src0.demo=i#rame.htm. width0.)??. height0.)??.><$i#rame>
Try it yourself
2#rame - 4emo%e the 1order
+
Web Tech Notes FX Engineering
College, Tirunelveli
The #rameborder attribute seci#ies whether or not to dislay a border around the i#rame.
3et the attribute %alue to .?. to remo%e the border&
E/amle
<i#rame src0.demo=i#rame.htm. #rameborder0.?.><$i#rame>
Try it yourself
Use i#rame as a Target #or a Link
An i#rame can be used as the target #rame #or a link.
The target attribute o# a link must re#er to the name attribute o# the i#rame&
E/amle
<i#rame src0.demo=i#rame.htm. name0.i#rame=a.><$i#rame>
<><a hre#0.htt&$$www.wCschools.com. target0.i#rame=a.>6C3chools.com<$a><$>
Try it yourself
HTML i#rame Tag
Tag Description
,iframe- *e#ines an inline sub window (#rame!
FORMS
HTML 5orms
HTML #orms are used to ass data to a ser%er.
A #orm can contain inut elements like te/t #ields+ checkbo/es+ radio-buttons+ submit buttons and
more. A #orm can also contain select lists+ te/tarea+ #ieldset+ legend+ and label elements.
.
Web Tech Notes FX Engineering
College, Tirunelveli
The <#orm> tag is used to create an HTML #orm&
<#orm>
.
input elements
.
<$#orm>
HTML 5orms - The 2nut Element
The most imortant #orm element is the inut element.
The inut element is used to select user in#ormation.
An inut element can %ary in many ways+ deending on the tye attribute. An inut element can be
o# tye te/t #ield+ checkbo/+ assword+ radio button+ submit button+ and more.
The most used inut tyes are described below.
Te/t 5ields
<inut tye0.te/t. $> de#ines a one-line inut #ield that a user can enter te/t into&
<#orm>
5irst name& <inut tye0.te/t. name0.#irstname. $><br $>
Last name& <inut tye0.te/t. name0.lastname. $>
<$#orm>
How the HTML code abo%e looks in a browser&
5irst name&
Last name&
Note: The #orm itsel# is not %isible. Also note that the de#ault width o# a te/t #ield is )? characters.
7assword 5ield
<inut tye0.assword. $> de#ines a assword #ield&
<#orm>
7assword& <inut tye0.assword. name0.wd. $>
<$#orm>
How the HTML code abo%e looks in a browser&
/
Web Tech Notes FX Engineering
College, Tirunelveli
7assword&
Note: The characters in a assword #ield are masked (shown as asterisks or circles!.
4adio 1uttons
<inut tye0.radio. $> de#ines a radio button. 4adio buttons let a user select '8L9 '8E one o# a
limited number o# choices&
<#orm>
<inut tye0.radio. name0.se/. %alue0.male. $> Male<br $>
<inut tye0.radio. name0.se/. %alue0.#emale. $> 5emale
<$#orm>
How the HTML code abo%e looks in a browser&
Male
5emale
"heckbo/es
<inut tye0.checkbo/. $> de#ines a checkbo/. "heckbo/es let a user select '8E or M'4E otions o#
a limited number o# choices.
<#orm>
<inut tye0.checkbo/. name0.%ehicle. %alue0.1ike. $> 2 ha%e a bike<br $>
<inut tye0.checkbo/. name0.%ehicle. %alue0."ar. $> 2 ha%e a car
<$#orm>
How the HTML code abo%e looks in a browser&
2 ha%e a bike
2 ha%e a car
3ubmit 1utton
<inut tye0.submit. $> de#ines a submit button.
A submit button is used to send #orm data to a ser%er. The data is sent to the age seci#ied in the
#ormDs action attribute. The #ile de#ined in the action attribute usually does something with the
recei%ed inut&
<#orm name0.inut. action0.html=#orm=action.as. method0.get.>
Username& <inut tye0.te/t. name0.user. $>
<inut tye0.submit. %alue0.3ubmit. $>
10
Web Tech Notes FX Engineering
College, Tirunelveli
<$#orm>
How the HTML code abo%e looks in a browser&
Username&
!ubmit
2# you tye some characters in the te/t #ield abo%e+ and click the .3ubmit. button+ the browser will
send your inut to a age called .html=#orm=action.as.. The age will show you the recei%ed inut.
UNIT 2
CSS SYNTAX
"33 3ynta/
A "33 rule has two main arts& a selector+ and one or more declarations&
11
Web Tech Notes FX Engineering
College, Tirunelveli
The selector is normally the HTML element you want to style.
Each declaration consists o# a roerty and a %alue.
The roerty is the style attribute you want to change. Each roerty has a %alue.
"33 E/amle
"33 declarations always ends with a semicolon+ and declaration grous are surrounded by curly
brackets&
Ecolor&redFte/t-align&centerFG
To make the "33 more readable+ you can ut one declaration on each line+ like this&
E/amle

E
color&redF
te/t-align&centerF
G
Try it yourself
"33 "omments
"omments are used to e/lain your code+ and may hel you when you edit the source code at a later
date. "omments are ignored by browsers.
A "33 comment begins with .$@.+ and ends with .@$.+ like this&
$@This is a comment@$

E
te/t-align&centerF
$@This is another comment@$
color&blackF
#ont-#amily&arialF
12
Web Tech Notes FX Engineering
College, Tirunelveli
G
The id and class 3electors
2n addition to setting a style #or a HTML element+ "33 allows you to seci#y your own selectors called
.id. and .class..
The id 3elector
The id selector is used to seci#y a style #or a single+ uniHue element.
The id selector uses the id attribute o# the HTML element+ and is de#ined with a .I..
The style rule below will be alied to the element with id0.ara(.&
E/amle
Iara(
E
te/t-align&centerF
color&redF
G
Try it yourself
*o NOT start an 2* name with a numberA 2t will not work in Mo>illa$5ire#o/.
The class 3elector
The class selector is used to seci#y a style #or a grou o# elements. Unlike the id selector+ the class
selector is most o#ten used on se%eral elements.
This allows you to set a articular style #or any HTML elements with the same class.
The class selector uses the HTML class attribute+ and is de#ined with a ...
2n the e/amle below+ all HTML elements with class0.center. will be center-aligned&
E/amle
.center Ete/t-align&centerFG
Try it yourself
13
Web Tech Notes FX Engineering
College, Tirunelveli
9ou can also seci#y that only seci#ic HTML elements should be a##ected by a class.
2n the e/amle below+ all elements with class0.center. will be center-aligned&
E/amle
.center Ete/t-align&centerFG
Try it yourself
*o NOT start a class name with a numberA This is only suorted in 2nternet E/lorer
Three 6ays to 2nsert "33
There are three ways o# inserting a style sheet&
E/ternal style sheet
2nternal style sheet
2nline style
E/ternal 3tyle 3heet
An e/ternal style sheet is ideal when the style is alied to many ages. 6ith an e/ternal style sheet+
you can change the look o# an entire 6eb site by changing one #ile. Each age must link to the style
sheet using the <link> tag. The <link> tag goes inside the head section&
<head>
<link rel0.stylesheet. tye0.te/t$css. hre#0.mystyle.css. $>
<$head>
An e/ternal style sheet can be written in any te/t editor. The #ile should not contain any html tags.
9our style sheet should be sa%ed with a .css e/tension. An e/amle o# a style sheet #ile is shown
below&
hr Ecolor&siennaFG
Emargin-le#t&)?/FG
body Ebackground-image&url(.images$backJ?.gi#.!FG
*o not lea%e saces between the roerty %alue and the unitsA .margin-le#t&)? /. (instead o#
.margin-le#t&)?/.! will work in 2E+ but not in 5ire#o/ or 'era.
2nternal 3tyle 3heet
1"
Web Tech Notes FX Engineering
College, Tirunelveli
An internal style sheet should be used when a single document has a uniHue style. 9ou de#ine internal
styles in the head section o# an HTML age+ by using the <style> tag+ like this&
<head>
<style tye0.te/t$css.>
hr Ecolor&siennaFG
Emargin-le#t&)?/FG
body Ebackground-image&url(.images$backJ?.gi#.!FG
<$style>
<$head>
2nline 3tyles
An inline style loses many o# the ad%antages o# style sheets by mi/ing content with resentation. Use
this method saringlyA
To use inline styles you use the style attribute in the rele%ant tag. The style attribute can contain any
"33 roerty. The e/amle shows how to change the color and the le#t margin o# a aragrah&
< style0.color&siennaFmargin-le#t&)?/.>This is a aragrah.<$>
Multile 3tyle 3heets
2# some roerties ha%e been set #or the same selector in di##erent style sheets+ the %alues will be
inherited #rom the more seci#ic style sheet.
5or e/amle+ an e/ternal style sheet has these roerties #or the hC selector&
hC
E
color&redF
te/t-align&le#tF
#ont-si>e&BtF
G
And an internal style sheet has these roerties #or the hC selector&
hC
E
te/t-align&rightF
#ont-si>e&)?tF
G
1%
Web Tech Notes FX Engineering
College, Tirunelveli
2# the age with the internal style sheet also links to the e/ternal style sheet the roerties #or hC will
be&
color&redF
te/t-align&rightF
#ont-si>e&)?tF
The color is inherited #rom the e/ternal style sheet and the te/t-alignment and the #ont-si>e is
relaced by the internal style sheet.
Multile 3tyles 6ill "ascade into 'ne
3tyles can be seci#ied&
inside an HTML element
inside the head section o# an HTML age
in an e/ternal "33 #ile
Tip: E%en multile e/ternal style sheets can be re#erenced inside a single HTML document.
Cascading order
6hat style will be used when there is more than one style seci#ied #or an HTML elementK
Lenerally seaking we can say that all the styles will .cascade. into a new .%irtual. style sheet by the
#ollowing rules+ where number #our has the highest riority&
(. 1rowser de#ault
). E/ternal style sheet
C. 2nternal style sheet (in the head section!
J. 2nline style (inside an HTML element!
3o+ an inline style (inside an HTML element! has the highest riority+ which means that it will o%erride
a style de#ined inside the <head> tag+ or in an e/ternal style sheet+ or in a browser (a de#ault %alue!.
Note: 2# the link to the e/ternal style sheet is laced a#ter the internal style sheet in HTML
<head>+ the e/ternal style sheet will o%erride the internal style sheetA
CSS Background
' (revious Ne)t Chater *
1&
Web Tech Notes FX Engineering
College, Tirunelveli
"33 background roerties are used to de#ine the background e##ects o# an
element.
"33 roerties used #or background e##ects&
background-color
background-image
background-reeat
background-attachment
background-osition
1ackground "olor
The background-color roerty seci#ies the background color o# an element.
The background color o# a age is de#ined in the body selector&
E/amle
body Ebackground-color&Ib?cJdeFG
Try it yourself
The background color can be seci#ied by&
name - a color name+ like .red.
4L1 - an 4L1 %alue+ like .rgb()::+?+?!.
He/ - a he/ %alue+ like .I##????.
2n the e/amle below+ the h(+ + and di% elements ha%e di##erent background colors&
E/amle
h( Ebackground-color&IMJN:edFG
Ebackground-color&Ie?####FG
di% Ebackground-color&Ib?cJdeFG
Try it yourself
1+
Web Tech Notes FX Engineering
College, Tirunelveli
1ackground 2mage
The background-image roerty seci#ies an image to use as the background o# an element.
1y de#ault+ the image is reeated so it co%ers the entire element.
The background image #or a age can be set like this&
E/amle
body Ebackground-image&url(Daer.gi#D!FG
Try it yourself
1elow is an e/amle o# a bad combination o# te/t and background image. The te/t is almost not
readable&
E/amle
body Ebackground-image&url(Dbgdesert.,gD!FG
Try it yourself
1ackground 2mage - 4eeat Hori>ontally or Oertically
1y de#ault+ the background-image roerty reeats an image both hori>ontally and %ertically.
3ome images should be reeated only hori>ontally or %ertically+ or they will look strange+ like this&
E/amle
body
E
background-image&url(Dgradient).ngD!F
G
Try it yourself
2# the image is reeated only hori>ontally (reeat-/!+ the background will look better&
1.
Web Tech Notes FX Engineering
College, Tirunelveli
E/amle
body
E
background-image&url(Dgradient).ngD!F
background-reeat&reeat-/F
G
Try it yourself
1ackground 2mage - 3et osition and no-reeat
6hen using a background image+ use an image that does not disturb the te/t.
3howing the image only once is seci#ied by the background-reeat roerty&
E/amle
body
E
background-image&url(Dimg=tree.ngD!F
background-reeat&no-reeatF
G
Try it yourself
2n the e/amle abo%e+ the background image is shown in the same lace as the te/t. 6e want to
change the osition o# the image+ so that it does not disturb the te/t too much.
The osition o# the image is seci#ied by the background-osition roerty&
E/amle
body
E
background-image&url(Dimg=tree.ngD!F
background-reeat&no-reeatF
background-osition&right toF
G
1/
Web Tech Notes FX Engineering
College, Tirunelveli
Try it yourself
1ackground - 3horthand roerty
As you can see #rom the e/amles abo%e+ there are many roerties to consider when dealing with
backgrounds.
To shorten the code+ it is also ossible to seci#y all the roerties in one single roerty. This is
called a shorthand roerty.
The shorthand roerty #or background is simly .background.&
E/amle
body Ebackground&I###### url(Dimg=tree.ngD! no-reeat right toFG
Try it yourself
6hen using the shorthand roerty the order o# the roerty %alues are&
background-color
background-image
background-reeat
background-attachment
background-osition
2t does not matter i# one o# the roerty %alues is missing+ as long as the ones that are resent are in
this order.
All "33 1ackground 7roerties
The number in the ."33. column indicates in which "33 %ersion the roerty is de#ined ("33( or
"33)!.
Property Description Vales !SS
background 3ets all the background roerties
in one declaration
background-color
background-image
background-repeat
background-attachment
(
20
Web Tech Notes FX Engineering
College, Tirunelveli
background-position
inherit
background-attachment 3ets whether a background image
is #i/ed or scrolls with the rest o#
the age
scroll
#i/ed
inherit
(
background-color 3ets the background color o# an
element
color-rgb
color-hex
color-name
transarent
inherit
(
background-image 3ets the background image #or an
element
url(URL!
none
inherit
(
background-position 3ets the starting osition o# a
background image
le#t to
le#t center
le#t bottom
right to
right center
right bottom
center to
center center
center bottom
x% y%
xpos ypos
inherit
(
background-repeat 3ets i#$how a background image will
be reeated
reeat
reeat-/
reeat-y
no-reeat
inherit
(
CSS Text
' (revious Ne)t Chater *
TEXT FOM!TTI"#
T h i s t e / t i s s t y l e d w i t h s o me o # t h e t e / t # o r ma t t i n g r o e r t i e s .
T h e h e a d i n g u s e s t h e t e / t - a l i g n + t e / t - t r a n s # o r m+ a n d c o l o r
r o e r t i e s . T h e a r a g r a h i s i n d e n t e d + a l i g n e d + a n d t h e s a c e
b e t w e e n c h a r a c t e r s i s s e c i # i e d . T h e u n d e r l i n e i s r e mo % e d # r o m t h e
. T r y i t y o u r s e l # . l i n k .
Te/t "olor
The color roerty is used to set the color o# the te/t. The color can be seci#ied by&
21
Web Tech Notes FX Engineering
College, Tirunelveli
name - a color name+ like .red.
4L1 - an 4L1 %alue+ like .rgb()::+?+?!.
He/ - a he/ %alue+ like .I##????.
The de#ault color #or a age is de#ined in the body selector.
E/amle
body Ecolor&blueFG
h( Ecolor&I??##??FG
h) Ecolor&rgb()::+?+?!FG
Try it yourself
5or 6C" comliant "33& 2# you de#ine the color roerty+ you must also de#ine the background-
color roerty.
Te/t Alignment
The te/t-align roerty is used to set the hori>ontal alignment o# a te/t.
Te/t can be centered+ or aligned to the le#t or right+ or ,usti#ied.
6hen te/t-align is set to .,usti#y.+ each line is stretched so that e%ery line has eHual width+ and the
le#t and right margins are straight (like in maga>ines and newsaers!.
E/amle
h( Ete/t-align&centerFG
.date Ete/t-align&rightFG
.main Ete/t-align&,usti#yFG
Try it yourself
Te/t *ecoration
The te/t-decoration roerty is used to set or remo%e decorations #rom te/t.
The te/t-decoration roerty is mostly used to remo%e underlines #rom links #or design uroses&
22
Web Tech Notes FX Engineering
College, Tirunelveli
E/amle
a Ete/t-decoration&noneFG
Try it yourself
2t can also be used to decorate te/t&
E/amle
h( Ete/t-decoration&o%erlineFG
h) Ete/t-decoration&line-throughFG
hC Ete/t-decoration&underlineFG
hJ Ete/t-decoration&blinkFG
Try it yourself
2t is not recommended to underline te/t that is not a link+ as this o#ten con#uses users.
Te/t Trans#ormation
The te/t-trans#orm roerty is used to seci#y uercase and lowercase letters in a te/t.
2t can be used to turn e%erything into uercase or lowercase letters+ or caitali>e the #irst letter o#
each word.
E/amle
.uercase Ete/t-trans#orm&uercaseFG
.lowercase Ete/t-trans#orm&lowercaseFG
.caitali>e Ete/t-trans#orm&caitali>eFG
Try it yourself
Te/t 2ndentation
The te/t-indentation roerty is used to seci#y the indentation o# the #irst line o# a te/t.
23
Web Tech Notes FX Engineering
College, Tirunelveli
E/amle
Ete/t-indent&:?/FG
Try it yourself
CSS Font
' (revious Ne)t Chater *
"33 #ont roerties de#ine the #ont #amily+ boldness+ si>e+ and the style o# a te/t.
*i##erence 1etween 3eri# and 3ans-seri# 5onts
'n comuter screens+ sans-seri# #onts are considered easier to read than seri# #onts.
"33 5ont 5amilies
2n "33+ there are two tyes o# #ont #amily names&
generic family - a grou o# #ont #amilies with a similar look (like .3eri#. or .Monosace.!
font family - a seci#ic #ont #amily (like .Times 8ew 4oman. or .Arial.!
"eneric family #ont family Description
3eri#
Times Ne1 2oman
Georgia
3eri# #onts ha%e small lines at the ends on some
characters
3ans-seri#
"rial
Oerdana
.3ans. means without - these #onts do not ha%e the
lines at the ends o# characters
2"
Web Tech Notes FX Engineering
College, Tirunelveli
Monosace
C&0r.er !e%
L0/.+a C&1s&)e
All monosace characters ha%e the same width
5ont 5amily
The #ont #amily o# a te/t is set with the #ont-#amily roerty.
The #ont-#amily roerty should hold se%eral #ont names as a .#allback. system. 2# the browser does
not suort the #irst #ont+ it tries the ne/t #ont.
3tart with the #ont you want+ and end with a generic #amily+ to let the browser ick a similar #ont in
the generic #amily+ i# no other #onts are a%ailable.
Note& 2# the name o# a #ont #amily is more than one word+ it must be in Huotation marks+ like #ont-
#amily& .Times 8ew 4oman..
More than one #ont #amily is seci#ied in a comma-searated list&
E/amle
E#ont-#amily&.Times 8ew 4oman.+ Times+ seri#FG
Try it yourself
5or more commonly used #ont combinations+ look at our 6eb 3a#e 5ont "ombinations.
5ont 3tyle
The #ont-style roerty is mostly used to seci#y italic te/t.
This roerty has three %alues&
normal - The te/t is shown normally
italic - The te/t is shown in italics
obliHue - The te/t is .leaning. (obliHue is %ery similar to italic+ but less suorted!
E/amle
.normal E#ont-style&normalFG
.italic E#ont-style&italicFG
2%
Web Tech Notes FX Engineering
College, Tirunelveli
.obliHue E#ont-style&obliHueFG
Try it yourself
5ont 3i>e
The #ont-si>e roerty sets the si>e o# the te/t.
1eing able to manage the te/t si>e is imortant in web design. Howe%er+ you should not use #ont si>e
ad,ustments to make aragrahs look like headings+ or headings look like aragrahs.
Always use the roer HTML tags+ like <h(> - <hM> #or headings and <> #or aragrahs.
The #ont-si>e %alue can be an absolute+ or relati%e si>e.
Absolute si>e&
3ets the te/t to a seci#ied si>e
*oes not allow a user to change the te/t si>e in all browsers (bad #or accessibility reasons!
Absolute si>e is use#ul when the hysical si>e o# the outut is known
4elati%e si>e&
3ets the si>e relati%e to surrounding elements
Allows a user to change the te/t si>e in browsers
2# you do not seci#y a #ont si>e+ the de#ault si>e #or normal te/t+ like aragrahs+ is (M/
((M/0(em!.
3et 5ont 3i>e 6ith 7i/els
3etting the te/t si>e with i/els+ gi%es you #ull control o%er the te/t si>e&
E/amle
h( E#ont-si>e&J?/FG
h) E#ont-si>e&C?/FG
E#ont-si>e&(J/FG
Try it yourself
2&
Web Tech Notes FX Engineering
College, Tirunelveli
The e/amle abo%e allows 5ire#o/+ "hrome+ and 3a#ari to resi>e the te/t+ $t not Internet
%xplorer.
The te/t can be resi>ed in all browsers using the >oom tool (howe%er+ this resi>es the entire age+ not
,ust the te/t!.
3et 5ont 3i>e 6ith Em
To a%oid the resi>ing roblem with 2nternet E/lorer+ many de%eloers use em instead o# i/els.
The em si>e unit is recommended by the 6C".
(em is eHual to the current #ont si>e. The de#ault te/t si>e in browsers is (M/. 3o+ the de#ault si>e o#
(em is (M/.
The si>e can be calculated #rom i/els to em using this #ormula& pixels$(M0em
E/amle
h( E#ont-si>e&).:emFG $@ J?/$(M0).:em @$
h) E#ont-si>e&(.B<:emFG $@ C?/$(M0(.B<:em @$
E#ont-si>e&?.B<:emFG $@ (J/$(M0?.B<:em @$
Try it yourself
2n the e/amle abo%e+ the te/t si>e in em is the same as the re%ious e/amle in i/els. Howe%er+
with the em si>e+ it is ossible to ad,ust the te/t si>e in all browsers.
Un#ortunately+ there is still a roblem with 2E. 6hen resi>ing the te/t+ it becomes larger than it should
when made larger+ and smaller than it should when made smaller.
Use a "ombination o# 7ercent and Em
The solution that works in all browsers+ is to set a de#ault #ont-si>e in ercent #or the body element&
E/amle
body E#ont-si>e&(??;FG
h( E#ont-si>e&).:emFG
h) E#ont-si>e&(.B<:emFG
E#ont-si>e&?.B<:emFG
2+
Web Tech Notes FX Engineering
College, Tirunelveli
Try it yourself
CSS Links
' (revious Ne)t Chater *
Links can be styled in di##erent ways.
3tyling Links
Links can be styled with any "33 roerty (e.g. color+ #ont-#amily+ background+ etc.!.
3ecial #or links are that they can be styled di##erently deending on what state they are in.
The #our links states are&
a&link - a normal+ un%isited link
a&%isited - a link the user has %isited
a&ho%er - a link when the user mouses o%er it
a&acti%e - a link the moment it is clicked
E/amle
a&link Ecolor&I55????FG $@ un%isited link @$
a&%isited Ecolor&I??55??FG $@ %isited link @$
a&ho%er Ecolor&I55??55FG $@ mouse o%er link @$
a&acti%e Ecolor&I????55FG $@ selected link @$
Try it yourself
6hen setting the style #or se%eral link states+ there are some order rules&
a&ho%er MU3T come a#ter a&link and a&%isited
a&acti%e MU3T come a#ter a&ho%er
"ommon Link 3tyles
2n the e/amle abo%e the link changes color deending on what state it is in.
2.
Web Tech Notes FX Engineering
College, Tirunelveli
Lets go through some o# the other common ways to style links&
Te/t *ecoration
The te/t-decoration roerty is mostly used to remo%e underlines #rom links&
E/amle
a&link Ete/t-decoration&noneFG
a&%isited Ete/t-decoration&noneFG
a&ho%er Ete/t-decoration&underlineFG
a&acti%e Ete/t-decoration&underlineFG
Try it yourself
1ackground "olor
The background-color roerty seci#ies the background color #or links&
E/amle
a&link Ebackground-color&I1)55NNFG
a&%isited Ebackground-color&I5555B:FG
a&ho%er Ebackground-color&I55<?J*FG
a&acti%e Ebackground-color&I55<?J*FG
Try it yourself
CSS Lists
' (revious Ne)t Chater *
The "33 list roerties allow you to&
3et di##erent list item markers #or ordered lists
3et di##erent list item markers #or unordered lists
3et an image as the list item marker
2/
Web Tech Notes FX Engineering
College, Tirunelveli
List
2n HTML+ there are two tyes o# lists&
unordered lists - the list items are marked with bullets
ordered lists - the list items are marked with numbers or letters
6ith "33+ lists can be styled #urther+ and images can be used as the list item marker.
*i##erent List 2tem Markers
The tye o# list item marker is seci#ied with the list-style-tye roerty&
E/amle
ul.a Elist-style-tye& circleFG
ul.b Elist-style-tye& sHuareFG
ol.c Elist-style-tye& uer-romanFG
ol.d Elist-style-tye& lower-alhaFG
Try it yourself
3ome o# the roerty %alues are #or unordered lists+ and some #or ordered lists.
Oalues #or Unordered Lists
Vale Description
none 8o marker
disc *e#ault. The marker is a #illed circle
circle The marker is a circle
sHuare The marker is a sHuare
Oalues #or 'rdered Lists
Vale Description
armenian The marker is traditional Armenian numbering
30
Web Tech Notes FX Engineering
College, Tirunelveli
decimal The marker is a number
decimal-leading->ero The marker is a number added by initial >eros (?(+ ?)+ ?C+ etc.!
georgian The marker is traditional Leorgian numbering (an+ ban+ gan+ etc.!
lower-alha The marker is lower-alha (a+ b+ c+ d+ e+ etc.!
lower-greek The marker is lower-greek (alha+ beta+ gamma+ etc.!
lower-latin The marker is lower-latin (a+ b+ c+ d+ e+ etc.!
lower-roman The marker is lower-roman (i+ ii+ iii+ i%+ %+ etc.!
uer-alha The marker is uer-alha (A+ 1+ "+ *+ E+ etc.!
uer-latin The marker is uer-latin (A+ 1+ "+ *+ E+ etc.!
uer-roman The marker is uer-roman (2+ 22+ 222+ 2O+ O+ etc.!
Note: 2EB+ and earlier+ suort the roerty %alues .decimal-leading->ero.+ .lower-greek.+ .lower-
latin.+ .uer-latin.+ .armenian.+ .georgian.+ or .inherit. only i# a *'"T97E is seci#iedA
An 2mage as The List 2tem Marker
To seci#y an image as the list item marker+ use the list-style-image roerty&
E/amle
ul
E
list-style-image& url(DsHurle.gi#D!F
G
Try it yourself
The e/amle abo%e does not dislay eHually in all browsers. 2E and 'era will dislay the image-
marker a little bit higher than 5ire#o/+ "hrome+ and 3a#ari.
2# you want the image-marker to be laced eHually in all browsers+ a crossbrowser solution is
e/lained below.
"rossbrowser 3olution
31
Web Tech Notes FX Engineering
College, Tirunelveli
The #ollowing e/amle dislays the image-marker eHually in all browsers&
E/amle
ul
E
list-style-tye& noneF
adding& ?/F
margin& ?/F
G
li
E
background-image& url(sHurle.gi#!F
background-reeat& no-reeatF
background-osition& ?/ :/F
adding-le#t& (J/F
G
Try it yourself
E/amle e/lained&
5or ul&
& 3et the list-style-tye to none to remo%e the list item marker
& 3et both adding and margin to ?/ (#or cross-browser comatibility!
5or li&
& 3et the U4L o# the image+ and show it only once (no-reeat!
& 7osition the image where you want it (le#t ?/ and down :/!
& 7osition the te/t in the list with adding-le#t
List - 3horthand roerty
2t is also ossible to seci#y all the list roerties in one+ single roerty. This is called a shorthand
roerty.
The shorthand roerty used #or lists+ is the list-style roerty&
E/amle
ul
32
Web Tech Notes FX Engineering
College, Tirunelveli
E
list-style& sHuare url(.sHurle.gi#.!F
G
Try it yourself
6hen using the shorthand roerty+ the order o# the %alues are&
list-style-tye
list-style-osition (#or a descrition+ see the "33 roerties table below!
list-style-image
2t does not matter i# one o# the %alues abo%e are missing+ as long as the rest are in the seci#ied
order.
CSS Tables
' (revious Ne)t Chater *
The look o# an HTML table can be greatly imro%ed with "33&
!ompany !ontact !ontry
Al#reds 5utterkiste Maria Anders Lermany
1erglunds snabbkP "hristina 1erglund 3weden
"entro comercial Mocte>uma 5rancisco "hang Me/ico
Ernst Handel 4oland Mendel Austria
2sland Trading Helen 1ennett UQ
QPniglich Essen 7hili "ramer Lermany
Laughing 1acchus 6inecellars 9oshi Tannamuri "anada
Maga>>ini Alimentari 4iuniti Lio%anni 4o%elli 2taly
8orth$3outh 3imon "rowther UQ
33
Web Tech Notes FX Engineering
College, Tirunelveli
7aris sRcialitRs Marie 1ertrand 5rance
The 1ig "heese Li> 8i/on U3A
Oa##el,ernet 7alle 2bsen *enmark
Table 1orders
To seci#y table borders in "33+ use the border roerty.
The e/amle below seci#ies a black border #or table+ th+ and td elements&
E/amle
table+ th+ td
E
border& (/ solid blackF
G
Try it yourself
8otice that the table in the e/amle abo%e has double borders. This is because both the table+ th+ and
td elements ha%e searate borders.
To dislay a single border #or the table+ use the border-collase roerty.
"ollase 1orders
The border-collase roerty sets whether the table borders are collased into a single border or
searated&
E/amle
table
E
border-collase&collaseF
G
table+th+ td
E
border& (/ solid blackF
G
3"
Web Tech Notes FX Engineering
College, Tirunelveli
Try it yourself
Table 6idth and Height
6idth and height o# a table is de#ined by the width and height roerties.
The e/amle below sets the width o# the table to (??;+ and the height o# the th elements to :?/&
E/amle
table
E
width&(??;F
G
th
E
height&:?/F
G
Try it yourself
Table Te/t Alignment
The te/t in a table is aligned with the te/t-align and %ertical-align roerties.
The te/t-align roerty sets the hori>ontal alignment+ like le#t+ right+ or center&
E/amle
td
E
te/t-align&rightF
G
Try it yourself
The %ertical-align roerty sets the %ertical alignment+ like to+ bottom+ or middle&
3%
Web Tech Notes FX Engineering
College, Tirunelveli
E/amle
td
E
height&:?/F
%ertical-align&bottomF
G
Try it yourself
Table 7adding
To control the sace between the border and content in a table+ use the adding roerty on td and
th elements&
E/amle
td
E
adding&(:/F
G
Try it yourself
Table "olor
The e/amle below seci#ies the color o# the borders+ and the te/t and background color o# th
elements&
E/amle
table+ td+ th
E
border&(/ solid greenF
G
th
E
background-color&greenF
color&whiteF
3&
Web Tech Notes FX Engineering
College, Tirunelveli
G
Try it yourself
The "33 1o/ Model
All HTML elements can be considered as bo/es. 2n "33+ the term .bo/ model. is used when talking
about design and layout.
The "33 bo/ model is essentially a bo/ that wras around HTML elements+ and it consists o#&
margins+ borders+ adding+ and the actual content.
The bo/ model allows us to lace a border around elements and sace elements in relation to other
elements.
The image below illustrates the bo/ model&
E/lanation o# the di##erent arts&
&argin - "lears an area around the border. The margin does not ha%e a background color+ it
is comletely transarent
'order - A border that goes around the adding and content. The border is a##ected by the
background color o# the bo/
Padding - "lears an area around the content. The adding is a##ected by the background
color o# the bo/
!ontent - The content o# the bo/+ where te/t and images aear
3+
Web Tech Notes FX Engineering
College, Tirunelveli
2n order to set the width and height o# an element correctly in all browsers+ you need to know how
the bo/ model works.
6idth and Height o# an Element
Important: 6hen you seci#y the width and height roerties o# an element with "33+ you are ,ust
setting the width and height o# the content area. To know the #ull si>e o# the element+ you must also
add the adding+ border and margin.
The total width o# the element in the e/amle below is C??/&
width&):?/F
adding&(?/F
border&:/ solid grayF
margin&(?/F
LetDs do the math&
):?/ (width!
S )?/ (le#t and right adding!
S (?/ (le#t and right border!
S )?/ (le#t and right margin!
0 C??/
2magine that you only had ):?/ o# sace. LetDs make an element with a total width o# ):?/&
E/amle
width&))?/F
adding&(?/F
border&:/ solid grayF
margin&?/F
Try it yourself
The total width o# an element should always be calculated like this&
Total element width 0 width S le#t adding S right adding S le#t border S right border S le#t margin
S right margin
The total height o# an element should always be calculated like this&
Total element height 0 height S to adding S bottom adding S to border S bottom border S to
margin S bottom margin
1rowsers "omatibility 2ssue
2# you tested the re%ious e/amle in 2nternet E/lorer+ you saw that the total width was not e/actly
):?/.
3.
Web Tech Notes FX Engineering
College, Tirunelveli
2E includes adding and border in the width+ when the width roerty is set+ nless a DO!T(P% is
declared.
To #i/ this roblem+ ,ust add a *'"T97E to the code&
E/amle
<A*'"T97E html 7U1L2" .-$$6C"$$*T* THTML (.? Transitional$$E8.
.htt&$$www.wC.org$T4$/html($*T*$/html(-transitional.dtd.>
<html>
<head>
<style tye0.te/t$css.>
di%.e/
E
width&))?/F
adding&(?/F
border&:/ solid grayF
margin&?/F
G
<$style>
<$head>
Try it yourself
CSS Border
' (revious Ne)t Chater *
"33 1order 7roerties
The "33 border roerties allow you to seci#y the style and color o# an elementDs border.
1order 3tyle
The border-style roerty seci#ies what kind o# border to dislay.
8one o# the border roerties will ha%e A89 e##ect unless the $order)style roerty is setA
border-style %alues&
none& *e#ines no border
dotted& *e#ines a dotted border
dashed& *e#ines a dashed border
3/
Web Tech Notes FX Engineering
College, Tirunelveli
solid& *e#ines a solid border
double& *e#ines two borders. The width o# the two borders are the same as the border-width %alue
groo%e& *e#ines a C* groo%ed border. The e##ect deends on the border-color %alue
ridge& *e#ines a C* ridged border. The e##ect deends on the border-color %alue
inset& *e#ines a C* inset border. The e##ect deends on the border-color %alue
outset& *e#ines a C* outset border. The e##ect deends on the border-color %alue
Try it yoursel#& 3et the style o# the border
1order 6idth
The border-width roerty is used to set the width o# the border.
The width is set in i/els+ or by using one o# the three re-de#ined %alues& thin+ medium+ or thick.
Note: The .border-width. roerty does not work i# it is used alone. Use the .border-style. roerty
to set the borders #irst.
E/amle
.one
E
border-style&solidF
border-width&:/F
G
.two
E
border-style&solidF
border-width&mediumF
G
Try it yourself
"0
Web Tech Notes FX Engineering
College, Tirunelveli
1order "olor
The border-color roerty is used to set the color o# the border. The color can be set by&
name - seci#y a color name+ like .red.
4L1 - seci#y a 4L1 %alue+ like .rgb()::+?+?!.
He/ - seci#y a he/ %alue+ like .I##????.
9ou can also set the border color to .transarent..
Note: The .border-color. roerty does not work i# it is used alone. Use the .border-style. roerty
to set the borders #irst.
E/amle
.one
E
border-style&solidF
border-color&redF
G
.two
E
border-style&solidF
border-color&INBb#)(F
G
Try it yourself
1order - 2ndi%idual sides
2n "33 it is ossible to seci#y di##erent borders #or di##erent sides&
E/amle

E
border-to-style&dottedF
border-right-style&solidF
border-bottom-style&dottedF
border-le#t-style&solidF
G
"1
Web Tech Notes FX Engineering
College, Tirunelveli
Try it yourself
The e/amle abo%e can also be set with a single roerty&
E/amle
border-style&dotted solidF
Try it yourself
The border-style roerty can ha%e #rom one to #our %alues.
$order)style:dotted solid do$le dashed*
& to border is dotted
& right border is solid
& bottom border is double
& le#t border is dashed
$order)style:dotted solid do$le*
& to border is dotted
& right and le#t borders are solid
& bottom border is double
$order)style:dotted solid*
& to and bottom borders are dotted
& right and le#t borders are solid
$order)style:dotted*
& all #our borders are dotted
The border-style roerty is used in the e/amle abo%e. Howe%er+ it also works with border-width
and border-color.
"2
Web Tech Notes FX Engineering
College, Tirunelveli
1order - 3horthand roerty
As you can see #rom the e/amles abo%e+ there are many roerties to consider when dealing with
borders.
To shorten the code+ it is also ossible to seci#y all the border roerties in one roerty. This is
called a shorthand roerty.
The shorthand roerty #or the border roerties is .border.&
E/amle
border&:/ solid redF
Try it yourself
6hen using the border roerty+ the order o# the %alues are&
border-width
border-style
border-color
2t does not matter i# one o# the %alues abo%e are missing (although+ border-style is reHuired!+ as long
as the rest are in the seci#ied order.
All "33 1order 7roerties
The number in the ."33. column indicates in which "33 %ersion the roerty is de#ined ("33( or
"33)!.
Property Description Vales !SS
border 3ets all the border roerties in one
declaration
border-width
border-style
border-color
(
border-bottom 3ets all the bottom border roerties in one
declaration
border-bottom-width
border-bottom-style
border-bottom-color
(
border-bottom-color 3ets the color o# the bottom border border-color )
border-bottom-style 3ets the style o# the bottom border border-style )
border-bottom-width 3ets the width o# the bottom border border-width (
border-color 3ets the color o# the #our borders color_name
hex_number
rgb_number
(
"3
Web Tech Notes FX Engineering
College, Tirunelveli
transarent
inherit
border-left 3ets all the le#t border roerties in one
declaration
border-left-width
border-left-style
border-left-color
(
border-left-color 3ets the color o# the le#t border border-color )
border-left-style 3ets the style o# the le#t border border-style )
border-left-width 3ets the width o# the le#t border border-width (
border-right 3ets all the right border roerties in one
declaration
border-right-width
border-right-style
border-right-color
(
border-right-color 3ets the color o# the right border border-color )
border-right-style 3ets the style o# the right border border-style )
border-right-width 3ets the width o# the right border border-width (
border-style 3ets the style o# the #our borders none
hidden
dotted
dashed
solid
double
groo%e
ridge
inset
outset
inherit
(
border-top 3ets all the to border roerties in one
declaration
border-top-width
border-top-style
border-top-color
(
border-top-color 3ets the color o# the to border border-color )
border-top-style 3ets the style o# the to border border-style )
border-top-width 3ets the width o# the to border border-width (
border-width 3ets the width o# the #our borders thin
medium
thick
length
inherit
(
CSS Outlines
' (revious Ne)t Chater *
An outline is a line that is drawn around elements+ outside the border edge+ to
make the element .stand out..
The outline roerties seci#ies the style+ color+ and width o# an outline.
""
Web Tech Notes FX Engineering
College, Tirunelveli
All "33 'utline 7roerties
The number in the ."33. column indicates in which "33 %ersion the roerty is de#ined ("33( or
"33)!.
Property Description Vales !SS
outline 3ets all the outline roerties in one declaration outline-color
outline-style
outline-width
inherit
)
outline-color 3ets the color o# an outline color_name
hex_number
rgb_number
in%ert
inherit
)
outline-style 3ets the style o# an outline none
dotted
dashed
solid
double
groo%e
ridge
inset
outset
inherit
)
outline-width 3ets the width o# an outline thin
medium
thick
length
inherit
)
CSS Margin
' (revious Ne)t Chater *
The "33 margin roerties de#ine the sace around elements.
Margin
The margin clears an area around an element (outside the border!. The margin does not ha%e a
background color+ and is comletely transarent.
The to+ right+ bottom+ and le#t margin can be changed indeendently using searate roerties. A
shorthand margin roerty can also be used+ to change all margins at once.
7ossible Oalues
"%
Web Tech Notes FX Engineering
College, Tirunelveli
Vale Description
auto The browser sets the margin.
The result o# this is deendant o# the browser
length *e#ines a #i/ed margin (in i/els+ t+ em+ etc.!
% *e#ines a margin in ; o# the containing element
2t is ossible to use negati%e %alues+ to o%erla content.
Margin - 2ndi%idual sides
2n "33+ it is ossible to seci#y di##erent margins #or di##erent sides&
E/amle
margin-to&(??/F
margin-bottom&(??/F
margin-right&:?/F
margin-le#t&:?/F
Try it yourself
Margin - 3horthand roerty
To shorten the code+ it is ossible to seci#y all the margin roerties in one roerty. This is called a
shorthand roerty.
The shorthand roerty #or all the margin roerties is .margin.&
E/amle
margin&(??/ :?/F
Try it yourself
The margin roerty can ha%e #rom one to #our %alues.
"&
Web Tech Notes FX Engineering
College, Tirunelveli
margin:2+px +,px -+px 1,,px*
& to margin is ):/
& right margin is :?/
& bottom margin is <:/
& le#t margin is (??/
margin:2+px +,px -+px*
& to margin is ):/
& right and le#t margins are :?/
& bottom margin is <:/
margin:2+px +,px*
& to and bottom margins are ):/
& right and le#t margins are :?/
margin:2+px*
& all #our margins are ):/
All "33 Margin 7roerties
The number in the ."33. column indicates in which "33 %ersion the roerty is de#ined ("33( or
"33)!.
Property Description Vales !SS
margin A shorthand roerty #or setting the margin
roerties in one declaration
margin-top
margin-right
margin-bottom
margin-left
(
margin-bottom 3ets the bottom margin o# an element auto
length
%
(
margin-left 3ets the le#t margin o# an element auto
length
%
(
margin-right 3ets the right margin o# an element auto
length
%
(
"+
Web Tech Notes FX Engineering
College, Tirunelveli
margin-top 3ets the to margin o# an element auto
length
%
(
CSS $adding
' (revious Ne)t Chater *
The "33 adding roerties de#ine the sace between the element border and the
element content.
7adding
The adding clears an area around the content (inside the border! o# an element. The adding is
a##ected by the background color o# the element.
The to+ right+ bottom+ and le#t adding can be changed indeendently using searate roerties. A
shorthand adding roerty can also be used+ to change all addings at once.
7ossible Oalues
Vale Description
length *e#ines a #i/ed adding (in i/els+ t+ em+ etc.!
% *e#ines a adding in ; o# the containing element
7adding - 2ndi%idual sides
2n "33+ it is ossible to seci#y di##erent adding #or di##erent sides&
E/amle
adding-to&):/F
adding-bottom&):/F
adding-right&:?/F
adding-le#t&:?/F
Try it yourself
".
Web Tech Notes FX Engineering
College, Tirunelveli
7adding - 3horthand roerty
To shorten the code+ it is ossible to seci#y all the adding roerties in one roerty. This is called a
shorthand roerty.
The shorthand roerty #or all the adding roerties is .adding.&
E/amle
adding&):/ :?/F
Try it yourself
The adding roerty can ha%e #rom one to #our %alues.
padding:2+px +,px -+px 1,,px*
& to adding is ):/
& right adding is :?/
& bottom adding is <:/
& le#t adding is (??/
padding:2+px +,px -+px*
& to adding is ):/
& right and le#t addings are :?/
& bottom adding is <:/
padding:2+px +,px*
& to and bottom addings are ):/
& right and le#t addings are :?/
padding:2+px*
& all #our addings are ):/
All "33 7adding 7roerties
"/
Web Tech Notes FX Engineering
College, Tirunelveli
The number in the ."33. column indicates in which "33 %ersion the roerty is de#ined ("33(
or "33)!.
Property Description Vales !SS
padding A shorthand roerty #or setting all the adding
roerties in one declaration
padding-top
padding-right
padding-bottom
padding-left
(
padding-bottom 3ets the bottom adding o# an element length
%
(
padding-left 3ets the le#t adding o# an element length
%
(
padding-right 3ets the right adding o# an element length
%
(
padding-top 3ets the to adding o# an element length
%
(
CSS #rou%ing and "esting Selectors
' (revious Ne)t Chater *
Lrouing 3electors
2n style sheets there are o#ten elements with the same style.
h(
E
color&greenF
G
h)
E
color&greenF
G

E
color&greenF
G
To minimi>e the code+ you can grou selectors.
3earate each selector with a comma.
2n the e/amle below we ha%e groued the selectors #rom the code abo%e&
%0
Web Tech Notes FX Engineering
College, Tirunelveli
E/amle
h(+h)+
E
color&greenF
G
Try it yourself
8esting 3electors
2t is ossible to aly a style #or a selector within a selector.
2n the e/amle below+ one style is seci#ied #or all elements+ and a searate style is seci#ied #or
elements nested within the .marked. class&
E/amle

E
color&blueF
te/t-align&centerF
G
.marked
E
background-color&blueF
G
.marked
E
color&whiteF
G
Try it yourself
A!A SCRI"T
%1
Web Tech Notes FX Engineering
College, Tirunelveli
-our #irst .ava/cript /cript
To follow the classic examples of many programming tutorials, let#s use $ava!cript to print out %Hello &orld% to
the browser. ' know this isn#t very interesting, but it will be a good way to explain all the overhead re(uired to
do something in $ava!cript.
HTML U Va%a3crit "ode&
.html/
.$ody/
.script type01text23a4aScript1/
.5))
docment67rite81Hello 9orld51:
22))/
.2script/
.2$ody/
.2html/
*islay&
Hello 6orldA
)ur first step was to tell the browser we were using a script with the *script+ tag. ,ext we set the type of script
e(ual to %text-$ava!cript%. .ou may notice that doing this is similar to the way you specify /!!, which is
%text-css%.
,ext, we added an optional HTML comment that surrounds our $ava!cript code. 'f a browser does not support
$ava!cript, it will not display our code in plain text to the user0 The comment was ended with a %--11+% because
%--% signifies a comment in $ava!cript. &e add that to prevent a browser from reading the end of the HTML
comment in as a piece of $ava!cript code.
.ava/cript docu'ent)write
The final step of our script was to use a function called document.write, which writes a string into our HTML
document. document.write can be used to write text, HTML, or a little of both. &e passed the famous string of
text to the function to spell out %Hello &orld0% which it printed to the screen.
2o not worry if you don#t completely understand how document.write works, as we will be discussing functions
in a later lesson.
/ynta0
Looking at our $ava!cript code above, notice that there is no semicolon at the end of the statement
%document.write3Hello &orld04%. &hy5 $ava!cript does not re(uire that you use semicolons to signify the end
of each statement.
'f you are an experienced programmer and prefer to use semicolons, feel free to do so. $ava!cript will not
malfunction from ending semicolons. The only time it is necessary to use a semicolon is when you choose to
smash two statements onto one line3i.e. two document.write statements on one line4.
%2
Web Tech Notes FX Engineering
College, Tirunelveli
Enable .ava/cript 1 2nternet E0plorer
'n 'nternet 6xplorer 7-8 3download 'nternet 6xplorer4, you can check to see if $ava!cript is enabled by
navigating to the custom security settings that are somewhat buried 3don#t worry9 we#ll help you find it4.
:. /lick on the Tools menu
;. /hoose 2nternet 3ptions))) from the menu
<. /lick the /ecurity tab on the 2nternet 3ptions pop up
=. /lick the 4usto' Level))) button to access your security settings
>. !croll almost all the way down to the /cripting section
7. !elect the 6nable button for Active scripting
8. /lick 35 to finish the process
?. /lick -es when asked to confirm
.ava/cript etection
These days, it#s basically impossible to navigate the web without a $ava!cript1enabled browser, so checking
whether or not a user has $ava!cript enabled is not all that important. /hances are, the only way it be
disabled is if the company#s 'T staff has decided to disable $ava!cript for some reason. However, if you still
want to be sure your users are $ava!cript enabled, this script will get it done.
The only sure fire way to separate users who don#t have $ava!cript from those who do is to use a simple
redirect script that will only work for those with $ava!cript enabled. 'f a person#s browser does not have
$ava!cript enabled, the script will not run, and they will remain on the same page.
Va%a3crit "ode&
.script type01text23a4aScript1/
7indo76location 0 1http:227776example6com23a4aScript)ena$led6html1
.2script/
@eplace the example A@L with the webpage of your choice.
6here to 7lace .ava/cript
There are three general areas that $ava!cript can be placed for use in a webpage.
:. 'nside the head tag
2# &ithin the body tag 3like our example in the previous lesson4
3# 'n an external file 3we#ll talk about this next lesson4
%3
Web Tech Notes FX Engineering
College, Tirunelveli
The location choice of head or body is very simple. 'f you want to have a script run on some event, such as
when a user clicks somewhere, then you will place that script in the head. 'f you want the script to run when
the page loads, like our %Hello &orld0% example in the previous lesson, then you will want to place the script
within the body tag.
6xternal $ava!cript files and their uses will be discussed in the next lesson.
An E0a'ple 8ead /cript
!ince we have already seen the kind of script that goes in the body, how about we write a script that takes
place when some event occurs5 Let#s have an alert show up when a user click on a button.
HTML U Va%a3crit "ode&
.html/
.head/
.script type01text23a4aScript1/
.5))
fnction popp8: ;
alert81Hello 9orld1:
<
22))/
.2script/
.2head/
.$ody/
.inpt type01$tton1 onclic=01popp8:1 4ale01popp1/
.2$ody/
.2html/
*islay&
&e created a function called popup and placed it in the head of the HTML document. ,ow every time
someone clicks on the button 3this is an event4, an alert will pop up with %Hello &orld0%. &e will go into more
depth on functions and events in a later lesson.
E0ternal .ava/cript #iles
Having already discussed placing $ava!cript in the head and body of your HTML document, let us now
explore the third possible location type 11 an external file. 'f you have ever used external /!! before, this
lesson will be a cinch.
2'porting an E0ternal .ava/cript #ile
'mporting an external file is relatively painless. First, the file you are importing must be valid $ava!cript, and
only $ava!cript. !econd, the file must have the file extension %.Bs%. Lastly, you must know the location of the
file.
%"
Web Tech Notes FX Engineering
College, Tirunelveli
Let us assume we have a file %myBs.Bs% that contains a one line Hello &orld alert function. "lso, let us assume
that the file is the same directory as the HTML file we are going to code up. To import the file you would do the
following in your HTML document.
5ile my,s.,s "ontents&
fnction popp8: ;
alert81Hello 9orld1:
<
HTML U Va%a3crit "ode&
.html/
.head/
.script src01my>s6>s1/
.2script/
.2head/
.$ody/
.inpt type01$tton1 onclic=01popp8:1 4ale01!lic= &e51/
.2$ody/
.2html/
*islay&
E0ternal #ile Tips 9 :ecap
Ase external $ava!cript files when you want to use the same script on many pages, but don#t want to
have to rewrite the code on every page0
Ase external $ava!cript files for including both types of scripts the type that you place in the head
3functions4 and the type you place in the body 3scripts you want to run when the page loads4.
Ce sure that your $ava!cript files 3.Bs4 do not include the *script+ tag. They should only contain HTML
commenting and $ava!cript code 11 nothing more0
.ava/cript 3perators
)perators in $ava!cript are very similar to operators that appear in other programming languages. The
definition of an operator is a symbol that is used to perform an operation. Most often these operations are
arithmetic 3addition, subtraction, etc4, but not always.
.ava/cript Arith'etic 3perator 4hart
3perator English E0a'ple
D "ddition ; D =
1 !ubtraction 7 1 ;
%%
Web Tech Notes FX Engineering
College, Tirunelveli
E Multiplication > E <
- 2ivision :> - <
F Modulus =< F :G
Modulus ; may be a new operation to you, but it#s Bust a special way of saying %finding the remainder%. &hen
you perform a division like :>-< you get >, exactly. However, if you do =<-:G you get an answer with a decimal,
=.<. :G goes into =G four times and then there is a leftover. This leftover is what is returned by the modulus
operator. =< F :G would e(ual <.
.ava/cript 3perator E0a'ple with <ariables
Herforming operations on variables that contain values is very common and easy to do. Celow is a simple
script that performs all the basic arithmetic operations.
HTML U Va%a3crit "ode&
.$ody/
.script type01text23a4aScript1/
.5))
4ar t7o 0 2
4ar ten 0 1,
4ar line$rea= 0 1.$r 2/1
docment67rite81t7o pls ten 0 1:
4ar reslt 0 t7o ? ten
docment67rite8reslt:
docment67rite8line$rea=:
docment67rite81ten @ ten 0 1:
reslt 0 ten @ ten
docment67rite8reslt:
docment67rite8line$rea=:
docment67rite81ten 2 t7o 0 1:
reslt 0 ten 2 t7o
docment67rite8reslt:
22))/
.2script/
.2$ody/
*islay&
two lus ten 0 ()
ten @ ten 0 (??
ten $ two 0 :
%&
Web Tech Notes FX Engineering
College, Tirunelveli
4o'parison 3perators
/omparisons are used to check the relationship between variables and-or values. " single e(ual sign sets a
value while a double e(ual sign 3II4 compares two values. /omparison operators are used inside conditional
statements and evaluate to either true or false. &e will talk more about conditional statements in the upcoming
lessons.
3perator English E0a'ple :esult
II 6(ual To x II y false
0I ,ot 6(ual To x 0I y true
* Less Than x * y true
+ Jreater Than x + y false
*I Less Than or 6(ual To x *I y true
+I Jreater Than or 6(ual To x +I y false

.ava/cript <ariables
Kariables in $ava!cript behave the same as variables in most popular programming languages 3/, /DD, etc4
do, but in $ava!cript you don#t have to declare variables before you use them. 'f you don#t know what declaring
is, don#t worry about it. 't isn#t important0
.ava/cript =sing <ariables
" variable#s purpose is to store information so that it can be used later. " variable is a symbolic name that
represents some data that you set. To think of a variable name in real world terms, picture that the name is a
grocery bag and the data it represents are the groceries. The name wraps up the data so you can move it
around a lot easier, but the name is not the data0
A <ariable E0a'ple
&hen using a variable for the first time it is not necessary to use %var% before the variable name, but it is a
good programming practice to make it crystal clear when a variable is being used for the first time in the
program. Here we are showing how the same variable can take on different values throughout a script.
HTML U Va%a3crit "ode&
%+
Web Tech Notes FX Engineering
College, Tirunelveli
.$ody/
.script type01text23a4aScript1/
.5))
4ar line$rea= 0 1.$r 2/1
4ar myA4ar 0 1Hello 9orld51
docment67rite8myA4ar:
docment67rite8line$rea=:
myA4ar 0 1I am learning 3a4aScript51
docment67rite8myA4ar:
docment67rite8line$rea=:
myA4ar 0 1Script is #inishing p6661
docment67rite8myA4ar:
22))/
.2script/
.2$ody/
*islay&
Hello 6orldA
2 am learning Va%a3critA
3crit is 5inishing u...
&e made two variables in this example11one to hold the HTML for a line break and the other for a dynamic
variable that had a total of three different values throughout the script.
To assign a value to a variable, you use the e(ual sign 3I4 with the variable on the left and the value to be
assigned on the right. 'f you swap the order, your script will not work correctly0 'n 6nglish, the $ava!cript
%myKar I #Hello &orld0#% would be myKar e(uals #Hello &orld0#.
The first time we used a variable, we placed var in front to signify its first use. This is an easy way to organiLe
the variables in your code and see when they came into existence. 'n subse(uent assignments of the same
variable, we did not need the var.
.ava/cript #unctions
'f you have any programming experience, you do not need to spend much time on this lesson. Functions in
$ava!cript behave similarly to numerous programming languages 3/, /DD, HHH, etc4. 'f this is your first time
learning about functions, then be sure to go through this lesson very thoroughly. " solid understanding of
functions will make the rest of this tutorial much easier to follow.
6hat+s a #unction?
" function is a piece of code that sits dormant until it is referenced or called upon to do its %function%. 'n
addition to controllable execution, functions are also a great time saver for doing repetitive tasks.
'nstead of having to type out the code every time you want something done, you can simply call the function
multiple times to get the same effect. This benefit is also known as %code reusability%.
%.
Web Tech Notes FX Engineering
College, Tirunelveli
E0a'ple #unction in .ava/cript
" function that does not execute when a page loads should be placed inside the head of your HTML
document. /reating a function is really (uite easy. "ll you have to do is tell the browser you#re making a
function, give the function a name, and then write the $ava!cript like normal. Celow is the example alert
function from the previous lesson.
HTML U Va%a3crit "ode&
.html/
.head/
.script type01text2>a4ascript1/
.5))
fnction popp8: ;
alert81Hello 9orld1:
<
22))/
.2script/
.2head/
.$ody/
.inpt type01$tton1 onclic=01popp8:1 4ale01popp1/
.2$ody/
.2html/
*islay&
&e first told the browser we were going to be using a function by typing %function%. ,ext, we gave our function
a name, so that we could use it later. !ince we are making a pop up alert, we called our function %popup%.
The curly braces %M,N% define the boundaries of our function code. "ll popup function code must be contained
within the curly braces.
!omething that might be slightly confusing is that within our %popup% function, we use another function called
%alert,% which brings up a popup box with the text that we supply it. 't is perfectly )O to use functions within
functions, like we have done here. Furthermore, this is one of the great things about using functions0
&hat we didn#t talk about was how we got this function to execute when the button is clicked. The click is
called an event, and we will be talking about how to make functions execute from various types of events in
the next lesson.
Events in .ava/cript
The absolute coolest thing about $ava!cript is its ability to help you create dynamic webpages that increase
user interaction, making the visitor feel like the website is almost coming alive right before her eyes.
The building blocks of an interactive web page is the $ava!cript event system. "n event in $ava!cript is
something that happens with or on the webpage. " few example of events
" mouse click
The webpage loading
%/
Web Tech Notes FX Engineering
College, Tirunelveli
Mousing over a hot spot on the webpage, also known as hovering
!electing an input box in an HTML form
" keystroke
A 4ouple of E0a'ples =sing Events
$ava!cript has predefined names that cover numerous events that can occur, including the ones listed above.
To capture an event and make something happen when that event occurs, you must specify the event, the
HTML element that will be waiting for the event, and the function3s4 that will be run when the event occurs.
&e have used a $ava!cript event in a previous lesson, where we had an alert popup when the button was
clicked. This was an %onclick% $ava!cript event. &e will do that same example again, as well as the
mouseover and mouseout events.
HTML U Va%a3crit "ode&
.html/
.head/
.script type01text2>a4ascript1/
.5))
fnction popp8: ;
alert81Hello 9orld1:
<
22))/
.2script/
.2head/
.$ody/
.inpt type01$tton1 4ale01!lic= &e51 onclic=01popp8:1/.$r 2/
.a href01B1 onmoseo4er011 on&oseot01popp8:1/
Ho4er &e5.2a/
.2$ody/
.2html/
*islay&
3over 4e5
&ith the button we used the event onClick event as our desired action and told it to call our popup function
that is defined in our header. To call a function you must give the function name followed up with parenthesis
%34%.
)ur mouseover and mouseout events were combined on one HTML element11a link. &e wanted to do nothing
when someone put their mouse on the link, but when the mouse moves off the link 3onMouseout4, we
displayed a popup.
&0
Web Tech Notes FX Engineering
College, Tirunelveli
.ava/cript /tate'ents
"ll the $ava!cript code that you will write will, for the most part, be comprised of many separate statements. "
statement can set a variable e(ual to a value. " statement can also be a function call, i.e. document.write().
!tatements define what the script will do and how it will be done.
Typical Ending of a /tate'ent
'n typical programming languages like / and HHH, the end of a statement is marked with a semicolon394, but
we have seen that the semicolon is optional in $ava!cript. 'n $ava!cript, the end of a statement is most often
marked by pressing return and starting a new line.
4ategories of /tate'ents
'n addition to standard statements like changing a variable#s value, assigning a new value, or calling a
function, there are groups of statements that are distinct in their purpose. &e will provide a brief overview of
each of these categories in this lesson and cover them in greater detail later in the tutorial. These distinct
groups of statements include
4onditional /tate'ents
Loop /tate'ents
3b*ect >anipulation /tate'ents
4o''ent /tate'ents
E0ception 8andling /tate'ents
4onditional /tate'ents
'f you were to win a P:GG million lottery, you would probably (uit your Bob. That last statement is a conditional
if-then statement that is used a great deal in programming. 'f some condition 3winning the lottery4 is true, then
something happens 3you (uit your Bob4. 'f the condition is false 3you didn#t win the lottery4, then you probably
will not take that action 3(uit your Bob4.
/onditional statements are used to control your scripts so that different actions can be taken depending on the
situation. .ou may want to display a special image on your home page during the holidays. This condition
would depend on what day it was, and if it was a holiday, then a special holiday image would be displayed to
your visitors. &ithout proper knowledge of the conditional statement, your scripts will not be as lively or
dynamic as they could possibly be.
&1
Web Tech Notes FX Engineering
College, Tirunelveli
Loop /tate'ents
Have you ever had to send out marriage announcements5 'f not, this is how it goes. .ou take the invitation,
place it in the envelope, lick the envelope, seal the envelope, then send it off. Then you take the next invitation
off the stack of QQ remaining invitations, place it in an envelope, lick the envelope, seal... .ou get the idea0 't is
a boring and repetitive task0
&ouldn#t it be great if there was an easier way5 &ell, in programming and in $ava!cript there is0 The process
is called %looping.% &ith the right planning, looping will turn your cute little scripts into massive workhorses.
" loop statement checks to see if some condition is true, and if that condition is true, it executes a chunk of
code. "fter the code is executed, the condition is checked again. 'f it is true, the process starts over again9 if it
is false, the loop stops and the rest of the code continues along. 'f we think about our wedding invitation
example as a loop, we would first check if there are any invitations left. 'f there are, we would stuff, lick, and
seal the next envelope. 'f there are no envelopes left, we would stop.
Celieve me when ' say this is something you want to learn more about0
3b*ect >anipulation /tate'ents
These are statements that are used to take advantage of the obBect model to get tasks done. 'f you do not
know about the obBect model at this time, do not worry. &e will be talking about it later.
4o''ent /tate'ents
/omment statements are used to prevent the browser from executing certain parts of code that you designate
as non1code. &hy would you want to do this5 There are many reasons. Cy disallowing the block of text from
being be read, you can then place in comments for yourself, much like HTML comments. .ou can also block
out segments of your code for whatever reason you may have.
The single line comment is Bust two slashes 3--4 and the multiple line comment starts with 3-E4 and ends with
3E-4. &e will talk about comments in greater depth in a later lesson.
E0ception 8andling /tate'ents
!ometimes when you are programming you do not know for sure if the file that you will be writing to, the input
stream you are reading from, or the connection you have established will be usable for the code that you want
to execute. There is a way to program safety mechanisms, so that your code handles common problems that
may arise 3maybe the input stream you are reading from suddenly disappears4.
The try...catch statement tries to execute a piece of code and if it fails, the catch should handle the error
gracefully. This is an advanced programming subBect that is interesting, but not necessary for the maBority of
$ava!cript programmers.
&2
Web Tech Notes FX Engineering
College, Tirunelveli
6rapup
' hope you found this overview of $ava!cript statements interesting. 2o not despair if you have not grasped all
the details discussed above, as we will be covering them further in a later lesson.
.ava/cript 2f /tate'ent /ynta0
There are two maBor parts to an 'f !tatement the conditional statement and the code to be executed.
The conditional statement is a statement that will evaluate to be either True or False. The most common type
of conditional statement used checks to see if something e(uals a value. "n example would be checking if a
date e(uals your birthday.
Celow is a segment of $ava!cript code that will be executed only if the 'f !tatement#s conditional statement is
true. 'n this simple If Statement example, we print out a message if the variable we are checking is e(ual to 8.
Va%a3crit "ode&
.script type01text2>a4ascript1/
.5))
4ar myNm 0 -*
if8myNm 00 -:;
docment67rite81Cc=y -51:*
<
22))/
.2script/
*islay&
Lucky <A
This simple example created myNum and set it to 8. &e then checked to see if myNum was e(ual to 8
3%my,um II 8%4 in the If Statement's conditional statement, evaluated to rue.
Cecause the conditional statement was rue the block of code associated with our 'f !tatement
3%document.write...%4 was executed, as you can see in the 2isplay.
.ava/cript 2f /tate'ent? Else
&e already taught you how to execute code if a given condition is rue, but what if you want to execute
another piece of code if something is !alse5 The answer is to use an extension to the If Statement9 the "lse
clause.
The "lse clause is executed when the conditional statement is !alse. Let#s take our example from above, add
an "lse clause, and change the value of myNum so that our conditional statement is False.
&3
Web Tech Notes FX Engineering
College, Tirunelveli
Va%a3crit "ode&
.script type01text2>a4ascript1/
.5))
4ar myNm 0 1,*
if8myNm 00 -:;
docment67rite81Cc=y -51:*
<else;
docment67rite81(oDre not 4ery lc=y today6661:*
<
22))/
.2script/
*islay&
9ouDre not %ery lucky today...
.ava/cript Else 2f E0a'ple
'magine that you want to have a small %student% script that will print out a customiLed message depending who
is accessing the webpage. 'f you have more than two custom messages, you could use the "lse If extension
to solve this programming problem.
Va%a3crit "ode&
.script type01text2>a4ascript1/
.5))
4ar 4isitor 0 1principal1*
if84isitor 00 1teacher1:;
docment67rite81&y dog ate my home7or=6661:*
<else if84isitor 00 1principal1:;
docment67rite819hat stin= $om$sE1:*
< else ;
docment67rite81Ho7 do yo doE1:*
<
22))/
.2script/
*islay&
6hat stink bombsK
There are two important things to note about the "lse If extension
:. .ou must have a normal 'f !tatement before you can use the "lse If statement. This is because the
"lse If statement is an addon to the 'f !tatement.
;. .ou can have multiple "lse If add1ons. 'n our example, we only used one "lse If extension, but you
can add as many as you re(uire.
&"
Web Tech Notes FX Engineering
College, Tirunelveli
.ava/cript 6hile Loop E0plained
There are two key parts to a $ava!cript while loop
:. The conditional statement which must be rue for the while loop's code to be executed.
;. The while loop's code that is contained in curly braces %M and N% will be executed if the condition is
rue.
&hen a while loop begins, the $ava!cript interpreter checks if the condition statement is true. 'f it is, the code
between the curly braces is executed. "t the end of the code segment %N%, the while loop loops back to the
condition statement and begins again.
'f the condition statement is always rue, then you will never exit the while loop, so be very careful when
using while loops0
4reating a /i'ple 6hile Loop
This example shows how to create a basic while loop that will execute a document.write :G times and then exit
the loop statement.
Va%a3crit "ode&
.script type01text2>a4ascript1/
.5))
4ar my!onter 0 ,*
4ar line$rea= 0 1.$r 2/1*
docment67rite819hile loop is $eginning1:*
docment67rite8line$rea=:*
7hile8my!onter . 1,:;
docment67rite81my!onter 0 1 ? my!onter:*
docment67rite8line$rea=:*
my!onter??*
<
docment67rite819hile loop is finished51:*
.2script/
*islay&
6hile loo is beginning
my"ounter 0 ?
my"ounter 0 (
my"ounter 0 )
my"ounter 0 C
my"ounter 0 J
my"ounter 0 :
my"ounter 0 M
my"ounter 0 <
&%
Web Tech Notes FX Engineering
College, Tirunelveli
my"ounter 0 B
my"ounter 0 N
6hile loo is #inishedA
)ur variable myCounter started off at G, which is less than :G, so our while loop executed its code. The value
G was printed to the browser and then myCounter was incremented by : and the while loop started over again.
: was less than :G so the while loop#s code was executed... and the process repeats itself a few more times
until...
myCounter was :G which was not less than :G so the while loop#s code did not execute. .ou can see this in
the #isplay$ because the last value to be printed out was Q.
,ote "dvanced programmers may recogniLe that a for loop would be a better solution for this example, but
we hope you can ignore this for our needs to create an easy example0
.ava/cript #or Loop E0plained
There are four important aspects of a $ava!cript for loop
:. The counter variable is something that is created and usually used only in the for loop to count how
many times the for loop has looped. i is the normal label for this counter variable and what we will be
using.
;. The conditional statement. 't is what decides whether the for loop continues executing or not. This
check usually includes the counter variable in some way.
<. The counter variable is incremented after every loop in the increment section of the for loop.
=. The code that is executed for each loop through the for loop.
This may seem strange, but :1< all occur on the same line of code. This is because the for loop is such a
standardiLed programming practice that the designers felt they might as well save some space and clutter
when creating the for loop.
.ava/cript #or Loop E0a'ple
This example will show you how to create a simple for loop that prints out the value of our counter until the
counter reaches >. Hay special close attention to the three different items that are on the first line of the for
loop code. These are the important for loop parts :1< that we talked about earlier.
Va%a3crit "ode&
.script type01text2>a4ascript1/
.5))
4ar line$rea= 0 1.$r 2/1*
docment67rite81#or loop code is $eginning1:*
docment67rite8line$rea=:*
for8i 0 ,* i . +* i??:;
&&
Web Tech Notes FX Engineering
College, Tirunelveli
docment67rite81!onter i 0 1 ? i:*
docment67rite8line$rea=:*
<
docment67rite81#or loop code is finished51:*
.2script/
*islay&
5or loo code is beginning
"ounter i 0 ?
"ounter i 0 (
"ounter i 0 )
"ounter i 0 C
"ounter i 0 J
5or loo code is #inishedA
The counter variable name i may seem a little strange, but it has been used for years now0 ,o matter the
language, i is the default name for a loop counter. )ther common variable names are %& k& '& y and (.
'n this example, our counter was initially set to G with %i I G9% and then the conditional statement %i * >9% was
executed. )ur counter was indeed smaller than >, so the for loop#s code was executed.
"fter the loop#s code is executed then the increment %iDD% happens, making the counter i e(ual to :. The for
loop then checked that i was less than >, which it was, causing the for loop's code to be executed again.
This looping happened a couple more times until i was e(ual to >, which is not less than >, causing the for
loop#s code to stop executing.
!or loops may seem very confusing at first, but let me assure you, they are (uite useful and should be studied
thoroughly by anyone who wishes to become an intermediate programmer.
.ava/cript 4o''ents
Have you ever written a script or a program in the past only to look at it six months later with no idea what#s
going on in the code5 .ou probably forgot to do what all programmers tend to forget to do write comments0
4reating /ingle Line 4o''ents
To create a single line comment in $ava!cript, you place two slashes %--% in front of the code or text you wish
to have the $ava!cript interpreter ignore. &hen you place these two slashes, all text to the right of them will be
ignored, until the next line.
These types of comments are great for commenting out single lines of code and writing small notes.
Va%a3crit "ode&
&+
Web Tech Notes FX Engineering
College, Tirunelveli
.script type01text2>a4ascript1/
.5))
22 This is a single line 3a4aScript comment
docment67rite81I ha4e comments in my 3a4aScript code51:*
22docment67rite81(o canDt see this51:*
22))/
.2script/
*islay&
2 ha%e comments in my Va%a3crit codeA
6ach line of code that is colored red is commented out and will not be interpreted by the $ava!cript engine.
4reating >ulti1line 4o''ents
"lthough a single line comment is (uite useful, it can sometimes be burdensome to use when disabling long
segments of code or inserting long1winded comments. For this large comments you can use $ava!cript#s
multi1line comment that begins with -E and ends with E-.
Va%a3crit "ode&
.script type01text2>a4ascript1/
.5))
docment67rite81I ha4e mlti)line comments51:*
2@docment67rite81(o canDt see this51:*
docment67rite81(o canDt see this51:*
docment67rite81(o canDt see this51:*
docment67rite81(o canDt see this51:*
docment67rite81(o canDt see this51:*
docment67rite81(o canDt see this51:*
docment67rite81(o canDt see this51:*@2
22))/
.2script/
*islay&
2 ha%e multi-line commentsA
Ruite often text editors have the ability to comment out many lines of code with a simple key stroke or option in
the menu. 'f you are using a specialiLed text editor for programming, be sure that you check and see if it has
an option to easily comment out many lines of code0
.ava/cript Array
"n array is a variable that can store many variables within it. Many programmers have seen arrays in other
languages, and they aren#t that different in $ava!cript.
&.
Web Tech Notes FX Engineering
College, Tirunelveli
The following points should always be remembered when using arrays in $ava!cript
The array is a special type of variable.
Kalues are stored into an array by using the array name and by stating the location in the array you
wish to store the value in brackets. 6xample my"rrayS;T I %Hello &orld%9
Kalues in an array are accessed by the array name and location of the value. 6xample my"rrayS;T9
$ava!cript has built1in functions for arrays, so check out these built1in array functions before writing
the code yourself0
4reating a .ava/cript Array
/reating an array is slightly different from creating a normal variable. Cecause $ava!cript has variables and
properties associated with arrays, you have to use a special function to create a new array. This example
shows how you would create a simple array, store values to it, and access these values.
Va%a3crit "ode&
.script type01text2>a4ascript1/
.5))
4ar myFrray 0 ne7 Frray8:*
myFrrayG,H 0 1#oot$all1*
myFrrayG1H 0 1'ase$all1*
myFrrayG2H 0 1!ric=et1*
docment67rite8myFrrayG,H ? myFrrayG1H ? myFrrayG2H:*
22))/
.2script/
*islay&
5ootball1aseball"ricket
,otice that you set values and get values from an array by specifying the position, in brackets, of the value you
want to use.
.ava/cript Array /orting
'magine that you wanted to sort an array alphabetically before you wrote the array to the browser. &ell, this
code has already been written and can be accessed by using the "rray#s sort method.
Va%a3crit "ode&
.script type01text2>a4ascript1/
.5))
4ar myFrray20 ne7 Frray8:*
&/
Web Tech Notes FX Engineering
College, Tirunelveli
myFrray2G,H 0 1#oot$all1*
myFrray2G1H 0 1'ase$all1*
myFrray2G2H 0 1!ric=et1*
myFrray26sort8:*
docment67rite8myFrray2G,H ? myFrray2G1H ? myFrray2G2H:*
22))/
.2script/
*islay&
1aseball"ricket5ootball
.ava/cript Alert 1 6hat is it?
'f you do not have $ava!cript enabled on your web browser, then you may have been able to avoid %alerts% in
your internet adventures. The $ava!cript alert is a dialogue box that pops up and takes the focus away from
the current window and forces the web browser to read the message.
6hen to =se 7opups @ Alerts
$ava!cript alerts are ideal for the following situations
'f you want to be absolutely sure they see a message before doing anything on the website.
.ou would like to warn the user about something. For example %the following page contains humor
not suitable for those under the age of :=.%
"n error has occurred and you want to inform the user of the problem.
&hen asking users for confirmation of some action. For example, if they have Bust agreed to sign over
the deed to their house and you want to ask them again if they are absolutely positive they want to go
through with this decision0
6ven though the above situations would all be valid times to use the alert function, you could also skip the alert
popup and Bust have the error message, confirmation, etc displayed in plain HTML. More and more bigger
sites are opting to lose $ava!cript alerts and instead keep everything in HTML.
4oding a /i'ple .ava/cript Alert
$ust for fun, let#s suppose that we are making an alert for some website that asks people to hand over the
deed to their house. &e need to add an alert to be sure these people are in agreement. The following code will
add an alert by using an HTML button and the onClick event.
HTML U Va%a3crit "ode&
+0
Web Tech Notes FX Engineering
College, Tirunelveli
.form/
.inpt type01$tton1 onclic=0
1alert8DFre yo sre yo 7ant to gi4e s the deed to yor hoseED:1
4ale01!onfirmation Flert1/
.2form/
*islay&
The string that appears between the single (uotes is what will be printed inside the alert box when the user
clicks on the button. 'f the HTML Forms are confusing to you, be sure to brush up on our HTML Forms Lesson.
/ontinue the tutorial to learn more about the different kinds of $ava!cript pop ups that are at your disposal.
.ava/cript 4onfir' E0a'ple
Celow is an example of how you would use a confirm dialogue box to warn users about something, giving
them the option to either continue on or stay put.
HTML U Va%a3crit "ode&
.html/
.head/
.script type01text2>a4ascript1/
.5))
fnction confirmation8: ;
4ar ans7er 0 confirm81Cea4e tiIag6comE1:
if 8ans7er:;
alert81'ye $ye51:
7indo76location 0 1http:227776google6com21*
<
else;
alert81Than=s for stic=ing arond51:
<
<
22))/
.2script/
.2head/
.$ody/
.form/
.inpt type01$tton1 onclic=01confirmation8:1 4ale01Cea4e TiIag6com1/
.2form/
.2$ody/
.2html/
*islay&
+1
Web Tech Notes FX Engineering
College, Tirunelveli
,ote the part in red. This is where all the magic happens. &e call the confirm function with the message,
%Leave TiLag5%. $ava!cript then makes a popup window with two choices and will return a value to our script
code depending on which button the user clicks.
'f the user clicks )O, a value of : is returned. 'f a user clicks cancel, a value of G is returned.. &e store this
value in answer by setting it e(ual to the confirm function call.
"fter answer has stored the value, we then use answer as a conditional statement. 'f answer is anything but
Lero, then we will send the user away from TiLag.com. 'f answer is e(ual to Lero, we will keep the user at
TiLag.com because they clicked the /ancel button.
'n either case, we have a $ava!cript alert box that appears to inform the user on what is going to happen. 't
will say, %Cye bye0% if they choose to leave and, %Thanks for sticking around0% if they choose to stay.
'n this lesson, we also used the window.location property for the first time. &hatever we set window.location to
will be where the browser is redirected to. 'n this example, we chose Joogle.com. &e will discuss redirection
in greater detail later on.
/i'ple .ava/cript 7ro'pt
.ou can use a prompt for a wide variety of useless tasks, but below we use it for an exceptionally silly task.
)ur prompt is used to gather the user#s name to be displayed in our alert dialogue box.
HTML U Va%a3crit "ode&
.head/
.script type01text2>a4ascript1/
.5))
fnction prompter8: ;
4ar reply 0 prompt81Hey thereJ good loo=ing stranger5 9hatDs yor nameE1J 11:
alert 8 1Nice to see yo arond these parts 1 ? reply ? 151:
<
22))/
.2script/
.2head/
.$ody/
.inpt type01$tton1 onclic=01prompter8:1 4ale01Say my name51/
.2$ody/
*islay&
:ecap on .ava/cript 7ro'pt
't sure is a (uick way to gather some information, but it is not as reliable an information gatherer as other
options available to you. 'f you want to find out someone#s name and information, the best way to re(uest this
information would be through the use of HTML Forms. "nd if you want to use the information you collected in
your website, you might use some HHH to get that Bob done in a more sophisticated manner.
+2
Web Tech Notes FX Engineering
College, Tirunelveli
.ava/cript 7rint /cript 1 window)print()
The $ava!cript print function window.print() will print the current webpage when executed. 'n this example
script, we will be placing the function on a $ava!cript button that will perform the print operation when the
onClick event occurs.
HTML U Va%a3crit "ode&
.form/
.inpt type01$tton1 4ale01Print This Page1 on!lic=017indo76print8:1 2/
.2form/
*islay&
'f you click this button you should be prompted with whatever application your computer uses to handle its
print functionality.
.ava/cript :edirect
.ou#re moving to a new domain name. .ou have a time1delay placeholder on your download site. .ou have a
list of external web servers that are helping to mirror your site. &hat will help you deal with and-or take
advantage of these situations5 $ava!cript redirects will.
.ava/cript 6indow)Location
/ontrol over what page is loaded into the browser rests in the $ava!cript property window.location. Cy setting
window.location e(ual to a new A@L, you will in turn change the current webpage to the one that is specified.
'f you wanted to redirect all your visitors to www.google.com when they arrived at your site, you would Bust
need the script below
HTML U Va%a3crit "ode&
.script type01text2>a4ascript1/
.5))
7indo76location 0 1http:227776google6com21
22))/
.2script/
.ava/cript Ti'e elay
'mplementing a timed delay in $ava!cript is useful in the following situations
!howing an %Apdate your bookmark% page when you have to change A@Ls or page locations
For download sites that wish to have a timed delay before the download starts
+3
Web Tech Notes FX Engineering
College, Tirunelveli
To refresh a webpage once every specified number of seconds
The code for this timed delay is slightly involved and is beyond the scope of this tutorial. However, we have
tested it and it seems to function properly.
HTML U Va%a3crit "ode&
.html/
.head/
.script type01text2>a4ascript1/
.5))
fnction delayer8:;
7indo76location 0 1662>a4ascriptredirect6php1
<
22))/
.2script/
.2head/
.$ody onCoad01setTimeot8Ddelayer8:DJ +,,,:1/
.h2/Prepare to $e redirected5.2h2/
.p/This page is a time delay redirectJ please pdate yor $oo=mar=s to or ne7
location5.2p/
.2$ody/
.2html/
Oiew 7age&
Time 6elay 2edirect
The most important part of getting the delay to work is being sure to use the $ava!cript function setimeout.
&e want the delayer() function to be used after > seconds or >GGG milliseconds 3> seconds4, so we pass the
setimeout() two arguments.
+delayer()+ 1 The function we want setimeout() to execute after the specified delay.
A,,, 1 the number of millisecods we want setimeout() to wait before executing our function. :GGG
miliseconds I : second.
6eb 7age :edirection
2o use $ava!cript for redirections when you change your website#s A@L or move a file to a new location. 2on#t
use redirections when they can easily be replaced with a normal HTML hyperlink.
.ava/cript window)open #unction
The window.open() function creates a new browser window, customiLed to your specifications, without the use
of an HTML anchor tag. 'n this example, we will be making a function that utiliLes the window.open() function.
HTML U Va%a3crit "ode&
+"
Web Tech Notes FX Engineering
College, Tirunelveli
.head/
.script type01text2>a4ascript1/
.5))
fnction myPopp8: ;
7indo76open8 1http:227776google6com21 :
<
22))/
.2script/
.2head/
.$ody/
.form/
.inpt type01$tton1 on!lic=01myPopp8:1 4ale01POP51/
.2form/
.p on!lic=01myPopp8:1/!CI!K &% TOO5.2p/
.2$ody/
*islay&
"L2"Q ME T''A
This works with pretty much any tag that can be clicked on, so please go ahead and experiment with this fun
little tool. "fterwards, read on to learn more about the different ways you can customiLe the $ava!cript window
that pops up.
.ava/cript 6indow)3pen Argu'ents
There are three arguments that the window.open function takes
:. The relative or absolute A@L of the webpage to be opened.
;. The text name for the window.
<. " long string that contains all the different properties of the window.
,aming a window is very useful if you want to manipulate it later with $ava!cript. However, this is beyond the
scope of this lesson, and we will instead be focusing on the different properties you can set with your brand
spanking new $ava!cript window. Celow are some of the more important properties
dependent 1 !ubwindow closes if the parent window 3the window that opened it4 closes
fullscreen 1 2isplay browser in fullscreen mode
height 1 The height of the new window, in pixels
width 1 The width of the new window, in pixels
left 1 Hixel offset from the left side of the screen
top 1 Hixel offset from the top of the screen
resiBable 1 "llow the user to resiLe the window or prevent the user from resiLing, currently broken in
Firefox.
+%
Web Tech Notes FX Engineering
College, Tirunelveli
status 1 2isplay or don#t display the status bar
2ependent, fullscreen, resiLable, and status are all examples of ),-)FF properties. .ou can either set them
e(ual to Lero to turn them off, or set them to one to turn them ),. There is no inbetween setting for these
types of properties.
=pgraded .ava/cript 7opup 6indowC
,ow that we have the tools, let#s make a sophisticated $ava!cript popup window that we can be proud of0
HTML U Va%a3crit "ode&
.head/
.script type01text2>a4ascript1/
.5))
fnction myPopp28: ;
7indo76open8 1http:227776google6com21J 1my9indo71J
1stats 0 1J height 0 L,,J 7idth 0 L,,J resiIa$le 0 ,1 :
<
22))/
.2script/
.2head/
.$ody/
.form/
.inpt type01$tton1 on!lic=01myPopp28:1 4ale01POP251/
.2form/
.p on!lic=01myPopp28:1/!CI!K &% TOO5.2p/
.2$ody/
*islay&
"L2"Q ME T''A
,ow, that is a prime example of a worthless popup0 &hen you make your own, try to have them relate to your
content, like a small popup with no navigation that Bust gives the definition or explanation of a word, sentence,
or picture0
Det the .ava/cript Ti'e
The 2ate obBect has been created, and now we have a variable that holds the current date0 To get the
information we need to print out, we have to utiliLe some or all of the following functions
getTi'e() 1 ,umber of milliseconds since :-:-:Q8G U :;GG "M
get/econds() 1 ,umber of seconds 3G1>Q4
get>inutes() 1 ,umber of minutes 3G1>Q4
get8ours() 1 ,umber of hours 3G1;<4
+&
Web Tech Notes FX Engineering
College, Tirunelveli
getay() 1 2ay of the week3G174. G I !unday, ... , 7 I !aturday
getate() 1 2ay of the month 3G1<:4
get>onth() 1 ,umber of month 3G1::4
get#ull-ear() 1 The four digit year 3:Q8G1QQQQ4
,ow we can print out the date information. &e will be using the )et#ate, )etMonth, and )et!ull*ear methods
in this example.
HTML U Va%a3crit "ode&
.hM/It is no7
.script type01text2>a4ascript1/
.5))
4ar crrentTime 0 ne7 Date8:
4ar month 0 crrentTime6get&onth8: ? 1
4ar day 0 crrentTime6getDate8:
4ar year 0 crrentTime6get#ll(ear8:
docment67rite8month ? 121 ? day ? 121 ? year:
22))/
.2script/
.2hM/
*islay&
It is now 1/1/2004 !
,otice that we added : to the month variable to correct the problem with $anuary being G and 2ecember being
::. "fter adding :, $anuary will be :, and 2ecember will be :;.
.ava/cript 4urrent Ti'e 4loc!
,ow, instead of displaying the date we, will display the format you might see on a typical digital clock 11
HHMM "M-HM 3H I Hour, M I Minute4.
HTML U Va%a3crit "ode&
.hM/It is no7
.script type01text2>a4ascript1/
.5))
4ar crrentTime 0 ne7 Date8:
4ar hors 0 crrentTime6getHors8:
4ar mintes 0 crrentTime6get&intes8:
if 8mintes . 1,:;
mintes 0 1,1 ? mintes
<
docment67rite8hors ? 1:1 ? mintes ? 1 1:
if8hors / 11:;
++
Web Tech Notes FX Engineering
College, Tirunelveli
docment67rite81P&1:
< else ;
docment67rite81F&1:
<
22))/
.2script/
.2hM/
*islay&
It is now 1:39 AM
"bove, we check to see if either the hours or minutes variable is less than :G. 'f it is, then we need to add a
Lero to the beginning of minutes. This is not necessary, but if it is :G: "M, our clock would output %:: "M%,
which doesn#t look very nice at all0
.ava/cript #or' <alidation
There#s nothing more troublesome than receiving orders, guestbook entries, or other form submitted data that
are incomplete in some way. .ou can avoid these headaches once and for all with $ava!cript#s amaLing way
to combat bad form data with a techni(ue called %form validation%.
The idea behind $ava!cript form validation is to provide a method to check the user entered information before
they can even submit it. $ava!cript also lets you display helpful alerts to inform the user what information they
have entered incorrectly and how they can fix it. 'n this lesson we will be reviewing some basic form validation,
showing you how to check for the following
'f a text input is empty or not
'f a text input is all numbers
'f a text input is all letters
'f a text input is all alphanumeric characters 3numbers V letters4
'f a text input has the correct number of characters in it 3useful when restricting the length of a
username and-or password4
'f a selection has been made from an HTML select input 3the drop down selector4
'f an email address is valid
How to check all above when the user has completed filling out the form
This lesson is a little long, but knowing how to implement these form validation techni(ues is definitely worth
the effort on your part. @emember to check out TiLag#s HTML forms lesson if you need to brush up on your form
knowledge.
+.
Web Tech Notes FX Engineering
College, Tirunelveli
#or' <alidation 1 4hec!ing for Eon1E'pty
This has to be the most common type of form validation. .ou want to be sure that your visitors enter data into
the HTML fields you have %re(uired% for a valid submission. Celow is the $ava!cript code to perform this basic
check to see if a given HTML input is empty or not.
Va%a3crit "ode&
22 If the length of the elementDs string is , then display helper message
fnction not%mpty8elemJ helper&sg:;
if8elem64ale6length 00 ,:;
alert8helper&sg:*
elem6focs8:* 22 set the focs to this inpt
retrn false*
<
retrn tre*
<
The function not"mpty will check to see that the HTML input that we send it has something in it. elem is a
HTML text input that we send this function. $ava!criptstrings have built in properties, one of which is the
len)th property which returns the length of the string. The chunk of code elem.value will grab the string inside
the input and by adding on length elem.value.len)th we can see how long the string is.
"s long as elem.value.len)th isn#t G then it#s not empty and we return true, otherwise we send an alert to the
user with a helperMs) to inform them of their error and return false.
6orking E/amle&
.script type0Dtext2>a4ascriptD/
fnction not%mpty8elemJ helper&sg:;
if8elem64ale6length 00 ,:;
alert8helper&sg:*
elem6focs8:*
retrn false*
<
retrn tre*
<
.2script/
.form/
NeOired #ield: .inpt type0DtextD id0DreO1D2/
.inpt type0D$ttonD
onclic=01not%mpty8docment6get%lement'yId8DreO1D:J DPlease %nter a ValeD:1
4ale0D!hec= #ieldD 2/
.2form/
*islay&
4eHuired 5ield&
+/
Web Tech Notes FX Engineering
College, Tirunelveli
#or' <alidation 1 4hec!ing for All Eu'bers
'f someone is entering a credit card, phone number, Lip code, similar information you want to be able to
ensure that the input is all numbers. The (uickest way to check if an input#s string value is all numbers is to
use a regular expression -WSG1QTDP- that will only match if the string is all numbers and is at least one character
long.
Va%a3crit "ode&
22 If the elementDs string matches the reglar expression it is all nm$ers
fnction isNmeric8elemJ helper&sg:;
4ar nmeric%xpression 0 2PG,)QH?R2*
if8elem64ale6match8nmeric%xpression::;
retrn tre*
<else;
alert8helper&sg:*
elem6focs8:*
retrn false*
<
<
&hat we#re doing here is using $ava!cript existing framework to have it do all the hard work for us. 'nside
each string is a function called match that you can use to see if the string matches a certain regular
expression. &e accessed this function like so elem.value.match3expressionhere4.
&e wanted to see if the input#s string was all numbers so we made a regular expression to check for numbers
SG1QT and stored it as numeric"'pression.
&e then used the match function with our regular expression. 'f it is numeric then match will return true,
making our if statement pass the test and our function isNumeric will also return true. However, if the
expression fails because there is a letter or other character in our input#s string then we#ll display our
helperMs) and return false.
6orking E/amle&
.script type0Dtext2>a4ascriptD/
fnction isNmeric8elemJ helper&sg:;
4ar nmeric%xpression 0 2PG,)QH?R2*
if8elem64ale6match8nmeric%xpression::;
retrn tre*
<else;
alert8helper&sg:*
elem6focs8:*
retrn false*
<
<
.2script/
.form/
Nm$ers Only: .inpt type0DtextD id0Dnm$ersD2/
.inpt type0D$ttonD
onclic=01isNmeric8docment6get%lement'yId8Dnm$ersD:J DNm$ers Only PleaseD:1
4ale0D!hec= #ieldD 2/
.2form/
.0
Web Tech Notes FX Engineering
College, Tirunelveli
*islay&
8umbers 'nly&
#or' <alidation 1 4hec!ing for All Letters
This function will be identical to isNumeric except for the change to the regular expression we use inside the
match function. 'nstead of checking for numbers we will want to check for all letters.
'f we wanted to see if a string contained only letters we need to specify an expression that allows for both
lowercase and uppercase letters -WSa1L"1XTDP- .
Va%a3crit "ode&
22 If the elementDs string matches the reglar expression it is all letters
fnction isFlpha$et8elemJ helper&sg:;
4ar alpha%xp 0 2PGa)IF)SH?R2*
if8elem64ale6match8alpha%xp::;
retrn tre*
<else;
alert8helper&sg:*
elem6focs8:*
retrn false*
<
<
6orking E/amle&
.script type0Dtext2>a4ascriptD/
fnction isFlpha$et8elemJ helper&sg:;
4ar alpha%xp 0 2PGa)IF)SH?R2*
if8elem64ale6match8alpha%xp::;
retrn tre*
<else;
alert8helper&sg:*
elem6focs8:*
retrn false*
<
<
.2script/
.form/
Cetters Only: .inpt type0DtextD id0DlettersD2/
.inpt type0D$ttonD
onclic=01isFlpha$et8docment6get%lement'yId8DlettersD:J DCetters Only PleaseD:1
4ale0D!hec= #ieldD 2/
.2form/
*islay&
.1
Web Tech Notes FX Engineering
College, Tirunelveli
Letters 'nly&
#or' <alidation 1 4hec!ing for Eu'bers and Letters
Cy combining both the is+lphabet and isNumeric functions into one we can check to see if a text input contains
only letters and numbers.
Va%a3crit "ode&
22 If the elementDs string matches the reglar expression it is nm$ers and letters
fnction isFlphanmeric8elemJ helper&sg:;
4ar alpha%xp 0 2PG,)Qa)IF)SH?R2*
if8elem64ale6match8alpha%xp::;
retrn tre*
<else;
alert8helper&sg:*
elem6focs8:*
retrn false*
<
<
#or' <alidation 1 :estricting the Length
Ceing able to restrict the number of characters a user can enter into a field is one of the best ways to prevent
bad data. For example, if you know that the Lip code field should only be > numbers you know that ; numbers
is not sufficient.
Celow we have created a len)th,estriction function that takes a text field and two numbers. The first number is
the minimum number of characters and the second is the maximum number of a characters the input can be. 'f
you Bust want to specify an exact number then send the same number for both minimum and maximum.
Va%a3crit "ode&
fnction lengthNestriction8elemJ minJ max:;
4ar Inpt 0 elem64ale*
if8Inpt6length /0 min TT Inpt6length .0 max:;
retrn tre*
<else;
alert81Please enter $et7een 1 ?min? 1 and 1 ?max? 1 characters1:*
elem6focs8:*
retrn false*
<
<
Here#s an example of this function for a field that re(uires 7 to ? characters for a valid username.
6orking E/amle&
.2
Web Tech Notes FX Engineering
College, Tirunelveli
.script type0Dtext2>a4ascriptD/
fnction lengthNestriction8elemJ minJ max:;
4ar Inpt 0 elem64ale*
if8Inpt6length /0 min TT Inpt6length .0 max:;
retrn tre*
<else;
alert81Please enter $et7een 1 ?min? 1 and 1 ?max? 1 characters1:*
elem6focs8:*
retrn false*
<
<
.2script/
.form/
Username8V)W characters:: .inpt type0DtextD id0DrestrictD2/
.inpt type0D$ttonD
onclic=01lengthNestriction8docment6get%lement'yId8DrestrictD:J VJ W:1
4ale0D!hec= #ieldD 2/
.2form/
*islay&
Username(M-B characters!&
#or' <alidation 1 /election >ade
To be sure that someone has actually selected a choice from an HTML select input you can use a simple trick
of making the first option as helpful prompt to the user and a red flag to you for your validation code.
Cy making the first option of your select input something like %Hlease /hoose% you can spur the user to both
make a selection and allow you to check to see if the default option %Hlease /hoose% is still selected when the
submit the form.
Va%a3crit "ode&
fnction madeSelection8elemJ helper&sg:;
if8elem64ale 00 1Please !hoose1:;
alert8helper&sg:*
elem6focs8:*
retrn false*
<else;
retrn tre*
<
<
6orking E/amle&
.script type0Dtext2>a4ascriptD/
fnction madeSelection8elemJ helper&sg:;
if8elem64ale 00 1Please !hoose1:;
.3
Web Tech Notes FX Engineering
College, Tirunelveli
alert8helper&sg:*
elem6focs8:*
retrn false*
<else;
retrn tre*
<
<
.2script/
.form/
Selection: .select id0DselectionD/
.option/Please !hoose.2option/
.option/!F.2option/
.option/9I.2option/
.option/XX.2option/
.2select/
.inpt type0D$ttonD
onclic=01madeSelection8docment6get%lement'yId8DselectionD:J DPlease !hoose
SomethingD:1
4ale0D!hec= #ieldD 2/
.2form/
*islay&
3election&
#or' <alidation 1 E'ail <alidation
"nd for our grand finale we will be showing you how to check to see if a user#s email address is valid. 6very
email is made up for > parts
:. " combination of letters, numbers, periods, hyphens, plus signs, and-or underscores
;. The at symbol U
<. " combination of letters, numbers, hyphens, and-or periods
=. " period
>. The top level domain 3com, net, org, us, gov, ...4
Kalid 6xamples
bobby.BoUfilltank.net
BackDBillUhill.com
the1standUsteven.king.com
'nvalid 6xamples
Udeleted.net 1 no characters before the U
free0domUbravehe.art 1 invalid character 0
."
Web Tech Notes FX Engineering
College, Tirunelveli
shoesUneedYshining.com 1 underscores are not allowed in the domain name
The regular expression to check for all of this is a little overkill and beyond the scope of this tutorial to explain
thoroughly. However, test it out and you#ll see that it gets the Bob done.
Va%a3crit "ode&
fnction emailValidator8elemJ helper&sg:;
4ar email%xp 0 2PGY7Y)Y6Y?H?YZGa)IF)S,)QY6Y)H?Y6Ga)IF)I,)QH;2JM<R2*
if8elem64ale6match8email%xp::;
retrn tre*
<else;
alert8helper&sg:*
elem6focs8:*
retrn false*
<
<
6orking E/amle&
.script type0Dtext2>a4ascriptD/
fnction emailValidator8elemJ helper&sg:;
4ar email%xp 0 2PGY7Y)Y6Y?H?YZGa)IF)S,)QY6Y)H?Y6Ga)IF)I,)QH;2JM<R2*
if8elem64ale6match8email%xp::;
retrn tre*
<else;
alert8helper&sg:*
elem6focs8:*
retrn false*
<
<
.2script/
.form/
%mail: .inpt type0DtextD id0DemailerD2/
.inpt type0D$ttonD
onclic=01emailValidator18docment6get%lement'yId8DemailerD:J DNot a Valid %mailD:1
4ale0D!hec= #ieldD 2/
.2form/
*islay&
Email&
<alidating a #or' 1 All at 3nce
'f you#ve made it this far ' commend you, but we#re not done yet0 The final step is to be able to perform all of
these validation steps when the user is ready to submit their data.
6ach form has a $ava!cript event called onSubmit that is triggered when its submit button is clicked. 'f this
even returns G or false then a form cannot be submitted, and if it returns : or true it will always be submitted.
.%
Web Tech Notes FX Engineering
College, Tirunelveli
&ouldn#t it be perfect if we could somehow make an if statement that said %'f the form is valid submit it 3:4 else
don#t submit it 3G4%5 &ell with a master form-alidator function we can do Bust that.
form-alidator will be somewhat like a list of checks that we want to do before a form is submitted. Cut before
we can decide what we want to check for, we need to have our form0
HTML 5orm "ode&
.form ons$mit0Dretrn formValidator8:D /
#irst Name: .inpt type0DtextD id0DfirstnameD 2/.$r 2/
Fddress: .inpt type0DtextD id0DaddrD 2/.$r 2/
Sip !ode: .inpt type0DtextD id0DIipD 2/.$r 2/
State: .select id0DstateD/
.option/Please !hoose.2option/
.option/FC.2option/
.option/!F.2option/
.option/TX.2option/
.option/9I.2option/
.2select/.$r 2/
Username8V)W characters:: .inpt type0DtextD id0DsernameD 2/.$r 2/
%mail: .inpt type0DtextD id0DemailD 2/.$r 2/
.inpt type0Ds$mitD 4ale0D!hec= #ormD 2/.$r 2/
.2form/
That#s a lot of data to verify and the first thing we would probably want to check is that each field was at least
filled out. To check for completion we will ensure no fields are empty and that the S"."C field has a
selection. Here are the starting pieces of our master validation function form-alidator.
Va%a3crit "ode&
fnction formValidator8:;
22 &a=e Oic= references to or fields
4ar firstname 0 docment6get%lement'yId8DfirstnameD:*
4ar addr 0 docment6get%lement'yId8DaddrD:*
4ar Iip 0 docment6get%lement'yId8DIipD:*
4ar state 0 docment6get%lement'yId8DstateD:*
4ar sername 0 docment6get%lement'yId8DsernameD:*
4ar email 0 docment6get%lement'yId8DemailD:*
22 !hec= each inpt in the order that it appears in the form5
if8isFlpha$et8firstnameJ 1Please enter only letters for yor name1::;
if8isFlphanmeric8addrJ 1Nm$ers and Cetters Only for Fddress1::;
if8isNmeric8IipJ 1Please enter a 4alid Iip code1::;
if8madeSelection8stateJ 1Please !hoose a State1::;
if8lengthNestriction8sernameJ VJ W::;
if8emailValidator8emailJ 1Please enter a 4alid email
address1::;
retrn tre*
<
<
<
<
<
<
.&
Web Tech Notes FX Engineering
College, Tirunelveli
retrn false*
<
The first part of this function is where we create easy references to our HTML inputs using the )et"lement/yId
function. These (uick references will make our next block of code much easier to read0
The second part uses a bunch of embedded if statements to see whether or not each field has the correct type
of data. 'f every single one of those fields we check validates, then we#ll return true and the form will be
submitted successfully.
However, if Bust one of those if statements fails then the return false at the end of the function is reached and
prevents the form for being submitted.
"s you can see this function really does do (uite a lot, definitely earning the title of form-alidator. ,otice how
this one function references all of the functions we have covered in this lesson. Cy placing all of these checks
in a central location you make your code easier to read and easier to change around in the future.
,ow let#s put all the necessary and HTML together and try it out0
All Together Eow
Celow we have taken the HTML form code and the new function form-alidator and plugged in all the other
form validation functions taught in this lesson that are referenced in form-alidator.
HTML U Va%a3crit "ode&
.script type0Dtext2>a4ascriptD/
fnction formValidator8:;
22 &a=e Oic= references to or fields
4ar firstname 0 docment6get%lement'yId8DfirstnameD:*
4ar addr 0 docment6get%lement'yId8DaddrD:*
4ar Iip 0 docment6get%lement'yId8DIipD:*
4ar state 0 docment6get%lement'yId8DstateD:*
4ar sername 0 docment6get%lement'yId8DsernameD:*
4ar email 0 docment6get%lement'yId8DemailD:*
22 !hec= each inpt in the order that it appears in the form5
if8isFlpha$et8firstnameJ 1Please enter only letters for yor name1::;
if8isFlphanmeric8addrJ 1Nm$ers and Cetters Only for Fddress1::;
if8isNmeric8IipJ 1Please enter a 4alid Iip code1::;
if8madeSelection8stateJ 1Please !hoose a State1::;
if8lengthNestriction8sernameJ VJ W::;
if8emailValidator8emailJ 1Please enter a 4alid email
address1::;
retrn tre*
<
<
<
.+
Web Tech Notes FX Engineering
College, Tirunelveli
<
<
<
retrn false*
<
fnction not%mpty8elemJ helper&sg:;
if8elem64ale6length 00 ,:;
alert8helper&sg:*
elem6focs8:* 22 set the focs to this inpt
retrn false*
<
retrn tre*
<
fnction isNmeric8elemJ helper&sg:;
4ar nmeric%xpression 0 2PG,)QH?R2*
if8elem64ale6match8nmeric%xpression::;
retrn tre*
<else;
alert8helper&sg:*
elem6focs8:*
retrn false*
<
<
fnction isFlpha$et8elemJ helper&sg:;
4ar alpha%xp 0 2PGa)IF)SH?R2*
if8elem64ale6match8alpha%xp::;
retrn tre*
<else;
alert8helper&sg:*
elem6focs8:*
retrn false*
<
<
fnction isFlphanmeric8elemJ helper&sg:;
4ar alpha%xp 0 2PG,)Qa)IF)SH?R2*
if8elem64ale6match8alpha%xp::;
retrn tre*
<else;
alert8helper&sg:*
elem6focs8:*
retrn false*
<
<
fnction lengthNestriction8elemJ minJ max:;
4ar Inpt 0 elem64ale*
if8Inpt6length /0 min TT Inpt6length .0 max:;
retrn tre*
<else;
alert81Please enter $et7een 1 ?min? 1 and 1 ?max? 1 characters1:*
elem6focs8:*
..
Web Tech Notes FX Engineering
College, Tirunelveli
retrn false*
<
<
fnction madeSelection8elemJ helper&sg:;
if8elem64ale 00 1Please !hoose1:;
alert8helper&sg:*
elem6focs8:*
retrn false*
<else;
retrn tre*
<
<
fnction emailValidator8elemJ helper&sg:;
4ar email%xp 0 2PGY7Y)Y6Y?H?YZGa)IF)S,)QY6Y)H?Y6Ga)IF)I,)QH;2JM<R2*
if8elem64ale6match8email%xp::;
retrn tre*
<else;
alert8helper&sg:*
elem6focs8:*
retrn false*
<
<
.2script/
.form ons$mit0Dretrn formValidator8:D /
#irst Name: .inpt type0DtextD id0DfirstnameD 2/.$r 2/
Fddress: .inpt type0DtextD id0DaddrD 2/.$r 2/
Sip !ode: .inpt type0DtextD id0DIipD 2/.$r 2/
State: .select id0DstateD/
.option/Please !hoose.2option/
.option/FC.2option/
.option/!F.2option/
.option/TX.2option/
.option/9I.2option/
.2select/.$r 2/
Username8V)W characters:: .inpt type0DtextD id0DsernameD 2/.$r 2/
%mail: .inpt type0DtextD id0DemailD 2/.$r 2/
.inpt type0Ds$mitD 4ale0D!hec= #ormD 2/
.2form/
*islay&
./
Web Tech Notes FX Engineering
College, Tirunelveli
#irst Name:
Fddress:
Sip !ode:
State:
Username8V)W characters::
%mail:
/heck Form
/tring Length 7roperty
The len)th property returns the number of characters that are in a string, using an integer. Celow is the basic
code for accessing this property.
Va%a3crit "ode&
.script type01text2>a4ascript1/
4ar myString 0 112LM+V1*
4ar length 0 myString6length*
docment67rite81The string is this long: 1 ? length:*
22 Same thingJ $t sing the property inside the 7rite fnction
docment67rite81.$r 2/The string is this long: 1 ? myString6length:*
.2script/
*islay&
The string is this long& M
The string is this long& M
/tring 4hanged? Length >ight 4hange
'f you were to reference the len)th property after concatenating 3adding4 some characters to the string, then
the length property will reflect these changes. Think of this as a friendly reminder to only check the length of
the string after you are sure it isn#t going to be changed.
Va%a3crit "ode&
.script type01text2>a4ascript1/
4ar myString 0 112LM+V1*
/0
Web Tech Notes FX Engineering
College, Tirunelveli
docment67rite81The string is this long: 1 ? myString6length:*
myString 0 myString ? 1-WQ,1*
docment67rite81.$r 2/The string is no7 this long: 1 ? myString6length:*
.2script/
*islay&
The string is this long& M
The string is now this long& (?
.ava/cript getEle'entBy2d
Have you ever tried to use $ava!cript to do some form validation5 2id you have any trouble using $ava!cript
to grab the value of your text field5 There#s an easy way to access any HTML element, and it#s through the use
of id attributes and the )et"lement/yId function.
.ava/cript docu'ent)getEle'entBy2d
'f you want to (uickly access the value of an HTML input give it an id to make your life a lot easier. This small
script below will check to see if there is any text in the text field %myText%. The argument that )et"lement/yId
re(uires is the id of the HTML element you wish to utiliLe.
Va%a3crit "ode&
.script type01text2>a4ascript1/
fnction not%mpty8:;
4ar myText#ield 0 docment6get%lement'yId8DmyTextD:*
if8myText#ield64ale 50 11:
alert81(o entered: 1 ? myText#ield64ale:
else
alert819old yo please enter some textE1:
<
.2script/
.inpt type0DtextD id0DmyTextD 2/
.inpt type0D$ttonD onclic=0Dnot%mpty8:D 4ale0D#orm !hec=erD 2/
*islay&
document.)et"lement/yId returned a reference to our HTML element mye't. &e stored this reference into a
variable, mye't!ield, and then used the value property that all input elements have to use to grab the value
the user enters.
There are other ways to accomplish what the above script does, but this is definitely a straight1forward and
browser1compatible approach.
/1
Web Tech Notes FX Engineering
College, Tirunelveli
Things to :e'e'ber About getEle'entBy2d
&hen using the )et"lement/yId function, you need to remember a few things to ensure that everything goes
smoothly. .ou always need to remember that )et"lement/yId is a method 3or function4 of the document
obBect. This means you can only access it by using document.)et"lement/yId.
"lso, be sure that you set your HTML elements# id attributes if you want to be able to use this function. &ithout
an id, you#ll be dead in the water.
'f you want to access the text within a non1input HTML element, then you are going to have to use the
inner0M. property instead of value. The next lesson goes into more detail about the uses of inner0M..
.ava/cript inner8T>L
6ver wonder how you could change the contents of an HTML element5 Maybe you#d like to replace the text in
a paragraph to reflect what a visitor has Bust selected from a drop down box. Cy manipulating an element#s
inner0tml you#ll be able to change your text and HTML as much as you like.
4hanging Te0t with inner8T>L
6ach HTML element has an inner0M. property that defines both the HTML code and the text that occurs
between that element#s opening and closing tag. Cy changing an element#s inner0M. after some user
interaction, you can make much more interactive pages.
However, using inner0M. re(uires some preparation if you want to be able to use it easily and reliably. First,
you must give the element you wish to change an id. &ith that id in place you will be able to use the
)et"lement/yId function, which works on all browsers.
"fter you have that set up you can now manipulate the text of an element. To start off, let#s try changing the
text inside a bold tag.
Va%a3crit "ode&
.script type01text2>a4ascript1/
fnction changeText8:;
docment6get%lement'yId8D$oldStffD:6innerHT&C 0 D#red #linstoneD*
<
.2script/
.p/9elcome to the site .$ id0D$oldStffD/dde.2$/ .2p/
.inpt type0D$ttonD onclic=0DchangeText8:D 4ale0D!hange TextD2/
*islay&
6elcome to the site #red #linstone
.ou now know how to change the text in any HTML element, but what about changing the text in an element
based on user input5 &ell, if we combine the above knowledge with a text input...
/2
Web Tech Notes FX Engineering
College, Tirunelveli
=pdating Te0t Based on =ser 2nput
Cy adding a Text 'nput, we can take to updating our bold text with whatever the user types into the text input.
,ote &e updated the function a bit and set the id to boldStuff1.
Va%a3crit "ode&
.script type01text2>a4ascript1/
fnction changeText28:;
4ar serInpt 0 docment6get%lement'yId8DserInptD:64ale*
docment6get%lement'yId8D$oldStff2D:6innerHT&C 0 serInpt*
<
.2script/
.p/9elcome to the site .$ id0D$oldStff2D/dde.2$/ .2p/
.inpt type0DtextD id0DserInptD 4ale0D%nter Text HereD 2/
.inpt type0D$ttonD onclic=0DchangeText28:D 4ale0D!hange TextD2/
*islay&
6elcome to the site %nter Text Here
6nter Text H
4hanging 8T>L with inner8T>L
.ou can also insert HTML into your elements in the exact same way. Let#s say we didn#t like the text that was
displayed in our paragraph and wanted to updated it with some color. The following code will take the old black
text and make it bright white. The only thing we#re doing different here is inserting the html element span to
change the color.
Va%a3crit "ode&
.script type01text2>a4ascript1/
fnction changeTextL8:;
4ar oldHT&C 0 docment6get%lement'yId8DparaD:6innerHT&C*
4ar ne7HT&C 0 1.span style0Dcolor:BffffffD/1 ? oldHT&C ? 1.2span/1*
docment6get%lement'yId8DparaD:6innerHT&C 0 ne7HT&C*
<
.2script/
.p id0DparaD/9elcome to the site .$ id0D$oldStffLD/dde.2$/ .2p/
.inpt type0D$ttonD onclic=0DchangeTextL8:D 4ale0D!hange TextD2/
*islay&
6elcome to the site dde
This was a pretty simple example for changing the HTML of an element. "ll we did was take the old text that
was in the para)raph tag and surround it in a span tag to change the color. However, there are many more
things you can do by changing an element#s HTML, so don#t forget this useful tool0
/3
Web Tech Notes FX Engineering
College, Tirunelveli
A,'T <
$"K" !6@KL6T
/ession Trac!ing
(. 6hat is 3ession TrackingK
There are a number of roblems that arise from the fact that 3TT( is a 7stateless7 rotocol# 8n
articular, 1hen you are doing on9line shoing, it is a real annoyance that the Web server
can:t easily remember revious transactions# This ma!es alications li!e shoing carts very
roblematic; 1hen you add an entry to your cart, ho1 does the server !no1 1hat:s already in
your cart< Even if servers did retain conte)tual information, you:d still have roblems 1ith e9
commerce# When you move from the age 1here you secify 1hat you 1ant to buy =hosted on
the regular Web server> to the age that ta!es your credit card number and shiing address
=hosted on the secure server that uses ??@>, ho1 does the server remember 1hat you 1ere
buying<
There are three tyical solutions to this roblem.
1# Coo#ies$ Aou can use 3TT( coo!ies to store information about a shoing session,
and each subseBuent connection can loo! u the current session and then e)tract
information about that session from some location on the server machine# This is an
e)cellent alternative, and is the most 1idely used aroach# 3o1ever, even though
servlets have a high9level and easy9to9use interface to coo!ies, there are still a number
of relatively tedious details that need to be handled;
& E)tracting the coo!ie that stores the session identifier from the other coo!ies
=there may be many, after all>,
& ?etting an aroriate e)iration time for the coo!ie =sessions interruted by 2"
hours robably should be reset>, and
& Cssociating information on the server 1ith the session identifier =there may be
far too much information to actually store it in the coo!ie, lus sensitive data li!e
credit card numbers should never go in coo!ies>#
2# URL Re%ritin&$ Aou can aend some e)tra data on the end of each D2@ that
identifies the session, and the server can associate that session identifier 1ith data it
has stored about that session# This is also an e)cellent solution, and even has the
advantage that it 1or!s 1ith bro1sers that don:t suort coo!ies or 1here the user has
disabled coo!ies# 3o1ever, it has most of the same roblems as coo!ies, namely that
the server9side rogram has a lot of straightfor1ard but tedious rocessing to do# 8n
addition, you have to be very careful that every D2@ returned to the user =even via
indirect means li!e L&/a.&1 fields in server redirects> has the e)tra information
/"
Web Tech Notes FX Engineering
College, Tirunelveli
aended# Cnd, if the user leaves the session and comes bac! via a boo!mar! or lin!,
the session information can be lost#
3# 'i((en for) fiel(s$ 3T4@ forms have an entry that loo!s li!e the follo1ing; <I!PUT
TYPE3"HIDDE!" !-ME3"sess.&1" ;-LUE3"...",# This means that, 1hen
the form is submitted, the secified name and value are included in the 9ET or PO2T
data# This can be used to store information about the session# 3o1ever, it has the ma$or
disadvantage that it only 1or!s if every age is dynamically generated, since the 1hole
oint is that each session has a uniBue identifier#
?ervlets rovide an outstanding technical solution; the H#2ess.&1 C(8# This is a high9
level interface built on to of coo!ies or D2@9re1riting# 8n fact, on many servers, they use
coo!ies if the bro1ser suorts them, but automatically revert to D2@9re1riting 1hen coo!ies
are unsuorted or e)licitly disabled# Eut the servlet author doesn:t need to bother 1ith many
of the details, doesn:t have to e)licitly maniulate coo!ies or information aended to the
D2@, and is automatically given a convenient lace to store data that is associated 1ith each
session#
). The 3ession Tracking A72
Dsing sessions in servlets is Buite straightfor1ard, and involves loo!ing u the session ob$ect
associated 1ith the current reBuest, creating a ne1 session ob$ect 1hen necessary, loo!ing u
information associated 1ith a session, storing information in a session, and discarding
comleted or abandoned sessions#
&'( Looking u% t)e Htt%Session ob*ect associated +it) t)e current re,uest'
This is done by calling the 'e2ess.&1 method of H#2er<)e(e=0es# 8f this returns
null, you can create a ne1 session, but this is so commonly done that there is an otion to
automatically create a ne1 session if there isn:t one already# Fust ass r0e to
'e2ess.&1# Thus, your first ste usually loo!s li!e this;
HttpSession session = request.getSession(true);
&'& Looking u% Information !ssociated +it) a Session'
H#2ess.&1 ob$ects live on the serverG they:re $ust automatically associated 1ith the
reBuester by a behind9the9scenes mechanism li!e coo!ies or D2@9re1riting# These session
ob$ects have a builtin data structure that let you store any number of !eys and associated
values# 8n version 2#1 and earlier of the servlet C(8, you use 'e;a)0e>"?e@"A to loo! u
a reviously stored value# The return tye is OBCe/, so you have to do a tyecast to
1hatever more secific tye of data 1as associated 1ith that !ey in the session# The return
value is 10)) if there is no such attribute# 8n version 2#2, 'e;a)0e is derecated in favor of
'e-r.B0e, both because of the better naming match 1ith se-r.B0e =the
match for 'e;a)0e is #0;a)0e, not se;a)0e>, and because se-r.B0e lets
you use an attached 3tt?essionEinding@istener to monitor values, 1hile #0;a)0e doesn:t#
/%
Web Tech Notes FX Engineering
College, Tirunelveli
Nevertheless, since fe1 commercial servlet engines yet suort version 2#2, 8:ll use
'e;a)0e in my e)amles# 3ere:s one reresentative e)amle, assuming 2"&##.1'Car
is some class you:ve defined yourself that stores information on items being urchased#
HttpSession session = request.getSession(true);
2"&##.1'Car #re<.&0sIems 3
>2"&##.1'CarAsess.&1.'e;a)0e>"#re<.&0sIems"AD
if (previousItems != null) {
doSomethingWith(previousItems);
} else {
previousItems = new Shopping!rt(...);
doSomething"lseWith(previousItems);
}
8n most cases, you have a secific attribute name in mind, and 1ant to find the value =if any>
already associated 1ith it# 3o1ever, you can also discover all the attribute names in a given
session by calling 'e;a)0e!ames, 1hich returns a 2r.1' array# 8n version 2#2, use
'e-r.B0e!ames, 1hich has a better name and 1hich is more consistent in that it
returns an E10mera.&1, $ust li!e the 'eHea+ers and 'eParameer!ames
methods of H#2er<)e(e=0es#
Although the data that was e/licitly associated with a session is the art
you care most about+ there are some other ieces o# in#ormation that are
sometimes use#ul as well.
&etI($ This method returns the uniBue identifier generated for each session# 8t is
sometimes used as the !ey name 1hen there is only a single value associated 1ith a
session, or 1hen logging information about revious sessions#
isNe%$ This returns r0e if the client =bro1ser> has never seen the session, usually
because it 1as $ust created rather than being referenced by an incoming client reBuest#
8t returns *a)se for ree)isting sessions#
&etCre*tionTi)e$ This returns the time, in milliseconds since the eoch, at 1hich the
session 1as made# To get a value useful for rinting out, ass the value to the Dae
constructor or the seT.meI1M.)).s method of 9re'&r.a1Ca)e1+ar#
&etL*stA++esse(Ti)e$ This returns the time, in milliseconds since the eoch, at 1hich
the session 1as last sent from the client#
&etM*,In*+ti-eInter-*l$ This returns the amount of time, in seconds, that a session
should go 1ithout access before being automatically invalidated# C negative value
indicates that the session should never timeout#
&'- !ssociating Information +it) a Session
Cs discussed in the revious section, you read information associated 1ith a session by using
'e;a)0e =or 'e-r.B0e in version 2#2 of the servlet sec># To secify information,
you use #0;a)0e =or se-r.B0e in version 2#2>, sulying a !ey and a value# Note
/&
Web Tech Notes FX Engineering
College, Tirunelveli
that #0;a)0e relaces any revious values# ?ometimes that:s 1hat you 1ant =as 1ith the
re*err.1'Pa'e entry in the e)amle belo1>, but other times you 1ant to retrieve a
revious value and augment it =as 1ith the #re<.&0sIems entry belo1># 3ere:s an
e)amle;
HttpSession session = request.getSession(true);
sess.&1.#0;a)0e>"re*err.1'Pa'e"6 re=0es.'eHea+er>"(e*erer"AAD
Shopping!rt previousItems =
(Shopping!rt)session.get#!lue($previousItems$);
if (previousItems == null) {
previousItems = new Shopping!rt(...);
}
String itemI% = request.get&!r!meter($itemI%$);
previousItems.!dd"ntr'(!t!log.get"ntr'(itemI%));
(( )ou still h!ve to do put#!lue* not +ust modif' the ,!rt* sin,e
(( the ,!rt m!' -e new !nd thus not !lre!d' stored in the session.
sess.&1.#0;a)0e>"#re<.&0sIems"6 #re<.&0sIemsAD
C. E/amle& 3howing 3ession 2n#ormation
3ere is a simle e)amle that generates a Web age sho1ing some information about the
current session# Aou can also do1nload the source or try it on9line#
p!,.!ge h!ll;
import +!v!.io./;
import +!v!0.servlet./;
import +!v!0.servlet.http./;
import +!v!.net./;
import +!v!.util./;
(// Simple e0!mple of session tr!,.ing. See the shopping
/ ,!rt e0!mple for ! more det!iled one.
/ 1&2
/ &!rt of tutori!l on servlets !nd 3S& th!t !ppe!rs !t
/ http4((www.!pl.+hu.edu(5h!ll(+!v!(Servlet67utori!l(
/ 8999 :!rt' H!ll; m!' -e freel' used or !d!pted.
/(
pu-li, ,l!ss ShowSession e0tends HttpServlet {
pu-li, void do;et(HttpServlet<equest request*
HttpServlet<esponse response)
throws Servlet"0,eption* I="0,eption {
HttpSession session = request.getSession(true);
response.setontent7'pe($te0t(html$);
&rintWriter out = response.getWriter();
String title = $Se!r,hing the We-$;
String he!ding;
Integer !,,essount = new Integer(>);;
if (session.is?ew()) {
he!ding = $Wel,ome* ?ew,omer$;
} else {
he!ding = $Wel,ome @!,.$;
/+
Web Tech Notes FX Engineering
College, Tirunelveli
Integer oldA,,essount =
(( Bse getAttri-ute* not get#!lue* in version
(( C.C of servlet A&I.
(Integer)session.get#!lue($!,,essount$);
if (oldA,,essount != null) {
!,,essount =
new Integer(oldA,,essount.int#!lue() D 8);
}
}
(( Bse putAttri-ute in version C.C of servlet A&I.
session.put#!lue($!,,essount$* !,,essount);

out.println(ServletBtilities.he!dWith7itle(title) D
$1@=%) @;=E=<=F$GH%HI"JF$2Fn$ D
$1H8 AEI;?=F$"?7"<F$2$ D he!ding D $1(H82Fn$ D
$1HC2Inform!tion on )our Session41(HC2Fn$ D
$17A@E" @=<%"<=8 AEI;?="?7"<2Fn$ D
$17< @;=E=<=F$GHHA%>>F$2Fn$ D
$ 17H2Info 7'pe17H2#!lueFn$ D
$17<2Fn$ D
$ 17%2I%Fn$ D
$ 17%2$ D session.getId() D $Fn$ D
$17<2Fn$ D
$ 17%2re!tion 7imeFn$ D
$ 17%2$ D new %!te(session.getre!tion7ime()) D $Fn$ D
$17<2Fn$ D
$ 17%27ime of E!st A,,essFn$ D
$ 17%2$ D new %!te(session.getE!stA,,essed7ime()) D $Fn$ D
$17<2Fn$ D
$ 17%2?um-er of &revious A,,essesFn$ D
$ 17%2$ D !,,essount D $Fn$ D
$1(7A@E"2Fn$ D
$1(@=%)21(H7:E2$);
}
pu-li, void do&ost(HttpServlet<equest request*
HttpServlet<esponse response)
throws Servlet"0,eption* I="0,eption {
do;et(request* response);
}
}
3ere:s a tyical result, sho1n after visiting the age several 1ithout Buitting the bro1ser in
bet1een;
/.
Web Tech Notes FX Engineering
College, Tirunelveli
8andling 4oo!ies
. '%er%iew o# "ookies
Coo!ies are small bits of te)tual information that a Web server sends to a bro1ser and that the
bro1ser returns unchanged 1hen visiting the same Web site or domain later# Ey having the
server read information it sent the client reviously, the site can rovide visitors 1ith a number
of conveniences;
I(entifyin& * user (urin& *n e.+o))er+e session$ 4any on9line stores use a
7shoing cart7 metahor in 1hich the user selects an item, adds it to his shoing cart,
then continues shoing# ?ince the 3TT( connection is closed after each age is sent,
1hen the user selects a ne1 item for his cart, ho1 does the store !no1 that he is the
same user that ut the revious item in his cart< Coo!ies are a good 1ay of
accomlishing this# 8n fact, this is so useful that servlets have an C(8 secifically for this,
and servlet authors don:t need to maniulate coo!ies directly to ma!e use of it# This is
discussed in the tutorial section on ?ession Trac!ing#
A-oi(in& usern*)e *n( /*ss%or($ 4any large sites reBuire you to register in order to
use their services, but it is inconvenient to remember the username and ass1ord#
Coo!ies are a good alternative for lo19security sites# When a user registers, a coo!ie is
//
Web Tech Notes FX Engineering
College, Tirunelveli
sent 1ith a uniBue user 86# When the client reconnects at a later date, the user 86 is
returned, the server loo!s it u, determines it belongs to a registered user, and doesn:t
reBuire an e)licit username and ass1ord#
Custo)i0in& * site$ 4any 7ortal7 sites let you customiHe the loo! of the main age#
They use coo!ies to remember 1hat you 1anted, so that you get that result initially ne)t
time# 8:ll give an e)amle li!e this later in this section of the tutorial#
Fo+usin& *(-ertisin&$ The search engines charge their customers much more for
dislaying 7directed7 ads than 7random7 ads# That is, if you do a search on 7Fava
?ervlets7, a search site can charge much more for an ad for a servlet develoment
environment than an ad for an on9line travel agent# In the other hand, if the search had
been 7Eali 3otels7, the situation 1ould be reversed# The roblem is that they have to
sho1 a random ad 1hen you first arrive and haven:t yet erformed a search, as 1ell as
1hen you search on something that doesn:t match any ad categories# Coo!ies let them
remember 7Ih, that:s the erson 1ho 1as searching for such and such reviously7 and
dislay an aroriate =read 7high riced7> ad instead of a random =read 7chea7> one#
No1, roviding convenience to the user and added value to the site o1ner is the urose
behind coo!ies# Cnd desite much misinformation, coo!ies are not a serious security threat#
Coo!ies are never interreted or e)ecuted in any 1ay, and thus can:t be used to insert viruses
or attac! your system in any 1ay# Furthermore, since bro1sers generally only accet 20
coo!ies er site and 300 coo!ies total, and each coo!ie is limited to "JE, coo!ies cannot be
used to fill u someone:s dis! or launch other denial of service attac!s# 3o1ever, even though
they don:t resent a serious security threat, they can reseent a significant threat to privacy#
First, some eole don:t li!e the fact that search engines can remember that they:re the erson
that usually does searches on such and such a toic# For e)amle, they might search for $ob
oenings or health data, and don:t 1ant some banner ad tiing off their co1or!ers ne)t time
they do a search# Even 1orse, t1o search engines could share data on a user by both loading
small images off a third arty site, 1here that third arty uses coo!ies and shares the data 1ith
both search engines# =Netscae, ho1ever, rovides a nice feature that lets you refuse coo!ies
from sites other than that to 1hich you connected, but 1ithout disabling coo!ies altogether#>
This tric! can even be e)loited via email if you use an 3T4@9enabled email reader that
7suorts7 coo!ies, as Iutloo! E)ress does# Thus, eole could send you email that loads
images, attach coo!ies to those images, then later identify you =email address and all> 1hen
you 1ent to their site#
'r+ a site that ought to ha%e much higher security standards might let users
ski user name and asswords %ia cookies. 5or e/amle+ some o# the big
on-line bookstores use cookies to remember users+ and let you order
without reentering much o# your ersonal in#ormation. Howe%er+ they donDt
actually dislay the #ull credit card number+ and only let you send books to
an address that was entered when you did enter the credit card in #ull or
use the username and assword. As a result+ someone using the ersonDs
comuter (or stealing their cookie #ile! could do no more harm than sending
100
Web Tech Notes FX Engineering
College, Tirunelveli
a big book order to the credit card ownerDs address+ where it could be
re#used. Howe%er+ smaller comanies might not be so care#ul+ and access to
someoneDs comuter or cookie #ile could result in loss o# %aluable ersonal
in#ormation. E%en worse+ incometent sites might embed credit card or
other sensiti%e in#ormation directly in the cookies themsel%es+ rather than
using innocuous identi#iers which are only linked to real users on the ser%er.
The oint o# all this is two#old. 5irst+ due to real and ercei%ed ri%acy
roblems+ some users turn o## cookies. 3o+ e%en when you use cookies to
gi%e added %alue to a site+ your site shouldnDt depend on them. 3econd+ as
the author o# ser%lets that use cookies+ you should be care#ul not to trust
cookies #or articularly sensiti%e in#ormation+ since this would oen the user
u to risks i# somebody accessed their comuter or cookie #iles.
). The 3er%let "ookie A72
To send coo!ies to the client, a servlet 1ould create one or more coo!ies 1ith the aroriate
names and values via 1e% C&&?.e>1ame6 <a)0eA =section 2#1>, set any desired
otional attributes via /&&?.e.seEFF =section 2#2>, and add the coo!ies to the resonse
headers via res#&1se.a++C&&?.e>/&&?.eA =section 2#3># To read incoming coo!ies,
call re=0es.'eC&&?.es>A, 1hich returns an array of C&&?.e ob$ects# 8n most cases,
you loo do1n this array until you find the one 1hose name ='e!ame> matches the name
you have in mind, then call 'e;a)0e on that C&&?.e to see the value associated 1ith that
name# This is discussed in section 2#"#
&'( Creating Cookies
C Coo!ie is created by calling the C&&?.e constructor, 1hich ta!es t1o strings; the coo!ie
name and the coo!ie value# Neither the name nor the value should contain 1hitesace or any
of;
K L ( ) = * $ ( M N 4 ;
&'& eading and S%ecif.ing Cookie !ttributes
Eefore adding the coo!ie to the outgoing headers, you can loo! u or set attributes of the
coo!ie# 3ere:s a summary;
&etCo))ent1setCo))ent
KetsLsets a comment associated 1ith this coo!ie#
&et2o)*in1set2o)*in
KetsLsets the domain to 1hich coo!ie alies# Normally, coo!ies are returned only to
the e)act hostname that sent them# Aou can use this method to instruct the bro1ser to
101
Web Tech Notes FX Engineering
College, Tirunelveli
return them to other hosts 1ithin the same domain# Note that the domain should start
1ith a dot =e#g# ##re1"a))./&m>, and must contain t1o dots for non9country domains
li!e ./&m, .e+0, and .'&<, and three dots for country domains li!e ./&.0? and
.e+0.es#
&etM*,A&e1setM*,A&e
KetsLsets ho1 much time =in seconds> should elase before the coo!ie e)ires# 8f you
don:t set this, the coo!ie 1ill last only for the current session =i#e# until the user Buits the
bro1ser>, and 1ill not be stored on dis!# ?ee the L&1'L.<e+C&&?.e class belo1,
1hich defines a subclass of C&&?.e 1ith a ma)imum age automatically set one year in
the future#
&etN*)e1setN*)e
KetsLsets the name of the coo!ie# The name and the value are the t1o ieces you
virtually al1ays care about# ?ince the 'eC&&?.es method of
H#2er<)e(e=0es returns an array of C&&?.e ob$ects, it is common to loo
do1n this array until you have a articular name, then chec! the value 1ith getMalue#
?ee the 'eC&&?.e;a)0e method sho1n belo1#
&et"*t31set"*t3
KetsLsets the ath to 1hich this coo!ie alies# 8f you don:t secify a ath, the coo!ie is
returned for all D2@s in the same directory as the current age as 1ell as all
subdirectories# This method can be used to secify something more general# For
e)amle, s&meC&&?.e.sePa">"/"A secifies that all ages on the server
should receive the coo!ie# Note that the ath secified must include the current
directory#
&etSe+ure1setSe+ure
KetsLsets the B&&)ea1 value indicating 1hether the coo!ie should only be sent over
encryted =i#e# ??@> connections#
&et!*lue1set!*lue
KetsLsets the value associated 1ith the coo!ie# Cgain, the name and the value are the
t1o arts of a coo!ie that you almost al1ays care about, although in a fe1 cases a
name is used as a boolean flag, and its value is ignored =i#e the e)istence of the name
means true>#
&et!ersion1set!ersion
102
Web Tech Notes FX Engineering
College, Tirunelveli
KetsLsets the coo!ie rotocol version this coo!ie comlies 1ith# Mersion 0, the default,
adheres to the original Netscae secification# Mersion 1, not yet 1idely suorted,
adheres to 2FC 210/#
&'- $lacing Cookies in t)e es%onse Headers
The coo!ie is added to the 2e-C&&?.e resonse header by means of the a++C&&?.e
method of H#2er<)e(es#&1se# 3ere:s an e)amle;
oo.ie useroo.ie = new oo.ie($user$* $uid8COP$);
response.!ddoo.ie(useroo.ie);
&'/ eading Cookies from t)e Client
To send coo!ies to the client, you created a C&&?.e then used a++C&&?.e to send a 2e-
C&&?.e 3TT( resonse header# This 1as discussed above in section 2#1# To read the
coo!ies that come bac! from the client, you call 'eC&&?.es on the
H#2er<)e(e=0es# This returns an array of C&&!ie ob$ects corresonding to the
values that came in on the C&&?.e 3TT( reBuest header# Ince you have this array, you
tyically loo do1n it, calling 'e!ame on each C&&?.e until you find one matching the
name you have in mind# Aou then call 'e;a)0e on the matching Coo!ie, doing some
rocessing secific to the resultant value# This is such a common rocess that the follo1ing
section resents a simle 'eC&&?.e;a)0e method that, given the array of coo!ies, a
name, and a default value, returns the value of the coo!ie matching the name, or, if there is no
such coo!ie, the designated default value#
C. 3ome Minor "ookie Utilities
3ere are some simle but useful utilities for dealing 1ith coo!ies#
-'( #etting t)e 0alue of a Cookie +it) a S%ecified "ame
3ere:s a section of ?ervletDtilities#$ava that slightly simlifies the retrieval of a coo!ie value
given a coo!ie name by looing through the array of available C&&?.e ob$ects, returning the
value of any C&&?.e 1hose name matches the inut# 8f there is no match, the designated
default value is returned#
pu-li, st!ti, String getoo.ie#!lue(oo.ieKL ,oo.ies*
String ,oo.ie?!me*
String def!ult#!lue) {
for(int i=>; i1,oo.ies.length; iDD) {
oo.ie ,oo.ie = ,oo.iesKiL;
if (,oo.ie?!me.equ!ls(,oo.ie.get?!me()))
return(,oo.ie.get#!lue());
}
return(def!ult#!lue);
}
103
Web Tech Notes FX Engineering
College, Tirunelveli
-'& LongLi1edCookie'*a1a 23o+nload source code4
3ere:s a small class that you can use instead of C&&?.e if you 1ant your coo!ie to
automatically ersist 1hen the client Buits the bro1ser#
p!,.!ge h!ll;
import +!v!0.servlet.http./;
pu-li, ,l!ss EongEivedoo.ie e0tends oo.ie {
pu-li, st!ti, fin!l int S"=?%SQ&"<Q)"A< = J>/J>/CP/OJI;

pu-li, EongEivedoo.ie(String n!me* String v!lue) {
super(n!me* v!lue);
seMaF-'e>2ECO!D28PE(8YE-(AD
}
}
J. E/amle& A "ustomi>ed 3earch Engine
2nter#ace
3ere:s a variation of the ?earchEngines e)amle sho1n in the section on the 3TT( status line#
8n this version, the front end is dynamically generated instead of coming from a static 3T4@
file# Then, the servlet that reads the arameters and for1ards them to the aroriate search
engine also returns coo!ies to the client that list these values# Ne)t time the client visits the
front end, the coo!ie values are used to reload the form fields 1ith the most recently used
entries#
/'( Searc)EnginesFrontEnd'*a1a
This servlet builds the form9based front end to the search engine servlet# Ct first blush, the
outut loo!s $ust li!e the age given by the static 3T4@ age resented in the section on 3TT(
status codes# 3ere, ho1ever, selected values are remembered in coo!ies =set by the
C0s&m.Ge+2ear/"E1'.1es servlet that this age sends data to>, so if the user comes
bac! to the same age at a later time =even after Buitting the bro1ser and restarting>, the age
is initialiHed 1ith the values from the revious search#
9ou can also download the source or try it on-line. 8ote that code uses
3er%letUtilities.,a%a+ #or the 'eC&&?.e;a)0e method (shown abo%e! and
#or "ea+W."T.)e #or generating art o# the HTML. 2t also uses the
L&1'L.<e+C&&?.e class+ shown abo%e+ #or creating a C&&?.e that
automatically has a long-term e/iration date.
p!,.!ge h!ll;
import +!v!.io./;
import +!v!0.servlet./;
import +!v!0.servlet.http./;
import +!v!.net./;
10"
Web Tech Notes FX Engineering
College, Tirunelveli
pu-li, ,l!ss Se!r,h"nginesHront"nd e0tends HttpServlet {
pu-li, void do;et(HttpServlet<equest request*
HttpServlet<esponse response)
throws Servlet"0,eption* I="0,eption {
C&&?.eHI /&&?.es 3 re=0es.'eC&&?.es>AD
2r.1' sear/"2r.1' 3
2er<)eU.)..es.'eC&&?.e;a)0e>/&&?.es6
"sear/"2r.1'"6
"Ja<a Pr&'ramm.1'"AD
2r.1' 10m(es0)s 3
2er<)eU.)..es.'eC&&?.e;a)0e>/&&?.es6
"10m(es0)s"6
"10"AD
2r.1' sear/"E1'.1e 3
2er<)eU.)..es.'eC&&?.e;a)0e>/&&?.es6
"sear/"E1'.1e"6
"'&&')e"AD
response.setontent7'pe($te0t(html$);
&rintWriter out = response.getWriter();
String title = $Se!r,hing the We-$;
out.println(ServletBtilities.he!dWith7itle(title) D
$1@=%) @;=E=<=F$GH%HI"JF$2Fn$ D
$1H8 AEI;?=F$"?7"<F$2Se!r,hing the We-1(H82Fn$ D
$Fn$ D
$1H=<: A7I=?=F$(servlet(h!ll.ustomiRedSe!r,h"nginesF$2Fn$ D
$1"?7"<2Fn$ D
$Se!r,h String4Fn$ D
$1I?&B7 7)&"=F$7"S7F$ ?A:"=F$se!r,hStringF$Fn$ D
$ #AEB"=F$$ D sear/"2r.1' D $F$21@<2Fn$ D
$<esults to Show &er &!ge4Fn$ D
$1I?&B7 7)&"=F$7"S7F$ ?A:"=F$num<esultsF$Fn$ D
$ #AEB"=$ D 10m(es0)s D $ SIT"=O21@<2Fn$ D
$1I?&B7 7)&"=F$<A%I=F$ ?A:"=F$se!r,h"ngineF$Fn$ D
$ #AEB"=F$googleF$$ D
/"e/?e+>"'&&')e"6 sear/"E1'.1eA D $2Fn$ D
$;oogle UFn$ D
$1I?&B7 7)&"=F$<A%I=F$ ?A:"=F$se!r,h"ngineF$Fn$ D
$ #AEB"=F$infosee.F$$ D
/"e/?e+>".1*&see?"6 sear/"E1'.1eA D $2Fn$ D
$Infosee. UFn$ D
$1I?&B7 7)&"=F$<A%I=F$ ?A:"=F$se!r,h"ngineF$Fn$ D
$ #AEB"=F$l',osF$$ D
/"e/?e+>")@/&s"6 sear/"E1'.1eA D $2Fn$ D
$E',os UFn$ D
$1I?&B7 7)&"=F$<A%I=F$ ?A:"=F$se!r,h"ngineF$Fn$ D
$ #AEB"=F$hot-otF$$ D
/"e/?e+>""&B&"6 sear/"E1'.1eA D $2Fn$ D
$Hot@otFn$ D
$1@<2Fn$ D
$1I?&B7 7)&"=F$SB@:I7F$ #AEB"=F$Se!r,hF$2Fn$ D
$1("?7"<2Fn$ D
$1(H=<:2Fn$ D
$Fn$ D
$1(@=%)2Fn$ D
10%
Web Tech Notes FX Engineering
College, Tirunelveli
$1(H7:E2Fn$);
}
priv!te String ,he,.ed(String n!me8* String n!meC) {
if (n!me8.equ!ls(n!meC))
return($ H"V"%$);
else
return($$);
}
}
/'& Customi5edSearc)Engines'*a1a
The 2ear/"E1'.1esFr&1E1+ servlet sho1n above sends its data to the
C0s&m.Ge+2ear/"E1'.1es servlet# 8n many resects, it is $ust li!e the
2ear/"E1'.1es servlet sho1n in the section on 3TT( status codes# 3o1ever, in addition
to constructing a D2@ for a search engine and sending a redirection resonse to the client, the
servlet also sends coo!ies recording the user data# These coo!ies 1ill, in turn, be used by the
servlet building the front end to initialiHe the entries in the 3T4@ forms#
p!,.!ge h!ll;
import +!v!.io./;
import +!v!0.servlet./;
import +!v!0.servlet.http./;
import +!v!.net./;
(// A v!rition of the Se!r,h"ngine servlet th!t uses
/ ,oo.ies to remem-er users ,hoi,es. 7hese v!lues
/ !re then used -' the Se!r,h"ngineHront"nd servlet
/ to ,re!te the form6-!sed front end with these
/ ,hoi,es preset.
/
K Par &* 0&r.a) &1 ser<)es a1+ J2P "a a##ears a
K "#$//%%%.a#).C"0.e+0/L"a))/Ca<a/2er<)e-T0&r.a)/
K 1MMM Mar@ Ha))D ma@ Be *ree)@ 0se+ &r a+a#e+.
K/
#0B)./ /)ass C0s&m.Ge+2ear/"E1'.1es eFe1+s H#2er<)e N
#0B)./ <&.+ +&9e>H#2er<)e(e=0es re=0es6
10&
Web Tech Notes FX Engineering
College, Tirunelveli
H#2er<)e(es#&1se res#&1seA
"r&%s 2er<)eEF/e#.&16 IOEF/e#.&1 N

String se!r,hString =
request.get&!r!meter($se!r,hString$);
oo.ie se!r,hStringoo.ie =
new EongEivedoo.ie($se!r,hString$* se!r,hString);
response.!ddoo.ie(se!r,hStringoo.ie);
se!r,hString = B<E"n,oder.en,ode(se!r,hString);
String num<esults = request.get&!r!meter($num<esults$);
oo.ie num<esultsoo.ie =
new EongEivedoo.ie($num<esults$* num<esults);
response.!ddoo.ie(num<esultsoo.ie);
String se!r,h"ngine =
request.get&!r!meter($se!r,h"ngine$);
oo.ie se!r,h"ngineoo.ie =
new EongEivedoo.ie($se!r,h"ngine$* se!r,h"ngine);
response.!ddoo.ie(se!r,h"ngineoo.ie);
2ear/"2#e/HI /&mm&12#e/s 3 2ear/"2#e/.'eC&mm&12#e/s>AD
*&r>.1 .30D .</&mm&12#e/s.)e1'"D .OOA N
2ear/"2#e/ sear/"2#e/ 3 /&mm&12#e/sH.ID
.* >sear/"2#e/.'e!ame>A.e=0a)s>sear/"E1'.1eAA N
2r.1' 0r) 3
10+
Web Tech Notes FX Engineering
College, Tirunelveli
sear/"2#e/.ma?eU(L>sear/"2r.1'6 10m(es0)sAD
res#&1se.se1+(e+.re/>0r)AD
re0r1D
P
P
res#&1se.se1+Err&r>res#&1se.2C8!OT8FOU!D6
"!& re/&'1.Ge+ sear/" e1'.1e
s#e/.*.e+."AD
P
#0B)./ <&.+ +&P&s>H#2er<)e(e=0es re=0es6
H#2er<)e(es#&1se res#&1seA
"r&%s 2er<)eEF/e#.&16 IOEF/e#.&1 N
+&9e>re=0es6 res#&1seAD
P
P
/'- Searc)EnginesFrontEnd Out%ut
3ere:s the front end as it loo!s after the user tyes in some values or if the user comes bac! to
the age in the same or a later session, after having tyed in the values in the revious visit#
10.
Web Tech Notes FX Engineering
College, Tirunelveli
10/
Web Tech Notes FX Engineering
College, Tirunelveli
/'/ Customi5edSearc)Engines Out%ut
.A<A /E:<LET ATA /T3:ADE
.B4F /ervletF .ava>ailF and >/Access hoo! up
fa&GHI1I,I
Hosted :; $ul G:
H@6@6RA6!'T6
.ou should have tomcat or some other servlet-Bsp working on your maching. you should know how to
create a database with msaccess and use the data sources administrative tool. you should run this
source on a local machine.
',T@)2A/T'),
$ust thought i#ll pass my example and show how easy servlets, databases and email can be incorporated.
&hy5
Cecause beginners like myself need help sometimes.
26!/@'HT'),
This class represents a simple movie database that gets updated through an HTML Form, !ervlet, and
$2C/. "lso it sends email to an specified email using $avaMail.
/"AT'),!
/aution: This servlet#s email method needs to be uncommented and provided with appropiate email
110
Web Tech Notes FX Engineering
College, Tirunelveli
server and email adddress information. )therwise, it will simply Bust update the database.
/aution; This servlet is not efficient, is not recommended for use only for educational purposes.
T))L!
Tools ' used to create this /lass
)perating !ystem &indows ;GGG Hrofessional
2atabase M!"ccess ;GGG
6ditor $/reator
$!H-!ervlet Tomcat <.;.;
Language $ava ;
$ava ; extensions $avaMail
2"T"C"!6 ',F)@M"T'),
This class was run under a L)/"L machine. ' provide the class only, you must create the 2atabase with
three tables using M!"ccess and add its appropiate 2ata !ource name through &indows ;GGG
administrative tools.
The 2efault data source name this class connects to is
Movies
The 2efault Tables this class updtates are
"ctionMovies
/omedyMovies
2ramaMovies
The 2efault Fields for each Table are
Title, .ear, Type, Length
)f course you can change the format of the database but these changes must be reflected on the class.
/),/LA!'),
!o, copy class and html form code below and have fun with it. Hopefully, if you do everything right, it
should work.
/)26
--/reator Justavo 2elgado
--The class Movie)nline was inspired through the readings of Marty Hall#s /ore !ervlets
--and $ava!erverHages, Michael Meloan#s 2ukeCakery example at
--http?@@developer)*ava)sun)co'@developer@technicalArticles@atabase@du!esba!ery@,
--and )reilly#s $ava ,etwork Hrogramming ;nd 6dition
--This class is not efficient, it Bust gives an idea of how to easily incorporate
--$2C/, !ervlets and $avaMail
import Bava.io.E9
import Bava.s(l.E9
import Bavax.servlet.E9
import Bavax.servlet.http.E9
import Bavax.mail.E9
import Bavax.mail.internet.E9
import Bava.util.E9
public class Movie)nline extends Http!ervlet M
!tring type, title, year, length, format, message9
/onnection connect9
111
Web Tech Notes FX Engineering
College, Tirunelveli

public void doJet3Http!ervlet@e(uest re(uest, Http!ervlet@esponse response4
throws !ervlet6xception, ')6xception M


--6stablishing connection to 2atabase
tryM
!tring url I %BdbcodbcMovies%9
/lass.for,ame3%sun.Bdbc.odbc.$dbc)dbc2river%49
connect I 2riverManager.get/onnection3url, %gabo%, %hi%49
message I %/onnection !uccesful%9
N
catch3/lass,otFound6xception cnfex4M
cnfex.print!tackTrace349
N
catch3!RL6xception s(lex4M
s(lex.print!tackTrace349
N
catch36xception excp4M
excp.print!tackTrace349
N

--Jathering parameters from HTML form

type I re(uest.getHarameter3%category%49
title I re(uest.getHarameter3%title%49
year I re(uest.getHarameter3%year%49
format I re(uest.getHarameter3%format%49
length I re(uest.getHarameter3%length%49
--)utputing a freindly message to user
response.set/ontentType3%text-html%49
Hrint&riter out I response.get&riter349
out.println3%*HTML+*H6"2+*T'TL6+% D message D %*-T'TL6+*-H6"2+% D
%*C)2. CJ/)L)@ I &H'T6+Zn% D
%*H:+% D message D %*-H:+Zn%49



--/hecking what database table should the html form information go
if 3type.e(uals3%comedy%44M
tryM
!tatement stmt I connect.create!tatement349
!tring (uery I %',!6@T ',T) /omedyMovies 3% D
%Title, .ear, Type, Length% D
%4 K"LA6! 3#% D
title D %#, #% D
year D %#, #%D
format D %#, #%D
length D %#4%9
int result I stmt.executeApdate3(uery49
stmt.close349
N
112
Web Tech Notes FX Engineering
College, Tirunelveli

catch3!RL6xception ex4M
while 3ex 0I null4M
!ystem.out.println3%Zn6rrorZn%49
!ystem.out.println3%Message % D ex.getMessage3449
!ystem.out.println3%!RL!tate % D ex.get!RL!tate3449
!ystem.out.println3%6rror /ode % D ex.get6rror/ode3449
ex I ex.get,ext6xception349
!ystem.out.println3%6@@)@ &'TH !RL%49
N
N
N

else if 3type.e(uals3%action%44M
tryM
!tatement stmt I connect.create!tatement349
!tring (uery I %',!6@T ',T) "ctionMovies 3% D
%Title, .ear, Type, Length% D
%4 K"LA6! 3#% D
title D %#, #% D
year D %#, #%D
format D %#, #%D
length D %#4%9
int result I stmt.executeApdate3(uery49
stmt.close349

N
catch3!RL6xception ex4M
while 3ex 0I null4M
!ystem.out.println3%Zn6rrorZn%49
!ystem.out.println3%Message % D ex.getMessage3449
!ystem.out.println3%!RL!tate % D ex.get!RL!tate3449
!ystem.out.println3%6rror /ode % D ex.get6rror/ode3449
ex I ex.get,ext6xception349
!ystem.out.println3%6@@)@ &'TH !RL%49

N
N
N


else if 3type.e(uals3%drama%44M
tryM
!tatement stmt I connect.create!tatement349

!tring (uery I %',!6@T ',T) 2ramaMovies 3% D
%Title, .ear, Type, Length% D
%4 K"LA6! 3#% D
title D %#, #% D
year D %#, #%D
format D %#, #%D
length D %#4%9
int result I stmt.executeApdate3(uery49
stmt.close349
113
Web Tech Notes FX Engineering
College, Tirunelveli
N
catch3!RL6xception ex4M
while 3ex 0I null4M
!ystem.out.println3%Zn6rrorZn%49
!ystem.out.println3%Message % D ex.getMessage3449
!ystem.out.println3%!RL!tate % D ex.get!RL!tate3449
!ystem.out.println3%6rror /ode % D ex.get6rror/ode3449
ex I ex.get,ext6xception349
!ystem.out.println3%6@@)@ &'TH !RL%49
N
N
N

else M!ystem.out.println3%something really went wrong%49N
--6nd of /hecking
--!ending friendly message continued..
out.println3%*H:+Movie 2atabase Apdated*-H:+Zn% D
%*H:+"n email has been sent to you for your records*-H:+Zn%D
%*H:+Thanks0*-H:+Zn% D
%*-C)2.+*-HTML+%49
--6nd of friendly message

--!ending 6mail describing how the database got updated

--send6mail349 A,/)MM6,T TH'! F'6L2 F)@ 6M"'L FA,/T'),"L'T.

N

--6nd of doJet Method



--The following method was inspired by )#reilly#s $ava ,etworking
--Hrogramming ;nd 6dition 3/hapter :Q, pg. 7=G4
--Ase of a working !TMH email server is re(uired for this method
--to work properly

-Epublic void send6mail34M
!tring message I %The following movie was added to the databaseZn% D
%Type % D type D %Zn% D
%Title % D title D %Zn% D
%.ear % D year D %Zn% D
%Length % D length D %Zn% D
%Format % D format D %Zn%9

try M
Hroperties prop I new Hroperties349
prop.put3%mail.host%, %yourYstmpYgoesYhere%49 --!MTH goes here

!ession mail/onnection I !ession.get'nstance3prop, null49
Message msg I new MimeMessage3mail/onnection49

"ddress myaddress I new 'nternet"ddress3%-3=:EA>EJ-our>ail)co'%, %.our,ame%49
11"
Web Tech Notes FX Engineering
College, Tirunelveli
"ddress sendingTo I new 'nternet"ddress3%/EEE:/EA>EJ-our>ail)co'%,
%)therHersons,ame%49

msg.set/ontent3message, %text-plain%49
msg.setFrom3myaddress49
msg.set@ecipient3Message.@ecipientType.T), sendingTo49
msg.set!ubBect3%Movie 2atabase Apdate%49

Transport.send3msg49
N
catch 36xception e4 M
e.print!tackTrace349
N


NE-
N
--6nd of class Movie)nline
HTML F)@M
*html+
*head+*title+2atabase Test*-title+*-head+
*body+
/hoose a Movie /ategory*br+
*form action I %http?@@localhost?K,K,@>y/ervlets@servlet@>ovie3nline(9+
*dl+
*dd+*input type I %radio% name I %category% value I %comedy%+
/omedy
*dd+*input type I %radio% name I %category% value I %action%+
"ction
*dd+*input type I %radio% name I %category% value I %drama%+
2rama
*-dl+
Title *input type I %text% name I %title%+*br+
.ear *input type I %text% name I %year%+*br+
Format *input type I %text% name I %format%+*br+
Length *input type I %text% name I %length%+*br+
*br+
*input type I %submit%+*br+*br+
EEFormat means what type of movie 2K2 or KH!
EELength in minutes
*-form+
Anit =
$sp with msaccess
11%
Web Tech Notes FX Engineering
College, Tirunelveli
11&

S-ar putea să vă placă și