0% found this document useful (0 votes)
191 views

HTML (Web Technology)

html

Uploaded by

D-suman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
191 views

HTML (Web Technology)

html

Uploaded by

D-suman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

3DJH 1

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Web Technology
HTML (Hyper Text Markup Language)

,QWURGXFWLRQ WR +70/ DQG 5HODWHG 7RROV


What is HTML?
The language used to develop web pages is called Hyper Text Markup Language (HTML). HTML is the
language interpreted by a Browser. Web Pages are also called HTML documents. HTML is set of special codes
that can be embedded in text to add formatting and linking information. HTML is specified as TAGS in an HTML
document (i.e. the Web page).

i
d

HTML is very easy to use. Web documents are typically written in HTML using any text editor such as
Windows Notepad and are usually named with the suffix (extention) .html or .htm. Thus, HTML documents are
standard ASCII files with formatting codes that contain information about layout (text styles, document titles,
paragraphs, lists) and links. After entering the HTML code in a file you can view it using any browser. Note that
the same web page might be interpreted differently by different browsers.

7RROV

r
a

Browsers
o Internet Explorer
o Netscape Navigator
Editors
o
o
o
o

Text Editors
NotePad(Windows), vi(Linux/Unix), Macintosh.
Word Processors
Microsoft Word, Word Perfect, Word Pro, AmiPro.
HTML Editors
HotDog Pro, Web Weaver.
Visual Editors

Microsoft FrontPage, Netscape Composer, Adobe PageMill, Dream Weaver(Macromedia).

6WUXFWXUH RI DQ +70/ 'RFXPHQW

Elements and Tags


Attributes

Special Characters
Comments

A Complete HTML 4.0 Document


Validating your HTML

Elements and Tags

Elements are the structures that describe parts of an HTML document. For example, the P element
represents a paragraph while the EM element gives emphasized content.
An element has three parts: a start tag, content, and an end tag. A tag is special text
--"markup"-that is delimited by "<" and ">". An end tag includes a "/" after the "<". For example, the EM element has a start
tag, <EM>, and an end tag, </EM>. The start and end tags surround the content of the EM element:
<EM>This is emphasized text</EM>

Element names are always case-insensitive, so <em>, <eM>, and <EM> are all the same.
Elements cannot overlap each other. If the start tag for an EM element appears within a P, the EM's end
tag must also appear within the same P element.
Some elements allow the start or end tag to be omitted. For example, the LI end tag is always optional
since the element's end is implied by the next LI element or by the end of the list:
<UL>
<LI> First list item; no end tag
<LI> Second list item; optional end tag included</LI>
<LI> Third list item; no end tag
</UL>

Some elements have no end tag because they have no content. These elements, such as the BR element for
line breaks, are represented only by a start tag and are said to be empty.

HTML tags can be of two types:

3DJH 2

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Paired Tags :
A tag is said to be a paired tag if it, along with a companion tag, flanks the text. For example the <B> tag is paired
tag. The <B> tag with its companion tag </B> causes the text contained between them to be rendered in bold. The effect of
other paired tags is applied only to the text they contain. In paired tags, the first tag (<B>) is often called the opening tag and
the second tag (</B>) is called the closing tag. The opening tag activities the effect and the closing tag turn the effect off.
Singular Tags :

i
d

The second type of tag is the singular or stand-alone tag. A stand-alone tag does not have a companion tag. For
example <BR> tag will insert a line break. This tag does not require any companion tag.

Attributes

An element's attributes define various properties for the element. For example, the IMG element takes a
SRC attribute to provide the location of the image and an ALT attribute to give alternate text for those not loading
images:
<IMG SRC="logo.gif" ALT="Web Design Logo">

An attribute is included in the start tag only--never the end tag--and takes the form Attributename="Attribute-value". The attribute value is delimited by single or double quotes. The quotes are optional if
the attribute value consists only of letters in the range A-Z and a-z, digits (0-9), hyphens ("-"), and periods (".").

r
a

Attribute names are case-insensitive, but attribute values may be case-sensitive.


Special Characters

Certain characters in HTML are reserved for use as markup and must be escaped to appear literally. The
"<" character may be represented with an entity, &lt;. Similarly, ">" is escaped as &gt;, and "&" is escaped as
&amp;. If an attribute value contains a double quotation mark and is delimited by double quotation marks, then
the quote should be escaped as &quot;.
Other entities exist for special characters that cannot easily be entered with some keyboards. For example,
the copyright symbol ("") may be represented with the entity &copy;.
As an alternative to entities, authors may also use numeric character references. Any character may be
represented by a numeric character reference based on its "code position" in Unicode. For example, one could use
&#169; for the copyright symbol or &#1575; for the Arabic letter ALEF.

Comments

Comments in HTML have a complicated syntax that can be simplified by following this rule: Begin a
comment with "<!--", end it with "-->", and do not use "--" within the comment.

<!-- An example comment -->

A Complete HTML Document

Layout :

An HTML document begins with a DOCTYPE declaration that declares the version of HTML to which
the document conforms. The HTML element follows and contains the HEAD and BODY. The HEAD contains
information about the document, such as its title and keywords, while the BODY contains the actual content of the
document, made up of block-level elements and inline elements. A basic HTML document takes on the following
form:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<HTML>
<HEAD><TITLE>The document title</TITLE>
</HEAD>
<BODY><H1>Main heading</H1>
<P>A paragraph.</P><P>Another paragraph.</P>
<UL><LI>A list item.</LI>
<LI>Another list item.</LI> </UL>
</BODY></HTML>

3DJH 3

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

In a Frameset document, the FRAMESET element replaces the BODY element.


Validating your HTML

Each HTML document should be validated to check for errors such as missing quotation marks (<A
HREF="oops.html>Oops</A>), misspelled element or attribute names, and invalid structures. Such errors are
not always visible when viewing a document in a browser since browsers are designed to recover from an author's
errors. However, different browsers recover in different ways, sometimes resulting in invisible text on one browser
but not on others.

i
d

6WUXFWXUHG 7DJV

<!DOCTYPE> tag

Each HTML document must begin with a document type declaration that declares which version of HTML
the document adheres to. HTML 4.0 comes in three flavors, each with a different DOCTYPE:
HTML 4.0 Strict

HTML 4.0 Strict is a trimmed down version of HTML 4.0 that emphasizes structure over presentation.
Deprecated elements and attributes (including most presentational attributes), frames, and link targets are not
allowed in HTML 4.0 Strict. By writing to HTML 4.0 Strict authors can achieve accessible, structurally rich
documents that easily adapt to style sheets and different browsing situations. However, since many browsers lack
full support for style sheets, HTML 4.0 Strict documents may look bland on common visual browsers such as
Netscape Navigator 3.x.

r
a

The document type declaration for HTML 4.0 Strict is

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"

"http://www.w3.org/TR/REC-html40/strict.dtd">

HTML 4.0 Transitional

HTML 4.0 Transitional includes all elements and attributes of HTML 4.0 Strict but adds presentational
attributes, deprecated elements, and link targets. HTML 4.0 Transitional recognizes the relatively poor browser
support for style sheets, allowing many HTML presentation features to be used as a transition towards HTML 4.0
Strict.
The document type declaration for HTML 4.0 Transitional is

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"


"http://www.w3.org/TR/REC-html40/loose.dtd">

HTML 4.0 Frameset

HTML 4.0 Frameset is a variant of HTML 4.0 Transitional for documents that use frames. The
FRAMESET element replaces the BODY in a Frameset document.
The document type declaration for HTML 4.0 Frameset is

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN"


"http://www.w3.org/TR/REC-html40/frameset.dtd">

<HTML> tag
Syntax :

<HTML>...</HTML>

The HTML element contains the HTML document, made up of the HEAD followed by the BODY, except
in Frameset documents where the FRAMESET element replaces the BODY. The start and end tags of the HTML
element are both optional.

<HEAD> tag
Syntax :

<HEAD>...</HEAD>

The HEAD element contains header information about the document, such as its title, keywords,
description, and style sheet. HEAD is required in all documents, but its start and end tags are always optional. The
HEAD element is followed by the BODY in HTML 4.0 Strict and Transitional documents; in HTML 4.0 Frameset
documents, the HEAD is followed by a FRAMESET element.
Content in the HEAD is generally not rendered, with the exception of the required TITLE element. If the
</HEAD> end tag is omitted, the first BODY or FRAMESET element infers the end of the HEAD.

<TITLE> tag
Syntax :

<TITLE>...</TITLE>

3DJH 4

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

The TITLE element gives the document's title. Each document must have exactly one TITLE within the
HEAD. TITLE contains plain text and entities; it may not contain other markup. A good TITLE should be short
and specific to the document's content so that it can be used as a title for a user's bookmark, a title for the display
window on visual browsers, and a link from a search engine. A suggested limit for the number of characters in a
TITLE is 60.

Example:

<TITLE> Web Page Title </TITLE>

<BODY> tag
Syntax :

i
d

<BODY>...</BODY>

BODY takes a number of attributes for specifying the background and colors of the document on visual
browsers.
Attributes
BACKGROUND

BGCOLOR

TEXT

BGPROPERTIES

STYLESRC
TOPMARGIN

:
:

LEFTMARGIN

LINK

ALINK

VLINK

ONLOAD

ONUNLOAD

Example:

Specifies the name of the GIF(Graphic Interchange Format),


JPEG/JPG(Joint Photograph Expert Group), BMP(Bit Map) or
PNG(Portable Network Graphics) file that will be used as the
background of the document.
Changes the default background color to whatever color is
specified with this tag. The user can specify a color by name
or its equivalent hexadecimal number.
Changes the body text color from its default value to the color
specified with this attribute.
A picture does not scroll with text, but remains fixed in the
background.
Get background information from another page.
Specify a top margin for the page. Type the size of the margin
in pixels.
Specify a left margin for the page. Type the size of the margin
in pixels.
Changes the default color of a Hyperlink to whatever color is
specified with this attributes.
Changes the default color of a Activated Hyperlink to
whatever color is specified with this attributes.
Changes the default color of a Visited Hyperlink to whatever
color is specified with this attributes.
Script attribute values are client-side scripts, typically a
function call or a few short statements. The value may contain
quote.( document has been loaded)
Script attribute values are client-side scripts, typically a
function call or a few short statements. The value may contain
quote.( document has been exited)

r
a

(1) <BODY BACKGROUND=D:\DEC4\LOGO.GIF TEXT=RED BGPROPERTIES=FIXED>


(2) <BODY BGCOLOR=BLUE TEXT=RED TOPMARGIN=0 LEFTMARGIN=1>

(3) <BODY STYLESRC= D:\DEC4\INDEX.HTML TEXT=RED TOPMARGIN=0 LEFTMARGIN=1>

&RPPRQ 7DJV $QG $WWULEXWHV

TEXT FORMATTING

Paragraph breaks

A blank line always separates paragraphs in textual material. The tag that provides this functionality is <P>.
On encountering this tag the browser, moves onto a new line, skipping one line between the previous line and the
new line.
Syntax :

<P> </P>

Attributes
ALIGN

Example:

Specify the horizontal alignment for the content of the


paragraph on visual browsers. Possible values are left, right,
center, and justify.

3DJH 5

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

<p align=justify>A channel is a dedicated path for data to flow along. It doesnt bother too much
about error correction on its own, <p>merely reporting to the processor that the transfer failed.
Line Breaks
When text needs to start from a new line and not continue on the same line (without skipping a blank line),
the <BR> tag should be used. This tag simply jumps to the start of the next line.
Syntax :

<BR>

i
d

Example :
A.V.P.T.I.(Comp. Dept.), <BR> Opp. Hemugadhavi Hall, <BR>
Rajkot.
Heading Style

HTML supports six(6) different levels of headings. The highest-level header format is <H1> and the lowest
level is <H6>. All the style appear in BOLDFACE and the size of the heading depends on the level chosen, i.e.
<H1> to <H6>.
Syntax :

<Hn> </Hn> where n = 1,2,3,4,5,6

Attributes
:

ALIGN

r
a

Specify the horizontal alignment for the heading on visual


browsers. Possible values are left, right, center, and justify.

Example :
<H3> The early years </H3>
Drawing Lines ( Horizontal Rule)

The tag <HR> draws lines and horizontal rules. This tag draws a horizontal line across the whole page,
wherever specified.
Syntax :

<HR>

Attributes
ALIGN

SIZE
WIDTH

:
:

G
:

COLOR

Example :

Specify the horizontal alignment for the line on visual


browsers. Possible values are left, right, and center.
Changes the size of the rule. Range 0 to 100
Sets the width of the rule. It can be set toa fixed number of
pixels, or to a percentage of the avialable screen width.
Sets the specify color.

<HR Align=Left Width=10 Size=4 Color=Red>


Preformatted Text

The PRE element contains preformatted text. Visual browsers should render preformatted text in a
fixed-pitch font, should not collapse whitespace, and should not wrap long lines.
Syntax :
Example :

<PRE> </PRE>

<PRE>
Hello! How are you

This is my first Page.

I am a fine.

</PRE>
TEXT STYLES

Displays text in BOLDFACE style.

Bold
Syntax :

<B> </B> or <STRONG> </STRONG>

Example :
Italics

<B>Welcome to our home page!</B>

Displays text in ITALICS style.

Syntax :
Example :

<I> </I>

or <EM> </EM>

<I>Welcome to our home page!</I>

Underline

3DJH 6

Displays text as UNDERLINED.

Syntax :

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

<U> </U>

Example :

<U> Welcome to our home page </U>

OTHER TEXT EFFECTS

Centering (Text, Images etc.)


Tags are used to center everything found between them text, lists, images, rules, tables or any other page
elements.
Syntax :

i
d

<CENTER> </CENTER>

Example :

<CENTER> Welcome to our home page! </CENTER>

Spacing (Indenting Text)

The tag used for inserting blank spaces in an HTML documents is <SPACER>.
Syntax :

<SPACER>

Attributes
TYPE

SIZE

To specify whether space has to be left horizontally or vertically.


TYPE =HORIZONTAL indicates that horizontal space has to be left.
TYPE =VERTICAL indicates that vertical space has to be left.
Indicates the amount of space to be left. Size accepts any integer.

r
a

Example :

Welcome to my site <BR>


<SPACER TYPE= HORIZONTAL SIZE=30> Hop you enjoy it.

Note: The SPACER command is understood only by the browser Netscape.

<FONT> tag
All text specified within the tags <FONT> and </FONT> will appear in the font, size and color as
specified as attributes of the tag <FONT>.
Syntax :

<FONT> </FONT>

Attributes
FACE
SIZE

:
:

COLOR

Sets the font to the specified font name.


Set the size of the text.
SIZE can be take values between 1 and 7. The default size used is 3.
SIZE can also be set relative to the default size. i.e. SIZE = +X, where x
is any integer value and will add up to default size. i.e. SIZE =+3.
Sets the color of the text. COLOR can be set to an English langauge
color name or to a hexadecimal triplet. i.e. red or #FF0000

Example :

<FONT FACE= Comic Sans MS SIZE=6 COLOR=RED>


Welcome to our home page.
</FONT>

/,676
TYPES OF LISTS

Unordered List (Bullets)

An unordered list starts with the tag <UL> and ends with </UL>. Each list item starts with tag <LI>.
Syntax :

<UL> <LI>.<LI> </UL>

Attributes
TYPE

Specifies the type of the bullet.


TYPE=disc or fillround will give a solid round black bullet.
TYPE=square will give a solid square black bullet.
TYPE=circle will give a empty round empty bullet.

3DJH 7

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Example :
Some of these products include:
<UL TYPE= square>
<LI> Floppies
<LI> Hard Disk
<LI> Monitors
</UL>

i
d

Ordered List (Numbering)

An ordered list starts with the tag <OL> and ends with </OL>. Each list items start with the tag <LI>.
Syntax :

<OL> <LI>.<LI> </OL>

Attributes
TYPE

START

:
:

VALUE

Controls the numbering scheme to be used.


TYPE= 1 will give counting numbers (1,2,.)
TYPE= A will give Uppercase letters (A,B,.)
TYPE= a will give Lowercase letters (a,b,.)
TYPE= I will give Uppercase Roman Numbers (I,II,.)
TYPE= i will give Lowercase Roman numbers (i,ii,.)
Alters the numbering sequence. Can be set to any numeric value.
Changes the numbering sequence in the middle of an ordered list. It is
to be specified with the <LI> tag.

r
a

Example :

Some of these products include:


<OL TYPE= 1 START= 3>
<LI> Floppies
<LI> Hard Disk
<LI> Monitors
</OL>
Definition Lists

Definition list values appear within tags <DL> and </DL>. Definition lists consists of two parts.
Syntax :

<DL> <DT><DD><DT><DD></DL>

DEFINITION TERM
DEFINITION DESCRIPTION
Example :
<DL>

:
:

Appears after the tag <DT>


Appears after the tag <DD>

<DT> Keyboard
<DD> An input device
<DT> Printer
<DD> An output device
</DL>

,1/,1( ,0$*(
<IMG> tag

The IMG element specifies an inline image. The required SRC attribute specifies the location of
the image. The image can be any format, though browsers generally only support GIF, BMP and JPEG
images. Support for the PNG image format is growing slowly.
Syntax :

<IMG> or <IMAGE>

3DJH 8
Attributes
SRC
ALIGN

BORDER
WIDTH
HEIGHT
HSPACE
VSPACE
ALT
TITLE
USEMAP
ISMAP

:
:

:
:
:
:
:
:
:
:
:

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Specifies th location of the image file.


Controls alignment of the text following the image
ALIGN=TOP indicates the text after the image to be written at
the top, next to the image.
ALIGN=MIDDLE indicates the text after the image to be written
at the top, next to the image.
ALIGN=BOTTOM indicates the text after the image to be
written at the top, next to the image.
Controls alignment of the image with respect to the VDU screen.
ALIGN=LEFT indicates the image is aligned to the left with
respect to the scree.
ALIGN=RIGHT indicates the image is laigned to the right with
respect to the screen.
Specifies the size of the border to place around the image.
Specifies the width of the images in pixels.
Specifies the height of the image in pixels.
Indicates the amount of space to the left and right of the image.
Indicates the amount of space to the top and bottom of the image.
Indicates the text to be displayed in case the Browser is unable to
display the image specified in the SRC attribute.
Indicates the text to be displayed as a tooltip text.
Indicates the clien-side image map
Indicates the server-side image map

i
d

r
a

Example :

<IMG SRC= LOGO.GIF BORDER=1 WIDTH=225 HEIGHT=230


RIGHT ALT= IMAGE NOT FOUND TITLE= LOGO.GIF

HSPACE=2 VSPACE=5 ALIGN=

/,1.,1* '2&80(176
URL(Universal/Uniform Resource Locator) Anatomy/Structure

A standardized way of representing different documents, media, and network services on the World Wide
Web.
Syntax:

http://me:[email protected]:81/users/galactus/file.html
^
^ ^
^
^ ^--- local URL part
|
| |
|
|------ port number
|
| |
---------------------- hostname of server, or IP address
|
| ----------------------------- password (optional)
|
-------------------------------- username (optional)
--------------------------------------- protocol name

In most cases, the username, password and port number are omitted. It is also possible that the local URL
part ends in a slash, in which case it is called a directory URL. If the local URL starts with a slash, it is called an
absolute local URL; otherwise it is called a relative local URL.
Different Protocols for URLs

Protocol
http://
https://
file:///
ftp://
gopher://
News://
mailto:
telnet:
LINKS

Accesses
HTML Documents on Server
Some secure HTML documents
HTML documents on your hard drive
FTP sites and files
Gopher menus and documents
UseNet newsgroups on a particular news server
E-mail messages
Remote Telnet (login) session

HTML allows linking to other HTML documents as well as image. Clicking on a section of text or an
image in one web page will open an entire web page or an image. The text or an image that provides such linkages
is called Hypertext, a Hyperlink, or a Hotspot.
Links are created in a web page by using the <A></A> tags.
Syntax:

<A> </A>

3DJH 9

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Attributes
HREF

NAME

TITLE

TARGET

ACCESSKEY

TABINDEX

Specifies a hypertext link to another resource, such as an HTML


document or a JPEG image.
Defines a destination for a link. For example, a document
containing defines a link destination named "foo" at the indicated
heading. One could then use HREF="#foo" in an A element
within the same document or HREF="somedoc.html#foo" from
within another document.
It can be used to briefly describe the contents of the link and is
rendered as a "tooltip" by some visual browsers. With mailto
links, some browsers use the TITLE attribute value as a subject
for the e-mail message.
It is used with frames to specify in which frame the link should be
rendered. If no frame with such a name exists, the link is rendered
in a new window unless overridden by the user. Special frame
names begin with an underscore:
_blank renders the link in a new, unnamed window

_self renders the link in the current frame

_parent renders the link in the immediate FRAMESET


parent

_top renders the link in the full, unframed window


Specifies a single Unicode character as a shortcut key for
following the link.
Specifies a number between 0 and 32767 to indicate the tabbing
order of the element

i
d

r
a

Example :
Link In the Same Folder

<A HREF= index.html> Home Page </A>


Link In the Different Folder

<A HREF= d:\dce4\html\index.html> Home Page </A>


Link On the Web

<A HREF= http://avptirajkot.edu\html\index.html> Home Page </A>

Linking to a Specific Location in a Same Document


<A HREF=#intro> Introduction </A>

<A NAME=intro> Html Introduction </A> i.e. create a bookmark or location intro
Linking to a Specific Location in a Different Document
Code for home.html

<A HREF=index.html#intro> Introduction </A>


OR
<A HREF=d:\dce4\html\index.html#intro> Introduction </A>
Code for index.html

<A NAME=intro> Html Introduction </A> i.e. create a bookmark or location intro
Inserting E-mail Links

<A HREF=mailto:[email protected]> [email protected] </A>


Images as Hyperlinks

<A HREF=index.html><IMG SRC=logo.gif> </A>


Image Maps

The MAP element defines a client-side image map for use with an IMG. MAP's required
NAME attribute is used as an anchor for the USEMAP attribute of the IMG. While a MAP
element can define image maps embedded in other files, browsers typically only support client-side
image maps with the MAP in the same file as the image.
Syntax :

<MAP>

<AREA>....</AREA>

</MAP>

3DJH 10

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Attribute <MAP> tag


:

NAME

MAP's required NAME attribute is used as an anchor for the


USEMAP attribute of the IMG.

Attributes <AREA> tag


SHAPE

The shape of region can be one of the rect, circle, poly(polygon).

COORDS

HREF

ALT
TITLE
TARGET

:
:
:

ACCESSKEY

TABINDEX

Each of the above shapes takes different coordinate values.


A rectangle will take four coordinates: x1, y1, x2, y2.
A circle will take three coordinates: center x, center y, radius.
A polygon will take three or more pairs of coordinates denoting
a polygonal region.
Take the name of the .htm, .jpg file that is linked to the particular
area on the image.
Provides alternate text for those not loading images
Indicates the text to be displayed as a tooltip text.
It is used with frames to specify in which frame the link should be
rendered. If no frame with such a name exists, the link is rendered
in a new window unless overridden by the user. Special frame
names begin with an underscore:

_blank renders the link in a new, unnamed window

_self renders the link in the current frame


_parent renders the link in the immediate FRAMESET

parent
_top renders the link in the full, unframed window

Specifies a single Unicode character as a shortcut key for


following the link.
Specifies a number between 0 and 32767 to indicate the tabbing
order of the element

Example:

r
a

i
d

<MAP NAME=mymap>

<AREA HREF="circle.html" ALT="circle.html" SHAPE=circle COORDS="134, 87, 13">

<AREA HREF="rect.html" ALT="rect.html" SHAPE=rect COORDS="188, 118, 235, 145">

<AREA HREF="poly.html" ALT="poly.html" SHAPE=poly COORDS="56, 54, 79, 87, 45, 99">
</MAP>

<IMG SRC="sitemap.gif" ALT="site map" USEMAP="#mymap" WIDTH=300 HEIGHT=200>

TABLES

The TABLE element defines a table for multi-dimensional data arranged in rows and columns. All table
related tags are included between the <TABLE> </TABLE> tags. Each row of a table is described the <TR> </TR>
tags. Each column of table is described between the <TD> </TD> tags.
TABLE Structure

<TABLE>
<CAPTION></CAPTION>
<THEAD>
<TR><TH><TH>..
</THEAD>
<TBODY>
<TR><TD><TD>.
</TBODY>
<TFOOT>
<TR><TD><TD>
</TFOOT>
</TABLE>

3DJH 11

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Attributes <TABLE> Tag


: Set to Horizontal alignment LEFT, CENTER, or RIGHT.
ALIGN
WIDTH

:
:

HEIGHT

BORDER
CELLPADDING

:
:

CELLSPACING
BGCOLOR

:
:

Set to Vertical alignment TOP, MIDDLE, or BOTTOM.


Sets the WIDTH to a specific number of pixels or to a percentage
of the available screen width. If width is not specified, the data
cell is adjusted based on the cell data value.
Sets the HEIGHT to a specific number of pixels or to a
percentage of the available screen height. If height is not
specified, the data cell is adjusted based on the cell data value.
Specifies the width in pixels of the border around a table.
This attribute controls the distance between the data in a cell
and the boundaries of the cell.
Controls the spacing between adjacent cells.
Specify a background color for the table.

BACKGROUND

Specify a background image for the table.

VALIGN

Attribute <THEAD>, <TBODY>, <TFOOT> & <TR> Tag


: Set to Horizontal alignment LEFT, CENTER, or RIGHT.
ALIGN
WIDTH

:
:

HEIGHT

BGCOLOR

VALIGN

r
a

i
d

Set to Vertical alignment TOP, MIDDLE, or BOTTOM.


Sets the WIDTH to a specific number of pixels or to a percentage
of the available screen width. If width is not specified, the data
cell is adjusted based on the cell data value.
Sets the HEIGHT to a specific number of pixels or to a
percentage of the available screen height. If height is not
specified, the data cell is adjusted based on the cell data value.
Specify a background color for the table.

Attribute <TH> & <TD> Tag


: Set to Horizontal alignment LEFT, CENTER, or RIGHT.
ALIGN
WIDTH

:
:

HEIGHT

BGCOLOR

Set to Vertical alignment TOP, MIDDLE, or BOTTOM.


Sets the WIDTH to a specific number of pixels or to a percentage
of the available screen width. If width is not specified, the data
cell is adjusted based on the cell data value.
Sets the HEIGHT to a specific number of pixels or to a
percentage of the available screen height. If height is not
specified, the data cell is adjusted based on the cell data value.
Specify a background color for the table.

BACKGROUND

Specify a background image for the table.

COLSPAN

Specify the number of column to span by the cell.

ROWSPAN

Specify the number of row to span by the cell.

NOWRAP

Suppress word wrap.

VALIGN

Example :
<HTML>
<BODY>
<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0 BGCOLOR=red>
<CAPTION> Mark sheet</CAPTION>
<THEAD><TR>
<TH ROWSPAN=2> Roll No. <TH ROWSPAN=2> Name
<TH COLSPAN=3> Subject
<TH ROWSPAN=2> Total
<TR> <TH> M1 <TH> M2 <TH> M2
</THEAD><TFOOT><TR><TD COLSPAN=6 BGCOLOR=Yellow> *Remarks
</TFOOT><TBODY>
<TR> <TD> 1. <TD> Ajay <TD> 76 <TD> 46 <TD> 65 <TD> 187
<TR>
<TD> 2. <TD> Vijay <TD> 46 <TD> 76 <TD> 64 <TD> 186
</TBODY>
</TABLE>

3DJH 12
FRAMES

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

INTRODUCTION TO FRAMES
Until now each web page when opened takes over the entire browser screen. The browser screen could not
be split into separate (unique) sections, showing different but related information.
The HTML tags that divide a browser screen into two or more HTML recognized unique regions is the
<FRAMESET> </FRAMESET> tags. Each unique region is called a frame.

i
d

The <FRAMESET> tag

The FRAMESET element is a frame container for dividing a window into rectangular subspaces
called frames. In a Frameset document, the outermost FRAMESET element takes the place of BODY and
immediately follows the HEAD.

The FRAMESET element contains one or more FRAMESET or FRAME elements, along with an
optional NOFRAMES element to provide alternate content for browsers that do not support frames or have
frames disabled. A meaningful NOFRAMES element should always be provided and should at the very
least contain links to the main frame or frames.
Attributes
: This attribute is used to divide the screen into multiple rows. It can be set
ROWS
equal to a list of values. Depending on the required size of each row. The
values can be :
A number of pixels.
Expressed as a percentage of the screen resolution.
The symbol *, which indicates the remaining space.
: This attribute is used to divide the screen into multiple columns. It can be
COLS
set equal to a list of values. Depending on the required size of each column.
The values can be :
A number of pixels.
Expressed as a percentage of the screen resolution.
The symbol *, which indicates the remaining space.
Example :
<FRAMESET ROWS=33%,33%,33%>
<FRAMESET COLS=50%,50%>
</FRAMESET>
<FRAMESET COLS=50%,50%>
</FRAMESET>
</FRAMESET>

r
a

- Divide the browser screen into 3 equal horizontal sections.


- Splits the 1st Horizontal Section into 2 equal Vertical Sectins.

- Spilts the 2nd Horizontal section into 2 equal Vertical sections.

The <FRAME> tag


The FRAME element defines a frame--a rectangular subspace within a Frameset document. Each
FRAME must be contained within a FRAMESET that defines the dimensions of the frame.
Attributes
: Indicates the URL of the document to be loaded into the frame.
SRC
MARGINHEIGHT
MARGINWIDTH
NAME
NORESIZE
SCROLLING
FRAMEBORDER

:
:
:

Specifies the amount of white space to be left at the top and bottom of the
frame.
Specifies the amount of white space to be left along the side of the frame.
Gives the frame a unique name so it can be targeted by other documents.
The name given must begin with an Alphanumeric character.
Disables the frames resizing capability.
Controls the appearance of horizontal and vertical scrollbars in a frame.
This take the values YES / NO / AUTO.
Specifies whether or not the frame has a visible border. The default value,
1, tells the browser to draw a border between the frame and all adjoining
frames. The value 0 indicates that no border should be drawn, though
borders from other frames will override this.

3DJH 13
Example :

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

<HTML>
<HEAD>
</HEAD>
<FRAMESET ROWS="25%,50%,25%">
<FRAME SRC="header.htm">
<FRAMESET COLS="25%,75%">
<FRAME SRC="label.htm">
<FRAME SRC="info.htm">
</FRAMESET>
<FRAME SRC="footer.htm">
</FRAMESET>
<NOFRAMES>
Your browser cannot display frames.
</NOFRAMES>
</HTML>

i
d

Creating Inline Frame

The IFRAME element defines an inline frame for the inclusion of external objects including other
HTML documents. IFRAME provides a subset of the functionality of OBJECT; the only advantage to
IFRAME is that an inline frame can act as a target for other links. OBJECT is more widely supported
than IFRAME, and, unlike IFRAME, OBJECT is included in HTML 4.0 Strict.

r
a

Attributes
SRC

Indicates the URL of the document to be loaded into the frame.

MARGINHEIGHT

MARGINWIDTH

:
:

Specifies the amount of white space to be left at the top and bottom of the
frame.
Specifies the amount of white space to be left along the side of the frame.
Gives the frame a unique name so it can be targeted by other documents.
The name given must begin with an Alphanumeric character.
Disables the frames resizing capability.
Controls the appearance of horizontal and vertical scrollbars in a frame.
This take the values YES / NO / AUTO.
Specifies whether or not the frame has a visible border. The default value,
1, tells the browser to draw a border between the frame and all adjoining
frames. The value 0 indicates that no border should be drawn, though
borders from other frames will override this.
Specify the dimensions of the inline frame in pixels or as a percentage of
the available space.
Specify the dimensions of the inline frame in pixels or as a percentage of
the available space.
Specifies the alignment of the inline frame. The values top, middle, and
bottom specify the frame's position with respect to surrounding content
on its left and right.

NAME

SCROLLING

:
:

FRAMEBORDER

NORESIZE

WIDTH
HEIGHT
ALIGN

Example:

G
:

<P ALIGN=center><IFRAME SRC="foo.html" WIDTH=300 HEIGHT=100></IFRAME></P>

Developing Form Content

Forms are one of the most popular, interactive features on the World Wide Web (WWW). They enable
users to interact with the text and graphics that are displayed on your machine. You can make forms with simple
yes or no questions; you can make highly complex order forms; or you can make forms for people to send you
comments.
HTML forms give you the opportunity to gather information from people reading your Web page. Just as
HTML provides many mechanisms for outputting information, the use of HTML forms enables input. These forms
can be used to ask for free-form text information, get answers to yes or no questions, and get answers from a set of
options.

3DJH 14
Creating FORM contents (FORM widgets control)

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Form Structure :

FORM - Interactive form


INPUT - Form input
SELECT - Option selector
OPTION - Menu option
TEXTAREA - Multi-line text input
FIELDSET - Form control group
LEGEND - Fieldset caption
LABEL - Form field label
BUTTON - Button

i
d

Working with HTML Forms Tags

The FORM element defines an interactive form. The element should contain form controls-INPUT, SELECT, TEXTAREA, and BUTTON--through which the user interacts.

When the user submits the form, through an INPUT or BUTTON element with TYPE=submit, the
form values are submitted to the URI given in FORM's required ACTION attribute. ACTION usually
points to a CGI script or Java servlet that handles the form submission.

r
a

Attributes
ACTION

METHOD

NAME

:
:
:
:

ONSUBMIT
ONRESET
TARGET

Example :

This attribute points the form to an URL that will accept the form's
information and do something with it. If you don't specify an ACTION, it
sends the information back to the same URL the page came from.
This attribute tells the form how to send its information back to the script.
The most common method is POST, which sends all the information from
the form separately from the URL. The other option for METHOD is GET,
which attaches the information from the form to the end of the URL.
Specify the name of the form for using Scripting.
Script call when the form is submitted
Script call when the form is reset.
Specify in which frame the form response should be rendered. If no frame
with such a name exists, the response is rendered in a new window unless
overridden by the user. Special frame names begin with an underscore:

<FORM METHOD="POST" ACTION="hello.html" NAME="hello" TARGET="_self">


...
</FORM>

Working with Input Tag


The INPUT element defines a form control for the user to enter input. While INPUT is most useful
within a FORM, HTML 4.0 allows INPUT in any block-level or inline element other than BUTTON.
However, Netscape Navigator will not display any INPUT elements outside of a FORM.
Attributes
: This sets the type of input field you want to display. text | password |
TYPE
checkbox | radio | submit | reset | file | hidden | image | button
: This defines the name for the data.
NAME
: For a text or password field, it defines the default text displayed. For a
VALUE
check box or radio button, it specifies the value that is returned to the
server if the box or button is selected. For the Submit and Reset buttons,
it defines the text inside the button.
: This sets a check box or radio button to on. It has no meaning for any
CHECKED
other type of <INPUT> tag.
: This is the size of the input field in number of characters for text or
SIZE
password.
: This specifies the maximum number of characters to be allowed for a text
MAXLENGTH
or password field.
: Specify the URI of the image.
SRC
: Provides alternate text for those not loading images
ALT

Prepared By Mr. P. P. Kotak & Mr. Sanjay B. Kuvad

3DJH 15
ACCESSKEY

:
:

TABINDEX

ONFOCUS

:
:
:
:

DISABLED

ONBLUR
ONSELECT
ONCHANGE

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Specifies the disable element to want.


Specifies a single Unicode character as a shortcut key for following the
link.
Specifies a number between 0 and 32767 to indicate the tabbing order of
the element
When the element receives focus.
When the element loses focus.
When text in an input of type text or password is selected;
When the element loses focus and its value has changed since it received
focus.

i
d

Working with Select Tag

The SELECT element defines a form control for the selection of options. While SELECT is most
useful within a FORM, HTML 4.0 allows SELECT in any block-level or inline element other than
BUTTON. However, Netscape Navigator will not display any SELECT elements outside of a FORM.
Attributes

r
a

NAME

This is required. It defines the name for the data.

SIZE

MULTIPLE

DISABLED
ACCESSKEY

:
:

TABINDEX

ONFOCUS

:
:
:

This attribute determines how many choices to show. If you omit SIZE or
set it to 1, the choices are shown as a drop-down list. If you set it to 2 or
higher, it shows the choices in a scroll box. If you set SIZE larger than the
number of choices you have within <SELECT>, a nothing choice is added.
When the end user chooses this, it's returned as an empty field.
This allows multiple selections. If you specify multiple, a scrolling
window displays--regardless of the number of choices or the setting of
SIZE.
Specifies the disable element to want.
Specifies a single Unicode character as a shortcut key for following the
link.
Specifies a number between 0 and 32767 to indicate the tabbing order of
the element
When the element receives focus.
When the element loses focus.
When the element loses focus and its value has changed since it received
focus.

ONBLUR
ONCHANGE

Working with Select Option Tag

The OPTION element defines a menu choice within a SELECT menu. The value of the option,
sent with a submitted form, is specified with the VALUE attribute. In the absence of a VALUE attribute,
the value is the content of the OPTION element.
Attributes
VALUE

SELECTED
DISABLED

This is the value to be assigned for the choice, which is what is sent back
to the script, and doesn't have to be the same as what is presented to the
end user.
If you want one of the choices to be a default, use the SELECTED option in
the <OPTION> tag.
Specifies the disable element to want.

Working with TextArea Tag

The TEXTAREA element defines a form control for the user to enter multi-line text input. While
TEXTAREA is most useful within a FORM, HTML 4.0 allows TEXTAREA in any block-level or inline
element other than BUTTON. However, Netscape Navigator will not display any TEXTAREA elements
outside of a FORM.

3DJH 16
Attributes

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

NAME

This is required. It defines the name for the data.

ROWS

ACCESSKEY

:
:
:
:

TABINDEX

ONFOCUS

:
:
:
:

This sets the number of rows in the field.


This sets the width of the field in characters.
Specifies the disable element to want.
Specifies a single Unicode character as a shortcut key for following the
link.
Specifies a number between 0 and 32767 to indicate the tabbing order of
the element
When the element receives focus.
When the element loses focus.
When textarea in an input of type text or password is selected;
When the element loses focus and its value has changed since it received
focus.

COLS
DISABLED

ONBLUR
ONSELECT
ONCHANGE

i
d

Working with Fieldset Tag

r
a

The FIELDSET element defines a form control group. By grouping related form controls, authors
can divide a form into smaller, more manageable parts, improving the usability disaster that can strike
when confronting users with too many form controls. The grouping provided by FIELDSET also helps the
accessibility of forms to those using aural browsers by allowing these users to more easily orient
themselves when filling in a large form.
The LEGEND element defines a caption for form controls grouped by the FIELDSET element.
The LEGEND element must be at the start of a FIELDSET, before any other elements
Attributes
ALIGN

ACCESSKEY

Specifies the alignment of the inline frame. The values top, middle, and
bottom specify the frame's position with respect to surrounding content
on its left and right.
Specifies a single Unicode character as a shortcut key for following the
link.

Working with Label Tag

The LABEL element associates a label with a form control. By associating labels with form
controls, authors give important hints to users of speech browsers while also allowing visual browsers to
duplicate common GUI features (e.g., the ability to click on a text label to select a radio button or
checkbox).
Attributes
FOR

ACCESSKEY
ONFOCUS
ONBLUR

:
:

Specifies the control associated with the LABEL. The value of the FOR
attribute must match the value of the associated form control's ID
attribute. In the absence of the FOR attribute, the LABEL must contain
the associated form control.
Specifies a single Unicode character as a shortcut key for following the
link.
When the element receives focus.
When the element loses focus.

Working with Button Tag

The BUTTON element defines a submit button, reset button, or push button. Authors can also use
INPUT to specify these buttons, but the BUTTON element allows richer labels, including images and
emphasis. However, BUTTON is new in HTML 4.0 and poorly supported among current browsers, so
INPUT is a more reliable choice at this time.

3DJH 17
Attributes

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

TYPE

This sets the type of input field you want to display. submit| reset | button

NAME

:
:

This defines the name for the data.


For a text or password field, it defines the default text displayed. For a
check box or radio button, it specifies the value that is returned to the
server if the box or button is selected. For the Submit and Reset buttons,
it defines the text inside the button.
Specifies the disable element to want.
Specifies a single Unicode character as a shortcut key for following the
link.
Specifies a number between 0 and 32767 to indicate the tabbing order of
the element
When the element receives focus.
When the element loses focus.

VALUE

ACCESSKEY

:
:

TABINDEX

ONFOCUS

:
:

DISABLED

ONBLUR

i
d

Example:

r
a

<HTML>
<HEAD>
<CENTER><H1> WEB APPLICATION </CENTER></H1>
<TITLE> WEB APPLICATION </TITLE>
</HEAD>
<BODY>
<FONT FACE="Verdana">
<FORM NAME=Personal ACTION=Retrive.html METHOD=post>
First Name<INPUT TYPE=Text NAME=FirstName SIZE=20 VALUE="My First Name">
Last Name<INPUT TYPE=Text NAME=LastName SIZE=30 VALUE="My Last Name">
<BR><BR>
<INPUT TYPE=Radio NAME="Sex" SIZE=20 VALUE="Male">Male
&nbsp;&nbsp;&nbsp;&nbsp;<INPUT TYPE=Radio NAME="Sex" SIZE=20 VALUE="Female">Female
<BR><HR><BR>
<TABLE>
<TR> <TD VALIGN=TOP>INCOME:
<TD> <SELECT NAME="IncomeRange">
<OPTION VALUE="invalid">Select your income range
<BR><OPTION VALUE="Low">less than $25k
<BR><OPTION VALUE="Med">between $25k-$50k
<BR><OPTION VALUE="High">more than $50k
<BR></SELECT>
<TD>&nbsp;&nbsp;&nbsp;&nbsp;
<TD VALIGN=Top>EDUCATION:
<TD> <SELECT NAME="Education">
<OPTION VALUE="invalid">Select your highest degree
<OPTION VALUE="HSchool">High School
<OPTION VALUE="College">College
<OPTION VALUE="University">University
</SELECT>
</TABLE><HR>
<TABLE>
<TR><TD VALIGN=TOP>MY INTEREST:
<TD VALIGN=TOP><TABLE>
<TR><TD><INPUT TYPE=CheckBox NAME="Books" Value="R">Reading
<TR><TD><INPUT TYPE=CheckBox NAME="Music" value="ON">Music
<TR><TD><INPUT TYPE=CheckBox NAME="Movies" value="ON">Movies
<TR><TD><INPUT TYPE=CheckBox NAME="Cooking" value="ON">Cooking
</TABLE>
<TD> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<TD VALIGN=TOP>I READ DAILY:
<TD VALIGN=TOP><TABLE>
<TR><TD><INPUT TYPE=CheckBox NAME="Local" value="ON">Local News
<TR><TD><INPUT TYPE=CheckBox NAME="National" value="ON">National News
<TR><TD><INPUT TYPE=CheckBox NAME="International" value="ON">International News
<TR><TD><INPUT TYPE=CheckBox NAME="Financial" value="ON">Financial News
</TABLE> </TABLE>
<HR><INPUT TYPE=SUBMIT NAME=SUBMIT VALUE=SUBMIT>
<INPUT TYPE=RESET NAME=RESET VALUE=RESET></FORM></FONT>
</BODY></HTML>

3DJH 18

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Cascading Style Sheets (CSS)


A style sheet is made up of style rules that tell a browser how to present a document. There are
various ways of linking these style rules to your HTML documents, but the simplest method for starting out
is to use HTML's STYLE element. This element is placed in the document HEAD, and it contains the style
rules for the page.

i
d

Structure
<STYLE TYPE= text/css>
<! .. -->
</STYLE>

Basic Syntax

Selectors
Any HTML element is a possible CSS1 selector. The selector is simply the element that is linked to
a particular style. For example, the selector in

r
a

P { text-indent: 3em }

is P.

Class Selectors

A simple selector can have different classes, thus allowing the same element to have different
styles. For example, an author may wish to display code in a different color depending on its language:
code.html { color: #191970 }
code.css { color: #4b0082 }

The above example has created two classes, css and html for use with HTML's CODE element.
The CLASS attribute is used in HTML to indicate the class of an element, e.g.,
<P CLASS=warning>Only one class is allowed per selector.
For example, code.html.proprietary is invalid.</p>

Classes may also be declared without an associated element:


.note { font-size: small }

In this case, the note class may be used with any element.

A good practice is to name classes according to their function rather than their appearance. The not e class in
the above example could have been named small, but this name would become meaningless if the author decided to
change the style of the class so that it no longer had a small font size.

ID Selectors

ID selectors are individually assigned for the purpose of defining on a per-element basis. This
selector type should only be used sparingly due to its inherent limitations. An ID selector is assigned by
using the indicator "#" to precede a name. For example, an ID selector could be assigned as such:
#svp94O { text-indent: 3em }

This would be referenced in HTML by the ID attribute:


<P ID=svp94O>Text indented 3em</P>

Contextual Selectors

Contextual selectors are merely strings of two or more simple selectors separated by white space.
These selectors can be assigned normal properties and, due to the rules of cascading order, they will take
precedence over simple selectors. For example, the contextual selector in
P EM { background: yellow }

is P EM. This rule says that emphasized text within a paragraph should have a yellow background;
emphasized text in a heading would be unaffected.

Declarations
Properties

A property is assigned to a selector in order to manipulate its style. Examples of properties include
color, margin, and font.

Values

The declaration value is an assignment that a property receives. For example, the property color
could receive the value red.

Grouping

In order to decrease repetitious statements within style sheets, grouping of selectors and
declarations is allowed. For example, all of the headings in a document could be given identical
declarations through a grouping:
H1, H2, H3, H4, H5, H6 {
color: red; font-family: sans-serif }

3DJH 19

Inheritance

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Virtually all selectors which are nested within selectors will inherit the property values assigned to
the outer selector unless otherwise modified. For example, a color defined for the BODY will also be
applied to text in a paragraph.
There are some cases where the inner selector does not inherit the surrounding selector's values, but
these should stand out logically. For example, the margin-top property is not inherited; intuitively, a
paragraph would not have the same top margin as the document body.

Comments

i
d

Comments are denoted within style sheets with the same conventions that are used in C
programming. A sample CSS1 comment would be in the format:
/* COMMENTS CANNOT BE NESTED */

Linking Style Sheet to HTML


1.

Linking to an External Style Sheet

An external style sheet may be linked to an HTML document through HTML's LINK element:
<LINK REL=StyleSheet HREF="style.css" TYPE="text/css" MEDIA=screen>
<LINK REL=StyleSheet HREF="color-8b.css" TYPE="text/css" TITLE="8-bit
Color Style" MEDIA="screen, print">
<LINK REL="Alternate StyleSheet" HREF="color-24b.css" TYPE="text/css"
TITLE="24-bit Color Style" MEDIA="screen, print">
<LINK REL=StyleSheet HREF="aural.css" TYPE="text/css" MEDIA=aural>

r
a

The <LINK> tag is placed in the document HEAD. The optional TYPE attribute is used to specify a
media type--text/css for a Cascading Style Sheet--allowing browsers to ignore style sheet types that they do not
support. Configuring the server to send text/css as the Content-type for CSS files is also a good idea.
External style sheets should not contain any HTML tags like <HEAD> or <STYLE>. The style sheet
should consist merely of style rules or statements. A file consisting solely of
P { margin: 2em }
could be used as an external style sheet.
The REL attribute is used to define the relationship between the linked file and the HTML document.
REL=StyleSheet specifies a persistent or preferred style while REL="Alternate StyleSheet" defines an
alternate style. A persistent style is one that is always applied when style sheets are enabled. The absence of the
TITLE attribute, as in the first <LINK> tag in the example, defines a persistent style.
A preferred style is one that is automatically applied, such as in the second <LINK> tag in the example.
The combination of REL=StyleSheet and a TITLE attribute specifies a preferred style. Authors cannot specify
more than one preferred style.
An alternate style is indicated by REL="Alternate StyleSheet". The third <LINK> tag in the example
defines an alternate style, which the user could choose to replace the preferred style sheet.
Note that current browsers generally lack the ability to choose alternate styles.
A single style may also be given through multiple style sheets:
<LINK REL=StyleSheet HREF="basics.css" TITLE="Contemporary">
<LINK REL=StyleSheet HREF="tables.css" TITLE="Contemporary">
<LINK REL=StyleSheet HREF="forms.css" TITLE="Contemporary">
In this example, three style sheets are combined into one "Contemporary" style that is applied as a preferred
style sheet. To combine multiple style sheets into a single style, one must use the same TITLE with each style
sheet.
An external style sheet is ideal when the style is applied to numerous pages. With an external style sheet, an
author could change the look of an entire site by simply changing one file. As well, most browsers will cache an
external style sheet, thus avoiding a delay in page presentation once the style sheet is cached.
Microsoft Internet Explorer 3 for Windows 95/NT4 does not support BODY background images or colors
from linked style sheets. Given this bug, authors may wish to provide another mechanism for including a
background image or color, such as embedding or inlining the style, or by using the BACKGROUND attribute of
the BODY element.
Embedding a Style Sheet
A style sheet may be embedded in a document with the STYLE element:
<STYLE TYPE="text/css" MEDIA=screen>
<!-BODY { background: url(foo.gif) red; color: black }
P EM { background: yellow; color: black }
.note { margin-left: 5em; margin-right: 5em }
-->
</STYLE>

3DJH 20

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

The STYLE element is placed in the document HEAD. The required TYPE attribute is used to specify a
media type, as is its function with the LINK element. Similarly, the TITLE and MEDIA attributes may also be
specified with STYLE.
Older browsers, unaware of the STYLE element, would normally show its contents as if they were part of
the BODY, thus making the style sheet visible to the user. To prevent this, the contents of the STYLE element are
contained within an SGML comment (<!-- comment -->), as in the preceding example.
An embedded style sheet should be used when a single document has a unique style. If the same style sheet
is used in multiple documents, then an external style sheet would be more appropriate.

i
d

Importing a Style Sheet


A style sheet may be imported with CSS's @import statement. This statement may be used in a CSS file or
inside the STYLE element:
<STYLE TYPE="text/css">
<!-@import url(http://www.htmlhelp.com/style.css);
@import url(/https/www.scribd.com/stylesheets/punk.css);
DT { background: yellow; color: black }
-->
</STYLE>
Note that other CSS rules may still be included in the STYLE element, but that all @import statements
must occur at the start of the style sheet. Any rules specified in the style sheet itself override conflicting rules in the
imported style sheets. For example, even if one of the imported style sheets contained DT { background: aqua },
definition terms would still have a yellow background.
The order in which the style sheets are imported is important in determining how they cascade. In the above
example, if the style.css imported style sheet specified that STRONG elements be shown in red and the punk.css
style sheet specified that STRONG elements be shown in yellow, then the latter rule would win out, and
STRONG elements would be in yellow.
Imported style sheets are useful for purposes of modularity. For example, a site may separate different style
sheets by the selectors used. There may be a simple.css style sheet that gives rules for common elements such as
BODY, P, H1, and H2. In addition, there may be an extra.css style sheet that gives rules for less common elements
such as CODE, BLOCKQUOTE, and DFN. A tables.css style sheet may be used to define rules for table
elements. These three style sheets could be included in HTML documents, as needed, with the @import statement.
The three style sheets could also be combined via the LINK element.

r
a

Inlining Style
Style may be inlined using the STYLE attribute. The STYLE attribute may be applied to any BODY
element (including BODY itself) except for BASEFONT, PARAM, and SCRIPT. The attribute takes as its value
any number of CSS declarations, where each declaration is separated by a semicolon. An example follows:
<P STYLE="color: red; font-family: 'New Century Schoolbook', serif">
This paragraph is styled in red with the New Century Schoolbook font,
if available.</P>
Note that New Century Schoolbook is contained within single quotes in the STYLE attribute since double
quotes are used to contain the style declarations.
Inlining style is far more inflexible than the other methods. To use inline style, one must declare a single
style sheet language for the entire document using the Content-Style-Type HTTP header extension. With inlined
CSS, an author must send text/css as the Content-Style-Type HTTP header or include the following tag in the
HEAD:
<META HTTP-EQUIV="Content-Style-Type" CONTENT="text/css">
Inlining style loses many of the advantages of style sheets by mixing content with presentation. As well,
inlined styles implicitly apply to all media, since there is no mechanism for specifying the intended medium for an
inlined style. This method should be used sparingly, such as when a style is to be applied on all media to a single
occurrence of an element. If the style should be applied to a single element instance but only with certain media,
use the ID attribute instead of the STYLE attribute.

The CLASS Attribute


The CLASS attribute is used to specify the style class to which the element belongs. For example, the style
sheet may have created the punk and warning classes:
.punk
{ color: lime; background: #ff80c0 }
P.warning { font-weight: bolder; color: red; background: white }
These classes could be referenced in HTML with the CLASS attribute:
<H1
CLASS=punk>Proprietary
Extensions</H1>
<P CLASS=warning>Many proprietary extensions can have negative sideeffects, both on supporting and non-supporting browsers...

3DJH 21

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

In this example, the punk class may be applied to any BODY element since it does not have an HTML
element associated with it in the style sheet. Using the example's style sheet, the warning class may only be
applied to the P element.
A good practice is to name classes according to their function rather than their appearance. The warning
class in the previous example could have been named red, but this name would become meaningless if the author
decided to change the style of the class to a different color, or if the author wished to define an aural style for those
using speech synthesizers.
Classes can be a very effective method of applying different styles to structurally identical sections of an
HTML document. For example, this page uses classes to give a different style to CSS code and HTML code.

i
d

The ID Attribute
The ID attribute is used to define a unique style for an element. A CSS rule such as
#wdg97 { font-size: larger }
may be applied in HTML through the ID attribute:
<P ID=wdg97>Welcome to the Web Design Group!</P>
Each ID attribute must have a unique value over the document. The value must be an initial letter followed
by letters, digits, or hyphens. The letters are restricted to A-Z and a-z.
Note that HTML 4.0 allows periods in ID attribute values, but CSS1 does not allow periods in ID selectors.
Also note that CSS1 allows the Unicode characters 161-255 as well as escaped Unicode characters as a numeric
code, but HTML 4.0 does not allow these characters in an ID attribute value.
The use of ID is appropriate when a style only needs to be applied once in any document. ID contrasts with
the STYLE attribute in that the former allows medium-specific styles and can also be applied to multiple
documents (though only once in each document).

r
a

The SPAN Element


The SPAN element was introduced into HTML to allow authors to give style that could not be attached to a
structural HTML element. SPAN may be used as a selector in a style sheet, and it also accepts the STYLE,
CLASS, and ID attributes.
SPAN is an inline element, so it may be used just as elements such as EM and STRONG in HTML. The
important distinction is that while EM and STRONG carry structural meaning, SPAN has no such meaning. It
exists purely to apply style, and so has no effect when the style sheet is disabled.
Some examples of SPAN follow:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Draft//EN">
<HTML>
<HEAD>
<TITLE>Example of SPAN</TITLE>
<META HTTP-EQUIV="Content-Style-Type" CONTENT="text/css">
<STYLE TYPE="text/css" MEDIA="screen, print, projection">
<!-.firstwords { font-variant: small-caps }
-->
</STYLE>
</HEAD>
<BODY>
<P><SPAN CLASS=firstwords>The first few words</SPAN> of a
paragraph could be in small-caps. Style may also be inlined, such as
to change the style of a word like <SPAN STYLE="font-family: Arial">
Arial</SPAN>.</P>
The DIV Element

The DIV element is similar to the SPAN element in function, with the main difference being that DIV
(short for "division") is a block-level element. DIV may contain paragraphs, headings, tables, and even other
divisions. This makes DIV ideal for marking different classes of containers, such as a chapter, abstract, or note.
For example:
<DIV CLASS=note>
<H1>Divisions</H1>
<P>The DIV element is defined in HTML 3.2, but only the ALIGN attribute
is permitted in HTML 3.2. HTML 4.0 adds the CLASS, STYLE, and ID
attributes, among others.</P>
<P>Since DIV may contain other block-level containers, it is useful for
marking large sections of a document, such as this note.</P>
<P>The closing tag is required.</P>
</DIV>

3DJH 22

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

CSS Properties
Background Properties
HTML style sheets provide you the capability to decorate the background of an element by using color and
images. Note that using the properties described in the following sections doesn't define the background for the
Web page as a whole. These properties set the background of an element on the Web page. For example, if you
define a background for the <UL> tag, as in the following example, then the background only appears within each
occurrence of that tag on the Web page.

i
d

UL {background-image: URL(http://www.myserver.com/images/watermark.gif)}
You can group the background properties described in the following sections using background. You

specify the background color, image, repeat, attachment, and position like this:

background: white URL(http://www.myserver.com/images/bg.gif) repeat-x fixed top, left

background-attachment

The background-attachment property determines whether the background image is fixed in the browser
window or scrolls as the user scrolls the window. You can use this property to create a watermark behind your
Web page that stays put regardless of which portion of the Web page the user is viewing.
Value
Description
fixed
The image is fixed within the browser window.
scroll
The image scrolls as the user scrolls the window.

r
a

background-color

You can change the background color for an element by using the background-color property. You can
assign one of the valid color names to background-color or an RGB value such as #808080 (white). For
example, if you define a style for the <UL> tag that changes the background color to blue, then all the unordered
lists in your HTML file will be displayed with a blue background.

background-image

You can display a background image in an element by setting the value of the background-image property
to the URL of an image. This has the effect of a watermark displayed behind that element on the Web page (the
element's content is displayed over the background image).
You set the URL by using the URL(address) format, like this:
H1 {background-image: URL(http://www.myserver.com/images/heading.gif)}

Units in CSS1
Most style sheet properties accept some sort of length. You can use many different units to specify a length, too.
HTML supports two types of units: relative and absolute lengths. The following table describes the relative units.
Unit
Example
Description
em
0.5em
The height of the element's font, relative to the output device
ex
0.75ex
The height of the letter X, relative to the output device
px
15px
Pixels, relative to the output device
Whenever possible, use relative units so that your Web pages will scale better from one device to the next.
You can also use the absolute units as described in the following table.
Unit
Example
Description
in
.5in
Inches
cm
1cm
Centimeters
mm
20mm
Millimeters
pt
12pt
Points (1pt = 1/72 inch)
pc
1pc
Pica (1pc = 12pt)

Aside from relative and absolute lengths, you can also specify most lengths in terms of percentages. With
HTML style sheets, percentages are almost always relative to the parent element. For example, if you're specifying
a font size of 50 percent, what you're really saying is that you want the element's font size to be half as big as the
parent element's font size.

background-position

You change the position of the background image by using the background-position property. The
position is always relative to the top-left corner of the element in which you're positioning the image. That is, if
you're positioning an image for the <UL> tag, the image's position will be relative to the top-left corner of the
unordered list.
The background-position property looks like
background-position: x y

3DJH 23

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

where x is the horizontal position, and y is the vertical position of the image. x and y can be a percentage,
which is relative to the size of the element; a fixed amount such as 1in (one inch); or one of the keywords that
indicate a relative position as described in Table.
For example:
background-position: center 20

Keyword Description
top
Aligns the image with the top of the containing element; only useful when substituted for y.
left
Aligns the image with the left side of the containing element; only useful when substituted for x.
right
Aligns the image with the right side of the containing element; only useful when substituted for y.
bottom Aligns the image with the bottom of the containing element; only useful when substituted for y.
center Centers the image within the containing element; when substituted for x, the image is centered
horizontally; when substituted for y, the image is centered vertically.

i
d

background-repeat

You can cause the user's browser to tile the background image so that it fills the entire area of the
containing element. The background-repeat property can have four values, as described in Table B.3.
Value
Description
repeat
Repeats the image both vertically and horizontally
repeat-x
Repeats the image horizontally
repeat-y
Repeats the image vertically
no-repeat
Doesn't repeat the image

r
a

color

The color property determines the foreground color for the element. Thus, the browser displays the
element's text using this color. You can set color to a named color or an RGB value. Named colors include those
in the following list:
black
maroon
green
navy

silver
red
lime
blue

gray
purple
olive
teal

Box Properties

white
fuchsia
yellow
aqua

W3C's style sheet recommendation provides you the capability to define the borders, margins, and padding
for elements on the Web page. You can wrap a border around a heading, for example, or change the margins of the
<P> tag so that any occurrences of this tag are indented into the page. Here's an overview of the properties that you
can use to change the boxes associated with an element:
Border
You use the border properties to set the left, right, top, and bottom borders of an element.
You can set the border's width, color, and style.
Margin
You use the margin properties to set the left, right, top, and bottom margins of an element.
With these properties, you only specify the size of the margin.
Padding
You use the padding properties to specify how much space the browser displays between
the border and the content of the element. With the padding properties, you only specify the size
of the margin.
Figure B.1 shows you how the border, margin, and padding properties work with the height and width
properties to form the boxes around the element. The following list describe these in more detail:

The height and width properties determine the overall size of the element's containing box.

The margin properties determine the element's margins within its containing box.

The border properties determine the position of the border within the element's margins.

The padding properties determine the amount of space between the element's border and the
contents of the element itself.
You can group border properties in five different ways. You can specify the properties for a particular side
of the element, using border-top, border-right, border-bottom, or border-left. You can also specify all
sides of the border at one time by using border.
With any of these attributes, you specify the width, style, and color of the border, as in the following
example:

border-top: thin dotted black

Four boxes are actually around each element.


You can group the margin properties using margin. You specify the top, right, bottom, and left, like this:
margin: .5in 1in .5in 1in

You can also group the margin properties using padding. You specify the top, right, bottom, and left
padding values, like this:

3DJH 24

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

padding: .25in .25in .25in .25in

If you specify only one value, the browser uses that value for all sides. If you leave out one or more values,
the browser takes the missing value from the opposite side. For example, if you leave off the last value (left), the
browser sets the left padding to the value you specified for the right margin.

border-bottom-width
You set the width of the bottom border by using the border-bottom-width property. This doesn't affect
the other sides of the border. You can assign any of the values described in Table B.4 to this property.
Value Description
thin
Displays the border by using a thin line.
medium Displays the border by using a medium line.
thick Displays the border by using a thick line.
length You can define the exact width of the border by using points (pt), inches (in), centimeters (cm), or pixels
(px); (for example, 2in).

i
d

border-color

The border-color property sets the color of the element's border. You can use a named color, such as RED,
or you can use an RGB value, such as #FF0000.

border-left-width

You set the width of the left border by using the border-left-width property. This doesn't affect the
other sides of the border. You can assign any of the values described in Table B.6 to this property.

r
a

border-right-width

You set the width of the right border by using the border-right-width property. This doesn't affect the
other sides of the border. You can assign any of the values described in Table B.6 to this property.

border-style

The border-style property determines the style of the border that the browser displays. You can specify
from one to four values for this property:
One
Value
Two
Values
Three
Values
Four
Values

All four borders are set to the style.

The top and bottom borders are set to the style in the first value, and the left and right borders are set to
the style in the second value.
The top border is set to the style in the first value; the right and left borders are set to the style in the
second value; and the bottom border is set to the style in the third value.
The top border is set to the style in the first value; the right border is set to the second value; the bottom
border is set to the third value; and the left border is set to the fourth value.
Table describes the values you can use for a border's style.
Value
Description
none
No border.
dotted
Dotted line drawn over the top of the element.
dashed
Dashed line drawn over the top of the element.
solid
Solid line.
double
Double line drawn over the top of the element; the width of the two lines and the space between them
equals the border-width value.
groove
3-D groove drawn in colors based upon color.
ridge
3-D ridge drawn in colors based upon color.
inset
3-D inset drawn in colors based upon color.
outset
3-D outset drawn in colors based upon color.

border-top-width

You set the width of the top border by using the border-top-width property. This doesn't affect the other
sides of the border. You can assign any of the values described in Table B.7 to this property.

float

The float property specifies that the element is floated to the left or right side, with the surrounding
elements flowing around it. Table B.7 describes the values you can assign to this property.

Table float Values


Value
none
left
right

Description
Displays the element where it is
Move to the left and wrap text around it
Move to the right and wrap text around it

3DJH 25

height

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

You set the total height of the element with the height property. You can set this property for text blocks
or images. For example, you can use the height and width properties to create a special warning on the Web page
that has a fixed size. Height is more useful with images, however. You can set this property to any length, a
percentage value, or auto, which lets the browser determine the best size for the element.

margin-bottom
You set the bottom margin by using the margin-bottom property. You can specify any valid length, a
percentage value (relative to the height and width) of the element, or auto, which lets the browser determine the
best margins to use for the element. You can also use a negative margin size to create special effects such as
hanging indents.

i
d

margin-left

You set the left margin by using the margin-left property. You can specify any valid length, a percentage
value (relative to the height and width) of the element, or auto, which lets the browser determine the best
margins to use for the element. You can also use a negative margin size to create special effects.

margin-right

You set the right margin by using the margin-right property. You can specify any valid length, a
percentage value (relative to the height and width) of the element, or auto, which lets the browser determine the
best margins to use for the element. You can also use a negative margin size to create special effects.

r
a

margin-top

You set the top margin by using the margin-top property. You can specify any valid length, a percentage
value (relative to the height and width) of the element, or auto, which lets the browser determine the best
margins to use for the element. You can also use a negative margin size to create special effects.

padding-bottom

The padding-bottom property specifies the amount of space to display between the element's bottom
border and the element's contents. You can set this property to a valid length or a percentage value (relative to the
height and width) of the element.

padding-left

The padding-left property specifies the amount of space to display between the element's left border and
the element's contents. You can set this property to a valid length or a percentage value (relative to the height and
width) of the element.

padding-right

The padding-right property specifies the amount of space to display between the element's right border
and the element's contents. You can set this property to a valid length or a percentage value (relative to the height
and width) of the element.

padding-top

The padding-top property specifies the amount of space to display between the element's top border and
the element's contents. You can set this property to a valid length or a percentage value (relative to the height and
width) of the element.

width

You set the total width of the element with the width property. You can set this property for text blocks or
images. You can set this property to any length, a percentage value, or auto, which lets the browser determine the
best size for the element.

Classification Properties

You use the list properties to specify how lists display in the browser window. You can change the position
of the marker (list-style-position) and the style or image used for the marker (list-style-type and liststyle-image). The sections that follow describe each property in more detail. Enjoy.
The list properties are inherited, so if you define a property for the <UL> tag, all its enclosed <LI> tags
inherit those properties. These tags are only meaningful for HTML list tags.
You can group the list properties using list-style. You specify the marker type, marker image, and
position, like this:
list-style: square URL(http://www.myserver.com/images/marker.gif) inside

list-style-image

You use the list-style-image property to specify an image that the browser will display as the marker
for a list item. The property's only value is the URL, using the URL(address) format, of the image to use as the
marker, like this:
list-style-image: url(http://www.myserver.com/images/marker.gif)

To affect all the items within a list, set this property for the list container, such as <UL> as opposed to the
list item <LI>. You can override an individual list item, however, by setting this property in a single occurrence of
the <LI> tag.

list-style-position
The list-style-position property determines the relative position of the marker. Table B.8 describes
the possible values you can assign to this property.

3DJH 26
Table list-style-position Values

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Value

Description
Inside
The list item's text wraps to the next line underneath the marker.
Outside
The list item's text wraps to the next line underneath the start of the text on the previous
line (hanging indent).

list-style-type
You use the list-style-type property to specify the type of marker the browser will display. Use this
instead of a marker image. Table B.9 describes each of the possible values you can assign to this property.

i
d

Table list-style-type Values


Value

Description
Disc
Circle
Square
Numbered (1, 2, 3, ...)
Lowercase roman numerals (i, ii, iii, ...)
Uppercase roman numerals (I, II, III, ...)
Lowercase alphabet (a, b, c, ...)
Uppercase alphabet (A, B, C, ...)
No markers

disc
circle
square
decimal
lower-roman
upper-roman
lower-alpha
upper-alpha
none

r
a

white-space

The white-space property defines how the browser handles white space within the element. You can leave
things alone and let the browser collapse all the white space, or you can specify that the browser treat white space
as if you're within a <PRE> container. Table B.10 shows you the values you can assign to this property.

Table white-space Values


Value
normal
pre
nowrap

Description
White space is collapsed.
Handle white space like the <PRE> tag.
Wrapping is only permitted with <BR>.

Font Properties

You can group the font properties using font. You specify the weight, style, size, and family, as in the
following example:
font: bold normal 12pt times, serif

font-family

font-family is a prioritized list of typefaces for the element. You can specify a single typeface or a list of
alternatives, separated by commas, as in the following example:
font-family: Courier, Times, Serif

You can use a font name you expect to be on the user's computer, such as Courier or Helvetica, or you can
use a generic font name. Table B.11 shows the generic font names and provides an example of a font that looks
similar.

Table Generic Fonts


Name

Similar to:
Times New Roman
sans-serif
Arial
cursive
Script
fantasy
Comic
monospace
Courier New
In case the user doesn't have the font you've requested, always use a generic font name as the last item in
the list. In the previous example, serif is the last font in the list. If the user doesn't have courier or times, the
browser will use the generic font instead.
If you're using a font name that has multiple words, enclose the font name in quotes, as in the following
example:
serif

font-family: "Courier New", serif

3DJH 27

font-size

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

font-size determines the size of the text in points (pt), inches (in), centimeters (cm), or pixels (px). You
can also use a percentage, which is relative to the parent element's font size. You can also use one of the values
shown in Table B.12.

Table font-size Values


Value

Description
50 percent smaller than the x-small font
50 percent smaller than the small font
50 percent smaller than the medium font
A medium-sized font, probably 10 points
50 percent larger than the medium font
50 percent larger than the large font
50 percent larger than the x-large font
50 percent larger than the parent element's font
50 percent smaller than the parent element's font

xx-small
x-small
small
medium
large
x-large
xx-large
larger
smaller

i
d

font-style

r
a

You can change the style of the font by using the font-style property. Table B.13 describes the possible
values.

Table font-style Values


Value
normal
oblique
italic

Description
Selects a normal face
Selects an oblique face
Selects an italic face

font-variant

You use the font-variant property to display text in small caps. Setting this property to normal causes
the browser to display the text normally. Setting this property to small-caps causes the browser to display the text
using small caps.

font-weight

font-weight determines the thickness of the font. You can assign normal, bold, bolder, or lighter to

this property. You can also use the series of numbers from 100, 200, ... 900 to this property, with each successive
number representing a weight that is thicker than the previous number. For example, font-weight: 700 sets a
thicker font weight than does font-weight: 400.

Text Properties

Text properties give you complete control over how the browser displays an element's text. You can change
its color, size, font, spacing, and so on. The sections that follow describe each text property you can set.

letter-spacing

letter-spacing determines the spacing between each letter in a line of text. You can set this property to
normal and let the browser worry about it, or you can set this property to any valid length, such as 1px.

line-height

You use the line-height property to set the leading for an element. An element's leading is the distance
between the baselines of two text lines. You can use any valid length or a percentage (which is relative to the
parent element's line-height property), or you can set this property to normal. Note that the spacing is added
before each line, not after.

text-align

text-align defines how text is aligned in an element. You can set this property to any of the values shown

in Table B.14.

Table text-align Values


Value
Left
Right
Center
justify

Description
Text is left justified.
Text is right justified.
Text is centered within the element.
Text is left and right justified.

text-decoration
You can add special decorations, such as underlining, to an element by using the text- decoration
property. Table describes the values you can assign to this property. You can combine these values, too.

3DJH 28
Table text-decoration Values
Value

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Description
No decorations
Underlined text
Text with a line over it
Strikethrough
Blinking text

None
underline
overline
line-through
blink

i
d

text-indent

You use the text-indent property to indent the first line of an element's text. You can set this property to
any valid length. For example, here's how to indent the <P> tag's text to the right by one inch:
P {text-indent: 1in}

text-transform

text-transform specifies that the text should be changed according to the values in Table B.16.

Table text-transform Values


Value
capitalize
uppercase
lowercase
none

Description
Capitalizes first letter of each word
Uppercases all letters in the element
Lowercases all letters in the element
No transformation

r
a

vertical-align

You use the vertical-align property to change the vertical position of the element's text within the
element itself. You can use one of the keywords described in Table B.17.

Table vertical-align Values


Value
baseline
middle
sub
super
text-top
text-bottom
top
bottom

word-spacing

Description
Aligns the baseline of the element with the baseline of the parent
Aligns the middle of the element with the middle of the parent
Subscripts the element
Superscripts the element
Aligns the top of the element with the top of the parent element's text
Aligns the bottom of the element with the bottom of the parent element's text
Aligns the top of the element with the tallest element on the line
Aligns the bottom of the element with the lowest element on the line

word-spacing determines the spacing between each word in a line of text. You can set this property to
normal and let the browser worry about it, or you can set this property to any valid length, such as 1px.

INTRODUCTION TO JAVASCRIPT
JavaScript in Web Pages

There is definite need to allow users, browsing through a web site, to actually interact with the web site.
The web site must be intelligent enough to accept users input and dynamically structure web page content, tailor,
to a users requirements.
This may be as simple as ensuring a web page delivered to a user, having a background color that the user
is comfortable with or as complex as delivering a web page with special textual formatting for a user with visual
disabilities.
Users who browse through a web site today; prefer to chose to view what interests them. Hence even the
content of a web page needs to dynamic, based on what a user wishes to see. This requires a web site
development that will allow the creation of Interactive web pages. These web pages will accept input from a user.
Based on the input received return customized web pages, both in content and presentation, to the user.

Advantages of JavaScript
An Interpreted Language : JavaScript is an interpreted language, which requires no compilations steps. This
provides an easy development process. The syntax is completely interpreted by the browser just as it interprets
HTML tags.

3DJH 29

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Embedded within HTML : JavaScript does not require any special or separate editor for programs to be written,
edited or compiled. It can be written in any text editor like Notepad, along with appropriate HTML tags, and saved
as filename.html. HTML files with embedded JavaScript commands can then be read and interpreted by any
browser that is JavaScript enabled.
Minimal Syntax Easy to Learn : Be learning just a few commands and simple rules of syntax, complete
applications can be built using JavaScript.

i
d

Quick Development: Because JavaScript does not require time-consuming compilations, scripts can be developed
in a short period of time. This is enhanced by the fact that many GUI interface features, such as alerts, prompts,
confirm boxes, and other GUI elements, are handled by client side JavaScript, the browser and HTML code.
Designed for Simple, Small Programs : It is well suited to implement simple, small programs (for example, a
unit conversion calculator between miles and kilometers, or pounds and kilograms). Such programs can be easily
written and executed at an acceptable speed using JavaScript. In addition, they can be easily integrated into a web
page.

r
a

Performance : JavaScript can be written such that the HTML files are fairly compact and quite small. This
minimizes storage requirements on the web server and download time for the client.
Procedural Capabilities : Every programming language needs to support facilities such as Condition checking,
Looping and Branching. JavaScript provides syntax, which can be used to add such procedural capabilities to web
page coding.
Designed for Programming User Events : JavaScript supports Object/Event based programming. JavaScript
recognizes when a form Button is pressed. This event can have suitable JavaScript code attached, which will
execute when the Button Pressed event occurs.
Easy Debugging and Testing : Being an interpreted language, JavaScript scripts are tested line by line, and the
errors are also listed as they are encountered, i.e. an appropriate error message along with the line number is listed
for every error that is encountered. It is thus easy to locate errors, make changes, and test it again without the
overhead and delay of compiling.

Platform Impendence / Architecture Neutral : JavaScript is a programming language that is completely


independent of the hardware on which it works. It is a language that is understood by any JavaScript enabled
browser. Thus, JavaScript applications work on any machine that has an appropriate JavaScript enabled browser
installed. This machine can be anywhere on the network.

Writing JavaScript into HTML Document

JavaScript syntax is embedded into an HTML file. A browser reads HTML files and interprets HTML tags. Since
all JavaScripts need to be included as an integral part of an HTML document when required, the browser needs to
be informed that specific sections of HTML code is JavaScript. The browser will then use its built-in JavaScript
engine to interpret this code.
The browser is given this information using the HTML tags <SCRIPT> . </SCRIPT>. The <SCRIPT>
tag mark the beginning of scripting code. The paired </SCRIPT> marks the end of scripting code.
Syntax:

<SCRIPT LANGUAGE=JavaScript TYPE= text/javascript>


Javascript code written here
</SCRIPT>
Attributes
: Indicate the scripting language used for writing the scripting code.
LANGUAGE
Values are JavaScript & VBScript
: Specifies the media type of the scripting language, e.g., text/javascript.
TYPE
However, most browsers only support the deprecated LANGUAGE
attribute, which specifies the language name. Examples of supported
LANGUAGE values include JavaScript, JavaScript1.1, and VBScript.
The values are not case sensitive.
: The SRC attribute allows authors to reuse code by specifying an external
SRC
script

3DJH 30

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

JavaScript Syntax
JavaScript is based on an action-oriented model of the World Wide Web. Elements of a Web page, such as a
button or checkbox, may trigger actions or events. When one of these events occurs, a corresponding piece of
JavaScript code, usually a JavaScript function, is executed. That function, in turn, is composed of various
statements which perform calculations, examine or modify the contents of the Web page, or perform other tasks in
order to respond in some way to that event. For example, pressing the SUBMIT button on an online order form
might invoke a JavaScript function that validates the contents of that form to ensure that the user entered all the
required information.
In general, the elements of a JavaScript program can be divided into five categories, as follows:
Variables and their values
Expressions, which manipulate those values
Control structures, which modify how statements are performed
Functions, which execute a block of statements
Objects and arrays, which are ways of grouping related pieces of data together
This set of categories is very similar to many other languages. As we examine each of these elements in
subsequent sections we will discover that JavaScript is somewhat minimalist in its approach. Many familiar
elements, such as explicit data types (int, String, REAL), are missing or have been substantially simplified.
However, JavaScript also provides a number of powerful object-oriented constructs which greatly simplify
program organization. In this way, JavaScript has the ex-pressive power of languages such as C or Java, while also
having fewer rules to remember.

i
d

r
a

Variables and Values

One of the main differences between JavaScript and most other languages is that it does not have explicit
data types. There is no way to specify that a particular variable represents an integer, a string, or a floating-point
(real) number. Any JavaScript variable can be any of these-in fact, the same variable can be interpreted differently
in different contexts.
All JavaScript variables are declared using the keyword var. A variable may be initialized, meaning that it is given
a value when it is declared, or it may be uninitialized. In addition, multiple variables can be declared on the same
line by separating their names with commas. For example, the statements
var x = 7
var y,z = "19"
var lk = "lucky"

declare a variable named x with initial value 7, an uninitialized variable y and variables named z and lk whose
initial values are "19" and "lucky," respectively. It might seem that x is an integer, z and lk are strings, and y is
some undefined quantity. In fact, the real story is a little more complicated than this. The value of each variable
depends on the context in which it is used.

Implicit Data Types in JavaScript

There are five major implicit data types in JavaScript. A JavaScript value may be as follows:
A number, such as -5, 0, or 3.3333
A string, such as "Click Here" or "JavaScript"
One of the logical values true or false
A "non-atomic" JavaScript element, such as a function or object
The special value null
Actually, it would be more correct to say that there are five categories of data type, since it is possible to
distinguish two different types of numbers (integers and floating-point numbers), and many different types of
JavaScript objects, functions, and other structured types. In fact, part II of this book, "JavaScript Objects," is
entirely devoted to explaining the many different JavaScript objects.

Variables and Variable Names It is very important to distinguish between variables and their values. The
statement x = 10 contains two components: the variable x and the literal value 10. A literal refers to anything that
is referred to directly, by its actual value. A variable is just an abstraction that provides a way of giving names to
values. Thus the statement x = 10 says, "I am going to refer to the concrete (literal) quantity 10 by the abstract
(variable) name x," just as you might say, "I am going to call this lumpy thing I'm sitting on a chair." This also
leads to the following important piece of advice.
One final rule about variable names: a valid JavaScript variable name must begin with a letter or with the
underscore character (_). Case is important, so that norl, NoRl, NORL, and _NORL are all valid JavaScript variable
names that refer to different variables.
Numerical Values There are two numeric types in JavaScript: integers and floating-point numbers. The rules for
specifying both types are almost identical to those of C or C++ or Java. Integers may be specified in base 10
(decimal), base 8 (octal), or base 16 (hexadecimal) formats. The three forms are distinguished as follows, based on
the first one or two characters:

3DJH 31

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

1-9 followed by any set of digits is a decimal integer.


0 followed by any set of the digits 0-7 is an octal integer.
0x or 0X followed by any of 0-9, a-f, or A-F is a hexadecimal integer.
Any of the three forms can also start with a + or - sign. Thus, -45 is a decimal integer, 017 is an octal integer, and
0x12EF5 is a hexadecimal integer. The minimum and maximum integers that can be used are implementation
dependent, but at least 32 bits should be expected.
Floating-point numbers can be specified in either the standard decimal point (.) format or the engineering Enotation. Typical floating-point numbers should contain a decimal point or an exponent, which may begin with

i
d

either e or E. A floating-point number may also have a + or - sign. 0.0, -1.4e12, and 3.14159 are all valid floatingpoint numbers. The range of valid floats is again implementation dependent, but you should expect that any valid
short floating-point number, as defined by the IEEE standard, is acceptable. (The IEEE is the Institute of Electrical
and Electronics Engineers, a professional and standards-making organization.)
Strings In JavaScript, strings may be specified using either single quotes ('stuff') or double quotes ("otherstuff").
If you begin a string with one type of quote you must end it with that same form of quote-for example, "badstuff' is
not a legal string in JavaScript. Strings may also be nested by alternating the types of quotes used. In fact, you
must alternate single and double quotes if you wish to put one string inside another. Here is an example of several
nested strings (with apologies to Rudyard Kipling):
"Oh, it's 'Tommy this' and 'Tommy that' and 'throw im out, the brute'"

r
a

As in C and Java, JavaScript strings may contain special combinations of characters, known as escape sequences,
to denote certain special characters. The rules for this are still emerging, but it is probably safe to assume that all
the escape sequences defined in C will be supported. Since you will almost always be using formatting directives
of HTML (such as <BR> for a line break) you will probably not use these directives very often. At the moment, the
following sequences are supported:.
\t
tab
\r

line feed

\n

return

\f

form feed (vertical tab)

\b

backspace

The special string "" or '' represents the zero length string. This is a perfectly valid string whose length is zero.
This is the shortest JavaScript string; the length of the longest is, as usual, implementation dependent. It is
reasonable to expect that most JavaScript environments will permit very long sonnets (or very short legislative
measures) to be represented as single strings.

Logical Values The logical, or boolean, values true and false are typically used in expressions that test some
condition to determine how to proceed. If that condition is met then one set of statements is executed; if it is not
then another set is used instead. The first corresponds to the true condition, while the second represents the false
condition. Not surprisingly, such expressions are known as conditional expressions. As you will see in the
"Operators" section there are several comparison operators, such as the equality test (==), which result in logical
values.
It is possible to think of true as 1 and false as 0. In fact, JavaScript converts these logical values into 1 and 0,
respectively. JavaScript also accepts any non-zero integer in place of true, for example, so that 5 and -3 can both
be used as stand-ins for true. Many different programming languages follow this same convention. It should be
avoided in JavaScript, as it can lead to type confusion.
The Value null The value null has a very special role in the JavaScript language. It is the value of last resort,
so to speak, for every variable. For the beginning JavaScript programmer, its primary role will be in initializing
variables that do not have any more meaningful initial value. For example, in the set of variable declarations given
in the earlier "Variables and Values" section, to initialize y to some value, we should have actually written
var y = null

Type Conversion

Several of the examples in the previous section use the + operator to combine different types of things. You may
recall that when a string is combined with a number in the form
stringthing + numberthing

the number is converted to a string and the + operator then glues the two strings together (concatenation).
However, if they are combined in the opposite order
numberthing + stringthing

3DJH 32

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

then JavaScript attempts to convert the stringthing to a number and add it, numerically, to numberthing. If the
stringthing can be converted to a string, such as "-14," then all goes well; if it cannot then an error results. This
illustrates the concept of implicit conversion in JavaScript.
We have already seen that some examples of implicit conversion are completely safe. false can be converted to 0,
"5" can be converted to 5, and null can be converted to just about anything. However, some conversions are
obviously invalid, and others might be questionable. Questions such as, "May the string '3.0' be legitimately
converted to the integer 3?" are actually very difficult to answer with complete generality.
There are two approaches to handling this complex issue: use explicit conversion whenever possible, and use
implicit conversion with great care.

i
d

Statements and Operators

The basic unit of work in JavaScript is the statement, as is the case in most programming languages. A JavaScript
statement accomplishes work by causing something to be evaluated. This can be the result of giving a value to a
variable, by calling a function, by performing some sort of calculation, or any combination of these. We have
already seen variable declaration statements, which not only create (declare) a new variable, but also give it an
initial value, such as the following statement:
var x = 10

JavaScript programs, as mentioned at the beginning of this chapter, are collections of statements, typically
organized into functions, which manipulate variables and the HTML environment in which the script itself works,
in order to achieve some goal.

r
a

The Structure of JavaScript Statements

Before plunging into a detailed description of the various types of statements and the operators they use, let's
examine one simple statement in excruciating detail. Consider the statement
y = x + 5

This statement contains three parts: the result y, the operator = and the expression x + 5. The result always occurs
in the left side, since JavaScript always operates from left to right, and is often called the lvalue. The result must
always be something that can be modified. It would be erroneous to write null = x + 5, for example, because
null is a built-in, unchangeable component of JavaScript itself-it cannot be modified, so it can never appear as a
result.
The operator = is the assignment operator, of course. It causes the expression on the right to be evaluated and its
value given (assigned) to the result. The expression x + 5 contains another operator, the + operator, which acts to
combine x and 5 in some context-specific way. Since x is a number in this case, the + operator performs ordinary
addition, and y gets the value 15. As we have already seen, if x had been a string, such as "bleh," then + would
have acted as a string concatenation operator and y would be given the value "bleh5" instead. This is an example of
operator overloading-the + operator can do different things in different situations. Many JavaScript operators are
overloaded.

Operators

The set of operators that JavaScript uses is, once again, very similar to that of the C, C++, and Java languages. It
provides a number of different ways of combining different values, both literals and variables, into expressions.
Some operators require two elements to participate in the operation, and are referred to as binary operators. The +
operator is a binary operator. Other operators require only a single participant (operand), and are known as unary
operators. The ++ operator, which adds 1 to its operand, is a unary operator. Operators may also join forces to form
aggregate operators, as we shall see next.
JavaScript operators may be classified into the following groups:
Computational operators
Logical operators
Bitwise operators
Assignment and aggregate operators
This grouping is purely functional, and is based on what the operators actually do. The next four subsections
examine each type of operator in more detail. Table 2.1 summarizes the operators in each category and how they
are used. Table : A Summary of JavaScript Operations
Computational Operators
+
Addition, String Concatenation
Subtraction, Unary Negation

Multiplication

Division

Modulus

++

Preincrement, Postincrement

--

Predecrement, Postdecrement

3DJH 33
Logical Operators

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

==, !=
<,<=,=>,>

Equality, Inequality
Arithmetic and String Comparison

Logical NOT

&&,||

Logical AND, Logical OR

Conditional Selection (trinary)

Logical Concatenation

&,|

Bitwise AND, Bitwise OR

Bitwise eXclusive OR (XOR)

Bitwise NOT_

i
d

Bitwise Operators

<<,>>,>>>
Assignment Operators
=
OP=

Shift Left, Shift Right, Unsigned Shift Right


Assignment
Aggregate Assignment
(+,-,*,/,%,&,|,^,~,<<,>>,>>>)

r
a

Comments in JavaScript Code

All professional code should have comments that clearly indicate the purpose and logic behind each major section
of the code. JavaScript offers two comment styles-the original comment style from C and the single line comment
style from C++ and Java.
C style comments are typically used to document major functions or code blocks. Because a C comment may
extend over multiple lines it is ideal for detailed discussions of important parts of the code. A C comment begins
with /* and ends with */. Our aesthetically pleasing function beaupage() might begin with a thorough description
of just what makes it so beautiful, as follows:
/*
The function beaupage() draws a stunningly beautiful
Web page by performing the following nineteen steps.
... list of the 19 steps
*/

Control Structures

At this point, you have had just enough of the JavaScript language to declare variables, perform assignments, and
do various types of arithmetic, string, and logical calculations. You are not yet able to write any meaningful code
because you do not have any higher level constructions. In this section, we will consider various methods of
controlling the way in which statements are executed. The next section will expose the highest level of JavaScriptits functions and objects.
There are three types of control structure in JavaScript, as follows:

if
while
for

These three control structures are very similar. Each is introduced by a keyword (while, for, and if, respectively)
and each manipulates a block of JavaScript statements. A block is introduced by a left brace ({) and terminated
with a right brace (}). There can be as many JavaScript statements between { and } as you wish, or as few. A block
of code can even be empty, with nothing between the braces. In many ways, a block of statements is like a single
gigantic statement. In particular, block structured constructs are often all or nothing-either the entire contents of the
block are executed, or none of it is. Since blocks behave like single statements, it is also possible to put blocks
inside other blocks, in a nested fashion.
As you will see, each of the three control structures has its own specific format and its own special uses, although
it is often possible to achieve the same results using any of the three types, with varying degrees of elegance.

The if Statement

The if statement is used to conditionally execute a single block of code. It has two forms, the simple if statement
and the ifelse statement. The simple if statement consists of a conditional expression, known as the if test, and
a block of code which is executed if that expression evaluates to a boolean true. An example of an if statement
follows:
if ( condstmt ) {
zero or more statements
}

The block of code within the braces is often called the if block. The conditional statement condstmt can be any
expression that yields a logical value. Note that numerical expressions may also be used; 0 is construed as false

3DJH 34

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

and all other values are taken to be true. As stated earlier, an if statement should be considered a single
statement. Code blocks are not traditionally terminated with a semicolon, although there is no harm in doing so.
if ( ( x < 10 ) && ( -10 < x ) ) {
// if test
y = ( x * x * x );
// 1: cube of x
ystr = "The cube of " + x + " is " + y; // 2: informative string
}

The while Statement

i
d

The while statement is used to execute a block of code while a certain condition is true. The format of the while
statement is as follows:
while ( condstmt ) {
zero of more statements
}
The condition clause condstmt is evaluated as a logical expression. If it is true then the block of statements
between the braces is executed. The flow of control then loops back to the top of the while statement, and
condstmt is evaluated again. This process continues until the condstmt becomes false, or until some statement

within the block forces it to terminate. Each pass through the block of code is called an iteration.
The first fundamental difference between a while statement and an if statement is that the while block may be
executed many times, while the if or else blocks are executed once at most. You might well wonder how a while
statement ever terminates.

r
a

var x = 1;
var xsum = 0;
while ( x <= 10 ) {
xsum += x;
x++;
}

// loop until x is greater than 10


// add x to the running sum xsum
// increment x

Using the break Statement There is a third way for a while loop to terminate. If the special statement break is
encountered inside the while block, the loop is forced to terminate immediately. No further statements are
executed and the condstmt is not retested.
var
var
var
var

x = 1;
xoddsum = 0;
xtmp = 0;
lastx = 0;

while ( true ) {
// 1: loop forever (well, almost)
xtmp = xoddsum + x;
// 2: compute a trial sum
if ( xtmp > 100 )
// 3: if it is too large, then...
break;
// 4: we are done
xoddsum += x;
// 5: add x to the running sum xoddsum
x += 2;
// 6: increment x by 2
}
lastx = x;
// 7: save the final value of x in the variable
lastx

Using the continue Statement There is another special statement that may be used inside while loops: the
continue statement. The continue statement is used to force the flow of control back to the top of the while
loop. When a continue statement is seen, all statements between it and the end of the while block are skipped, and
execution continues at the top of the while. Listing 2.6 shows a simple use for the continue statement.
var x = 0;
var xsum = 0;
var loopcount = 0;

while ( loopcount++ < 100 ) {


// 1: loop 100 times
x++;
// 2: increment x
if ( ( x % 5 ) == 0 )
// 3: if x is divisible by 5
continue;
// 4: skip it
xsum += x;
// 5: otherwise, add x to xsum
}

The for Statement


The for statement is the most powerful and complex of the three flow control constructions in JavaScript. The
primary purpose of the for statement is to iterate over a block of statements for some particular range of values.
The for statement has the following format:

3DJH 35

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

for ( initstmt; condstmt; updstmt ) {


forblock
}
The for clause, as shown, has three parts, separated by two mandatory semicolons. The initstmt is typically used
to initialize a variable, although any valid statement may be used in this position. The initstmt is always
executed exactly once, when the for statement is first encountered. The condstmt is a conditional test, and serves
exactly the same function as in the while statement. It is tested at the top of each loop. The for statement
terminates when this condition evaluates to false. The updstmt is executed at the bottom of each loop, as if it
were placed immediately after the last statement in the for block. It is typically used to update the variable that is
initialized by the initstmt.

i
d

var xsum = 0;
var x;
for ( x = 1; x <= 10; x++ ) {
// 1: loop while x is <= 10
xsum += x;
// 2: add x to xsum
}

A second useful feature of the for statement is that both the initialization portion and the update portion of the for
clause may contain multiple statements separated by the comma operator (,).

r
a

var xsum = 0;
for ( var x = 1, lcnt = 0; lcnt < 100; x++, lcnt++ ) {
if ( ( x % 5 ) == 0 )
// if x is divisible by 5
continue;
// skip it
xsum += x;
// otherwise, add x to xsum
}

This usage underlines the fact that both x and lcnt are used only within the body of the for loop. It is also much
more compact than its counterpart in listing 2.6. In this example, we need not worry about the logical effect of the
continue; we know that both x++ and lcnt++ will always be executed. This is also the most common and useful
way to use the comma operator.

Functions and Objects

The basic statements, expressions, and operators that were discussed at the beginning of this chapter are what
computer scientists usually call primitives. Primitives are the building blocks from which more complex elements
of a program are constructed. The for, while, and if control structures represent the next higher level of
organization in JavaScript. Each of these control structures deals with blocks of code whose execution is controlled
by the various conditional tests and other clauses. The for, while, and if statements are all block structured.
Functions and objects represent the highest level of organization within the JavaScript language. We will spend
many chapters learning how to make effective use of these concepts. The purpose of this section is to introduce
them and describe their basic features.

Functions

A function is a block of code that has a name. Whenever that name is used the function is called, which means that
the code within that function is executed. Functions may also be called with values, known as parameters, which
may be used inside the body of the function. Functions serve two purposes. A function is an organizational tool, in
the sense that it permits you to perform the same operation without simply copying the same code.
The second purpose of JavaScript functions is to link actions on a Web page with JavaScript code. Mouse clicks,
button presses, text selections, and other user actions can call JavaScript functions by including suitable tags in the
HTML source for the page.
The syntax for a function statement in JavaScript is as follows:
function Name ( listofparams ) {
body
}
The function's Name is given immediately after the function keyword. All function names should be unique, and

also should not conflict with any of the statement names which JavaScript itself uses (known as the reserved
words). You cannot have a function named while, for example, and you should not have two functions both
named UserHelp. The listofparams is a comma-separated list of the values that are passed into the function.
These are referred to as the function's parameters, or arguments. This list may be empty, indicating that the
function does not use any arguments (often called a void function). The function's body is the set of statements that
make up the function.

function summation ( endval ) {


var thesum = 0;
// this variable will hold the sum
for ( var iter = 1; iter < endval; iter++ ) {
thesum += iter;
// add the integer into the sum

}
return( thesum );

3DJH 36

// end of the for loop


// return the sum

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Objects
Functions are used to provide a uniform method for organizing code. Objects serve the same purpose for data. Up
to this point, the only data items we have seen are simple variables declared with var. Each of these typeless
quantities can only hold a single value of some sort at a time. Objects provide the ability to hold multiple values, so
that a group of related data elements can be associated with one another.
What JavaScript calls an object is called a data structure (or class) in many other languages. As with JavaScript
functions, there are two aspects to JavaScript objects: creating them and using them. For the moment, we will defer
the question of how to create objects and concentrate on how they are used. We will also see that a JavaScript
capable browser will provide a number of its own, built-in objects.
A JavaScript object is made up of a set of component parts, which are called its properties, or members. Suppose
you have an object named appt which you are using to organize your appointments. The appointment object might
have properties that specify the date and time of the appointment, as well as the name of the person with whom the
appointment will take place. It might also have a general description field to remind you of the purpose of this
meeting. Thus, you can imagine that the appt object will have the following properties:

day
month
time
who
why

i
d

r
a

Each of the properties of the appt object are referenced using the dot operator (.). Thus, appt.month refers to the
month property and appt.why gives us the reason for the appointment. These references may appear on both the
right and left sides of an expression; we may get their values and also set them.
if ( appt.day == Today ) {
document.write('<BR>You have an appointment today<BR>');
document.write('See ' + appt.who + ' at ' + appt.time<BR>');
document.write(appt.why + '<BR>');
}

This example assumes that the variable Today has somehow been initialized with today's date, so that the equality
test with appt.day is only true for today's appointments. If the test does succeed then the three statements in the
if block are executed. Each of these references document.write. The document object is a built-in object of the
Netscape Navigator browser. This object has a member known as write, which is actually a function. Functional
members of JavaScript objects are known as methods. This particular method takes a string and displays it on the
current Web page.
Each of the three strings that are passed to document.write are constructed using + as a string concatenation
operator. Each of them references one or more properties of the appt object in order to provide meaningful
messages to the user. Each also includes <BR>, the HTML construction for a line break. This ability to directly
issue HTML directives is one of the most powerful aspects of JavaScript, as it allows the programmer to
dynamically modify the contents of Web pages using JavaScript functions and objects.
Once you learn more about the Date object, in "The Date Object" section of chapter 5, you will be able to
construct a much more satisfying version of this example. Even at this stage, however, the advantage of objectbased programming should be apparent. Rather than carrying about many variables, you can use objects instead.
Each object can contain all the variables of interest to a particular idea. It can also contain method functions that
perform related work. Objects can even contain other objects, so that you can organize your data in a hierarchical
structure. Subsequent chapters explore these ideas in much greater detail.

Built-In Objects

Now that we have covered the foundations of object-oriented programming in JavaScript we can begin
to look at the actual objects that JavaScript itself provides. These objects can be put into the following three
categories:

String Objects

String objects are the most built-in of all the built-in JavaScript objects. You do not even use new
when creating a string object. Any variable whose value is a string is actually a string object. Literal strings
such as "HelloWorld" are also string objects.

3DJH 37

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

String objects have one property, length, and many methods. The length property gives the length
of the string. The methods fall into three categories: methods that manipulate the contents of the string,
methods that manipulate the appearance of the string, and methods that convert the string into an HTML
element.
String Content Methods
The following methods can be used on string objects to access, control, or modify their content:

i
d

charAt( idx )
indexOf( chr )
lastIndexOf( chr )
substring( fromidx, toidx )
toLowerCase()
toUpperCase()

The toLowerCase and toUpperCase methods convert the contents of the string entirely to lower- and
uppercase, respectively. So if we define the string variable

r
a

var mystr = "Look At This"

String Appearance Methods The string appearance methods are used to control how a string appears when
displayed on a Web page. If you are creating a page with standard HTML tags you would achieve the same effects
by using various tags. For example, to make the string "help" appear in italics you would write <I>help</I>. The
string appearance methods allow you to obtain the same effects in JavaScript without using the corresponding
HTML elements. The string appearance methods are as follows:

big()
blink()
bold()
fixed()
fontcolor( colr )
fontsize( sz )
italics()
small()
strike()
sub()
sup()

The Math Object

The Math object is used for various forms of mathematical calculations. It contains several
properties that are standard constants, such as pi = 3.14159, as well as a large set of methods that
represent common trigonometric and algebraic functions. All Math methods deal with floating-point
numbers. Angles are expected to be given in radians, not degrees.
The Math object is our first example of a static object. A static object is one that does not change.
All of the slots in the Math object already have values. This makes perfect sense, since you cannot change
the value of pi or invent a new meaning for the cos() function (not without creating chaos). The practical
consequence of Math being static is that you never use new with Math; you always refer to the Math object
directly. Math is the opposite of the String object. The String object has instances but no explicit object;
the Math object has only itself, and no instances.
The Math object has the following properties:

E
LN10
LN2
PI
SQRT1_2
SQRT2

3DJH 38
The Math object has the following methods:

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

abs( num )
acos( num )
asin( num )
atan( num )
ceil( num )
cos( ang )
exp( num )
floor( num )
log( num )
max( num1, num2 )
max( num1, num2 )
pow( num1, num2 )
random()
round( num )
sin( ang )
sqrt( num )
tan( ang)

r
a

i
d

These are all the functions and constants you find on any decent calculator. Remember that JavaScript
is case-sensitive, so you must write Math.PI exactly to get the value of pi. The constants stand for the base
of the natural logarithm (Napier's constant, or about 2.71828), the natural log of 10 (about 2.30259), the
natural log of 2 (about 0.69315), everyone's favorite pi (about 3.141592653589793), the square root of 1/2
(about 0.7071), and the square root of 2 (about 1.4142).

The Date Object

Dealing with dates is one of the most tedious tasks in any language. This is because many people
like to represent dates and times in decidedly nondecimal systems. Months come in units of 12, hours in
units of 24, and minutes and seconds in units of 60. All these variations are quite illogical from the
computer's standpoint. It likes to deal with nice, round numbers, preferably powers of 2, or at least
multiples of 10.
The Date object simplifies and automates a lot of the conversion woes associated with going back
and forth between a human readable representation, such as November 23, 1990, and the internal
representation. JavaScript's Date object follows the UNIX standard of storing date and time information
internally as the number of milliseconds since January 1, 1970. This date is often called "The Epoch," since
it is shortly after UNIX was first unleashed on an unsuspecting world.

The Date object has no properties, but many methods. In order to use the Date object you must first understand
how to construct instances of it. There are three basic methods of creating a Date instance, as follows:

new Date()
new Date( datestring )
new Date( yr, mon, day )

The Date object has a large set of methods for getting and setting the components of a date. These methods are as
follows:

getDate()
getDay()
getHours()
getMinutes()
getMonth()
getSeconds()
getTime()
getYear()
setDate()
setHours()
setMinutes()
setMonth()
setSeconds()
setTime()
setYear()

3DJH 39

Built-In Functions

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

You have now had your first exposure to the built-in String, Math, and Date objects. Some of
these objects are more built-in than others. While Date acts like an actual object, with the exception of its
two static methods, the String object is almost invisible. All normal JavaScript programs manipulate
strings as if they are a separate data type. The essence of a string is part of the JavaScript language.
There is also a small set of functions built in to JavaScript itself. They are not methods, and are never
applied to an instance using the dot operator (.). They are on the same plane as functions that you create
using the function keyword. At present, there are five such built-in functions; they are as follows:

i
d

escape( str )
eval( str )
parseFloat( str )
parseInt( str, radix )
unEscape( str )

The escape and unEscape functions are used to convert to and from the escape code convention used
by HTML. In HTML a number of special characters, such as the HTML delimiters < and >, must be
represented in a special way to include them in ordinary text. For example, if you have written any HTML
at all then you know that you sometimes need to write %20 to represent a space character. The escape
built-in function takes a string representing one of these special characters and returns its escape code in the
form %xx, where xx is a two-digit number. Thus, escape(" ") returns %20, the code for a space character.
The unEscape function is the inverse of the escape function. It takes an escape code and returns the character which that code represents. Thus unEscape("%20") returns the string " " (a single space character).

r
a

The parseFloat built-in function attempts to parse its string argument as a floating-point number. It
only continues parsing the str until it encounters a character that could not possibly be part of a valid
floating-point number, such as g. The parseInt built-in function performs a similar operation. It attempts
to parse its str argument as an integer in base radix. Thus we would obtain the following values:
parseFloat("+3.14williamtell5") = 3.14
parseInt(10111, 2) = 23

Browser Objects

The primary browser objects, in rough order of significance, are as follows:

window
document
location
history

The window Object

JavaScript maintains an idea of the current window, so that almost all references to sub-objects of the current
window do not need to refer to it explicitly. This is why all of our output has been done using document.write()
rather than window.document.write(). window objects have the following interesting methods (among others):

alert( msgstr )

close()
confirm( msgstr )
open( urlstr, wname )
prompt( msgstr )

The document Object

Every window is associated with a document object. The document object contains properties for every
anchor, link, and form on that page, as well as all of the sub-elements of those elements. It also contains properties
for its title (the content of the <TITLE> field of the page), its foreground color (the fgColor property), its
background color (the bgColor property), its various link colors, and other attributes of the page itself. The
document object has the following methods:

3DJH 40

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

clear()

close()
open()
write( str )
writeln( str )

The clear method is used to completely erase a document window. The entire contents are wiped out,
regardless of how they got there. The clear method is particularly useful if you are constructing a Web page
entirely within JavaScript, and want to make sure it is empty before you start. The open and close methods are
used to start and stop buffered output. If you call the open method, perform a series of writes and/or writelns,
and then call the close method, the results of your write operations are layed out and appear on the page.

i
d

The history and location Objects

The history object is used to refer to the history list of previously visited URLs. The history object has a
property known as length, which indicates how many URLs are stored on the history list at present. It also has the
following three methods:

back()

r
a

forward()
go( where )

The go method is used to navigate the history list. The where argument can be a number or a string. If the
where argument is a number then it indicates how far we wish to move in the history list. A positive number means
that we wish to move that many documents forward in this history list, while a negative number is used to move
backward. Thus, go(5) has the same effect as using the Forward button five times, while go(-1) would be the
same as clicking the Back button once. If where is a string representing a URL then that URL is loaded, and
becomes the current document.
The location object describes the URL of a document. It has properties representing the various components of
the URL, including its protocol part, its hostname part, its pathname part, and its port number part, among other
properties. Unfortunately, these properties are often null, at least in the UNIX version of Netscape Navigator 2.0.
It also has a toString method which can be used to convert it to a string. We can use the following code to
display a formatted message giving the current URL:

var loc = document.location;


document.write("<BR>URL is " + loc.toString());
document.write("<BR>");

HTML Objects

The important aspect of this example is not its primitive HTML, but the fact that the HTML elements in it are
reflected in the JavaScript object hierarchy. We have already seen that we can access the title of this document
through the title property of the document object. We can also access the other HTML elements of this
document using the following properties:

anchors
forms
links

These properties of the document object are arrays representing every HTML element that is an anchor, form, or
link on the page. In our particular example there is only one of each, so we would refer to the anchor at the top of
the page as document.anchors[0], the link at the bottom of the page as document.links[0], and the form in the
middle of the page as document.forms[0]. These are the top-level HTML objects represented by this document.
Each of these elements, in turn, has properties and methods that can be used to describe and manipulate it.
In particular, the form object corresponding to forms[0] has sub-objects for each of the three form elements (the
reset button, the submit button, and the text input field), as well as properties for the submit method and the
submit target. forms[0].elements[0] corresponds to the text input field. forms[0].elements[0].name is the
name of that field, as specified by the NAME field, which is "me" in this case.

3DJH 41

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Example 1 : Creating a New Window in JavaScript

<HTML><HEAD><TITLE>Opening a Window with JavaScript</TITLE>


<SCRIPT>
//window globals
var aNoteWin
function openNote(topic)
{
aPopUp= window.open(, Note,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,
copyhistory=no, resizable=yes,width=300,height=200)
ndoc= aPopUp.document
astr ='<HTML><HEAD><BR><TITLE>' + topic + '</TITLE>'
astr +='</HEAD>'
astr +='<BODY>'
astr +=topic + '<BR>'
astr +='</BODY></HTML>'
ndoc.write(astr)
ndoc.close()
self.aNoteWin = aPopUp
}
function closeNote()
{
self.aNoteWin.close()
}
</SCRIPT></HEAD>
<BODY><H3><BR><HR><BR></H3><CENTER>
<FONT SIZE=5 COLOR='darkred'><B>Example 1</B></FONT>:
<FONT SIZE=5 COLOR='darkblue'><B>Opening a New Window</B></FONT>
<FORM NAME='noteForm'>
<INPUT TYPE='button' NAME='makeBtn' VALUE='Make Note' onclick='openNote("JoAnn
Murphy at 7:00; bring salad")'>
<INPUT TYPE='button' NAME='closeBtn' VALUE='Close note' onclick='closeNote()'>
</FORM></CENTER><H3><BR><HR><BR></H3></BODY></HTML>

Including Multimedia

i
d

r
a

Using Animated GIFs

The first animations that appeared on the Web required a great deal of effort. Using an approach introduced
by Netscape called server push, you could create an animation by having a server literally push several
images down an open HTTP connection. When presented in sequence on the browser screen, these images
created the illusion of animation. Setting this up required knowledge of the Common Gateway Interface
(CGI) and some type of programming language. Since most digital media graphic artists don't have
knowledge of CGI programming, producing a Web animation often required collaboration between the
artists and the server administrator. Then it occurred to someone that the GIF 89a standard supports
multiple images stored in the same file. Further, you could place instructions in the file header that describe
how the images should be presented. In short, the 89a standard gives you everything you need to produce
an animation! The individual frames that comprise the animation can all be stored in one file, and you can
specify in the file header parameters like how much delay before starting the animation and how many
times the animation should repeat.
Animated GIFs let you place animations on a page without knowledge of programming.
Creating animated GIFs has become fairly easy with the advent of software tools like the GIF Construction
Set, available at http://www.mindworkshop.com. In this program, you can specify the individual GIF
files that make up the animation and presentation instructions in a set of dialog boxes. When you're
finished with the setup, the program will create the animated GIF file using the information you specified.

Adding Sounds
There are three different kinds of audio files your computer can play: digitized audio, music files, and text-tospeech. Text-to-speech is a technique for converting text files into (somewhat) recognizable speech by replacing

3DJH 42

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

the letters with phonemes. The Macintosh is particularly adept at this. Music files are like sheet music--they
specify a sequence of notes and the "instruments" to play them. MIDI music files are the most popular format in
this category. Digitized audio is sound that has been run through an analog-to-digital converter to turn it into data.
Your PC's system sounds are WAV format files that are digitized audio.

Using <BGSOUND> tag


<bgsound src="Musica Asterisk.wav" loop="-1">
<bgsound src="Musica Asterisk.wav" loop="2">

i
d

Using <EMBED> tag

The <EMBED> tag is used to embed plug-in content on an HTML page, and the way in which a page designer uses
the <EMBED> tag often determines how plug-in content is displayed.
For example, the <EMBED> tag's attributes control several different aspects of the LiveAudio plug-in's functionality.
Here's a typical example:
<EMBED SRC="audio.mp3" WIDTH=144 HEIGHT=60 AUTOSTART=false VOLUME=100 CONTROLS=Console>

r
a

This example plays the Macintosh format sound file AUDIO.AIF (SRC="audio.aif") only when the user presses
the Play button (AUTOSTART=false). The LiveAudio control window is 144 pixels wide (WIDTH=144) and 60 pixels
high (HEIGHT=60) and contains a complete control console (CONTROLS=Console).
Attribute
SRC="filename"

Values
A file name with an extension associated with a MIME type assigned to be played by
LiveAudio (.AU, .AIFF, .AIF, .WAV, .MIDI, or .MID). Required.

WIDTH=integer

The control console width in pixels. Required.

HEIGHT=integer

The control console height in pixels. Required.

AUTOSTART=TRUE|FALSE If True, the sound clip plays automatically. The default is False.
AUTOLOAD=TRUE|FALSE

If False, the sound clip does not automatically load. The default is True.

STARTTIME="mm:ss"

The start time in minutes and seconds from the start of the clip. The default is 00:00.

ENDTIME="mm:ss"

The end time in minutes and seconds from the start of the clip. The default is the end of
the clip.

VOLUME=percentage

Playback volume expressed as a percentage of the maximum. The default is the last
previously set volume.

ALIGN="value"

The point at which to align the control panel with respect to adjoining text. The possible
values are CENTER, BASELINE, TOP, LEFT, and RIGHT. BASELINE is the default.

CONTROLS="value"

The controls to include on the control panel. The values can be CONSOLE, SMALLCONSOLE,
PLAYBUTTON, PAUSEBUTTON, STOPBUTTON, or VOLUMELEVER. The remainder of this table
describes the sets of controls associated with each of these values. The default is
CONSOLE.

CONSOLE

A full set of controls: Play, Pause, Stop, and Volume.

SMALLCONSOLE

A reduced set of controls consisting of Play, Stop, and Volume. AUTOSTART defaults to
True.

PLAYBUTTON

The Play button only.

PAUSEBUTTON

The Pause button only.

STOPBUTTON

The Stop button. Also, the sound file unloads.

VOLUMELEVER

The Volume control only.

CONSOLE="name"

A combination of controls that enables you to include multiple sound clips on a page. For
example, you could specify CONSOLE="MySetup" as an attribute on two <EMBED> lines on
a single HTML page; then each line would use the controls defined by the other as well as
its own.

3DJH 43

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Adding Video
To embed MPEG videos into your pages for viewing with InterVU, you first need to make the following MIME
type associations in your server software:
video/mpeg

mpg
*.mpe
*.mpv
*.mpeg
*.mp1
*.mp2
video/x-mpeg mpg
*.mpe
*.mpv
*.mpeg
*.mp1
*.mp2

i
d

r
a

Next, you use the EMBED tag, including the standard SRC, WIDTH, and HEIGHT attributes, as well as these optional
attributes:

AUTOPLAY=NO|YES. If YES, the clip is automatically played. NO is the default. (It's unfortunate that this plugin doesn't use TRUE and FALSE with AUTOSTART, which is the standard usage.)

FRAMERATE=integer. Legitimate values are from 1 to 25, representing frames per second. (This attribute

automatically disables sound.)

LOOP=Integer. Enter the number of times you want the video to play. Each time the Start button is pressed,

the video plays the specified number of times.

DOUBLESIZE=YES|NO. Default is NO. If YES, the video is shown at double the encoded size.

HALFSIZE=YES|NO. As DOUBLESIZE, but half the size.

CONBAR=YES|NO. If NO, the control toolbar is not displayed. Default is YES.

FRAMES=YES|NO. If YES, autoplays the video on a Mac when Netscape Framesets are used.

PALETTE=FOREGROUND|BACKGROUND. If FOREGROUND, specifies that the video's palette be used as the

standard palette on a 256-color screen.

Using <IMG > tag


<img border="0" src="logo.gif" dynsrc="outline.mpeg"
loop="infinite" start="fileopen" width="103" height="117">

Including Java Applets

The APPLET element is used to embed Java applets. It has been deprecated in HTML 4.0 in favor of the
more generalized OBJECT element. However, since the few browsers that support OBJECT do so with
significant bugs, APPLET is currently a more reliable method of embedding Java applets.
APPLET's CODE attribute specifies the name of the class file that contains the compiled Applet subclass.
The value is relative to the URI specified in the CODEBASE attribute, or to the HTML document's base
URI if the CODEBASE attribute is not given.
The required WIDTH and HEIGHT attributes define the dimensions of the applet. The value may be
given in pixels or as a percentage of the parent element's width or height.

3DJH 44

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

The ALT attribute can be used to give alternate text for browsers that recognize the APPLET element but
do not support Java or do not have Java enabled. Authors can also give alternate content between the start
and end tags of the APPLET element--a better method than using the ALT attribute since it allows authors
to include HTML markup in the alternate content and also works with pre-HTML 3.2 browsers that do not
support APPLET.
An APPLET may contain PARAM elements to define applet-specific parameters. PARAM elements
should be specified before any other content of the APPLET element. In the following example, a
decorative Java applet takes two parameters. The APPLET contains an animated GIF as an alternative for
non-Java browsers.

i
d

<APPLET CODE="Animate.class" WIDTH=100 HEIGHT=100>


<PARAM NAME=img1 VALUE="/images/1.jpg">
<PARAM NAME=img2 VALUE="/images/2.jpg">
<IMG SRC="animation.gif" ALT="" WIDTH=100 HEIGHT=100>
</APPLET>

Understanding XML

r
a

Since HTML made its smashing debut a few years ago, it has seen numerous revisions. Each
revision brought more features to the specification, which may, in turn, be implemented in a given browser.
More often than not, a browser implements not only most of the features defined by the specification, but
also a series of its own proprietary tags. The Netscape layer tag is an example.
In looking at the revision problem that plagued HTML, it became necessary to develop a new
markup language that could be implemented once and never need revisions. Instead of looking to a new
mark-up language, the engineers at the W3C decided to look back to the roots of HTML.
As most of you remember, HTML is a very slimmed-down version of SGML, which is a featurerich language for marking up data. SGML as it currently exists is a rather good language for marking up
data. Unfortunately, it is not geared for deployment in a network environment. Where SGML is a good
extensible language, HTML is a simple non-extensible language. As a middle point with the networkcentric non-extensible HTML on one end and the non-network-centric extensible SGML on the other, the
engineers at the W3C developed eXtensible Markup Language (XML).
XML as envisioned by the W3C will exist in only one form for as long as the Web exists. It is
designed to allow developers to dynamically describe the information stored in a Web page. By making
Web pages self-describing, it will be possible to not only have Web browsers accessing the Web, but also
for developers to write custom search tools which scour the Web for specific information.
In designing XML, the W3C has taken into account ten design goals. These goals define a plan for
a markup language that is better than HTML in that it fixes the evolution and compatibility problems, and
is better than SGML in that it's geared for Internet deployment and is easier to use.
The W3C defines the XML's goals as follows (taken from http://www.w3.org/TR/WD-xml-lang):
XML shall be straightforwardly usable over the Internet.
XML shall support a wide variety of applications.
XML shall be compatible with SGML.
It shall be easy to write programs that process XML documents.
The number of optional features shall be kept to the absolute minimum, ideally zero.
XML documents shall be human-legible and reasonably clear.
The XML design should be prepared quickly.
The design of XML shall be formal and concise.
XML documents shall be easy to create.
Terseness in XML markup is of minimal importance.
This chapter will examine where XML as a language is heading. The chapter will give an overview of the
technology, discuss its uses, and also some areas where it is not of use.

XML as a Metalanguage

XML is what is referred to as a metalanguage, or a language for describing other languages. In your case,
XML allows you to create documents that describe themselves to their reader. While some may attempt to
say that the same is true for HTML, HTML lacks an easily expandable vocabulary. In order to expand on
HTML, a proposal needs to be submitted to and approved by the W3C. However, to expand on XML, one
simply has to use the new descriptors in an XML file. For example, take a look at the XML fragment in
Listing 33.1:

Listing 33.1 Sample XML Describing a Listing of Books


<heading>Great San Francisco Books</heading>
<title>Tales of the City</title>

3DJH 45

<author>Armistead Maupin</author>
<title>The Vampire Lestat</title>
<author>Anne Rice</author>
<title>Access San Francisco Restaurants</title>
<author>Graceann Walden</author>

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

The most obvious thing in Listing 33.1 is that these tags, while HTML-like, are not in any way approved
by the W3C. This could obviously create problems to applications that you want to work with the data.

i
d

Though HTML does describe to a browser the manner in which the HTML page should be displayed on
screen, that is not an XML document's purpose. An XML document simply serves to describe the data
contained in the files. When an XML page is sent to a browser for on-screen display, it usually arrives with
a style sheet or Document Type Definition (DTD), which tells the browser how to display the text. What's
important is that XML does not simply make on-screen display easier, it also simplifies the job of
applications, such as search engines. Because the XML in Listing 33.1 describes to the reader the location
of all authors, search engine applications can now easily index the document by author.

Creating XML

An explanation of what XML is and what needs it provides for are covered in the previous sections. In this
next section, you dive in and take a look at what is required of an XML document.
In its raw form, XML looks very similar to HTML, as you can see in Listing 33.1. The languages sport a
similar look because of their common ancestor, SGML. XML and HTML have many functional
differences.
The first, most obvious difference is that XML tag structure is very rigid. In HTML, there are tags that
always have an opening and closing tag pair (<CENTER></CENTER>), tags that stand alone (<BR>), and tags
that do either (<P></P>, or simply <P>). To further confuse the tag situation, most browsers will attempt to
display even incorrect HTML. For example, if you are missing a </TABLE> tag Navigator will usually still
display the table, while Internet Explorer will not. This browser work-around may make a lot of Web pages
look better, but since incorrect HTML is still displayed, sloppy HTML coding is also encouraged.
In contrast, XML requires that all tags either exist in pairs, or announce to the reader that a closing tag is
not present. For example, the <BR> tag rendered in XML appears either as <BR></BR> or <BR/>. Note that
when the <BR/> tag stands alone, it ends with a trailing slash, indicating the lack of a closing tag.
In addition to those requirements, XML also requires that all attribute values occur in quotation marks. For
example, the following tag pair is incorrect: <COLOR value=red></COLOR>. Instead, opt for the slightly
different: <COLOR value="red"></COLOR>. HTML originally asked the same of authors. However, it
seems that over time, authors stopped using quotation marks and browsers stopped requiring them.
Finally, XML allows no illegal nesting of tags. This means that for every open tag, its closing tag must
appear at an unambiguous location. For example, in Listing 33.2, there may be some confusion regarding
which question is being closed by the first and then the second </question> tags.

r
a

Listing 33.2 Invalid XML tag structure

<title>Coversation</title>
<question>What is the average flying speed of a swallow?
<question>What kind of swallow?</question></question>

Listing 33.3 contains a better option.

Listing 33.3 Valid XML tag structure

<title>Coversation</title>
<question>What is the average flying speed of a swallow? </question>
<question>What kind of swallow?</question>

Creating Valid/Well-Formed Pages

One of the keys to creating XML pages is knowing the rules the reader applications use when evaluating a
given page. Because these rules are strictly defined (and hopefully enforced), it is actually rather easy to
create documents that follow all the required rules. In fact, at the end of this chapter there are URLs to
three publicly available parsers that you can use to test your currently developing XML.
When developing an XML file, that file can be defined as either valid, well-formed, or both. Valid XML
files are those that have and follow a given Document Type Definition (DTD).

3DJH 46

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Short Questions
1. Where can I find a list of all the current HTML tags?

2.

The current W3C Recommendation is HTML 4.0. HTML 4.0 extends HTML 3.2 to include support
for frames, internationalization, style sheets, advanced tables, and more. HTML 4.0 is not well
supported by current browsers, but many of its features can be used safely in non-supporting
browsers.
Recommended materials on HTML 4.0:
http://www.w3.org/TR/REC-html40/ -- the official HTML 4.0 Recommendation
http://www.htmlhelp.com/reference/html40/ -- a handy reference, with notes on using poorly supported
features safely
Recommended materials on HTML 3.2:
http://www.w3.org/TR/REC-html32 -- the official HTML 3.2 Recommendation
http://www.htmlhelp.com/reference/wilbur/ -- a more readable version of the above
http://www.hut.fi/~jkorpela/HTML3.2/ -- Jukka Korpela's "Learning HTML 3.2 by Examples"
Some materials on browser-specific versions of HTML:
http://www.blooberry.com/html/supportkey/a.htm -- Brian Wilson's checklist of browser support for
HTML tags and attributes
Developer Netscape -- a list of all available Netscape HTML tags
Microsoft Workshop -- a list of all available Microsoft HTML tags

i
d

r
a

How do I get a so-and-so character in my HTML?

The safest way to do HTML is in (7-bit) US-ASCII, and expressing characters from the upper half
of the 8-bit code by using HTML entities. See the answer to "Which should I use, &entityname; or
&#number; ?"
Working with 8-bit characters can also be successful in many practical situations: Unix and MSWindows (using Latin-1), and also Macs (with some reservations).
The available characters are those in ISO-8859-1, listed at <URL:HTMLHelp>. On the Web, these
are the only characters widely supported. In particular, characters 128 through 159 as used in MSWindows are not part of the ISO-8859-1 code set and will not be displayed as Windows users
expect. This includes the em dash, en dash, curly quotes, bullet, and TM symbol; neither the actual
character nor &#nnn; is correct. (See the last paragraph of this answer for more about those
characters.)
On platforms whose own character code isn't ISO-8859-1, such as MS DOS, Macs, there may be
problems: you'd have to use text transfer methods that convert between the platform's own code and
ISO-8859-1 (e.g Fetch for the Mac), or convert separately (e.g GNU recode). Using 7-bit ASCII
with entities avoids those problems, and this FAQ is too small to cover other possibilities in detail.
Mac users - see the notes at the above URL.
If you run a web server (httpd) on a platform whose own character code isn't ISO-8859-1, such as a
Mac, or IBM mainframe, it's the job of the server to convert text documents into ISO-8859-1 code
when sending them to the network.
If you want to use characters outside of the ISO-8859-1 repertoire, you must use HTML 4.0 rather
than HTML 3.2. See the HTML 4.0 Recommendation at <URL:W3> and the Babel site at
<URL:Babel> for more details. Another useful resource for internationalization issues is at
<URL:flavell>.

3.

Should I put quotes around attribute values?

It depends. It is never wrong to use them, but you don't have to if the attribute value consists only of
letters (A-Za-z), digits, periods and hyphens. This is explained in the HTML 2.0 specs.
Be careful when your attribute value includes double quotes, for instance when you want ALT text
like "the "King of Comedy" takes a bow" for an image. Humans can parse that to know where the
quoted material ends, but browsers can't. You have to code the attribute value specially so that the
first interior quote doesn't terminate the value prematurely. There are two main techniques:
Escape any quotes inside the value with &#34; so you don't terminate the value prematurely: ALT="the
&#34;King of Comedy&#34; takes a bow". (&quot; is not part of the formal HTML 3.2 spec, though most
current browsers support it.)
Use single quotes to enclose the attribute value: ALT='the "King of Comedy" takes a bow'.
Both these methods are correct according to the spec and are supported by current browsers, but
both were poorly supported in some earlier browsers. The only truly safe advice is to rewrite the
text so that the attribute value need not contain quotes, or to change the interior double quotes to
single quotes, like this: ALT="the 'King of Comedy' takes a bow".

3DJH 47

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

4. How can I include comments in HTML?


A comment declaration starts with "<!", followed by zero or more comments, followed by ">". A
comment starts and ends with "--", and does not contain any occurrence of "--" between the
beginning and ending pairs. This means that the following are all legal HTML comments:

<!-- Hello -->


<!-- Hello -- -- Hello-->
<!---->
<!------ Hello -->
<!>

i
d

But some browsers do not support the full syntax, so we recommend you follow this simple rule to
compose valid and accepted comments:
An HTML comment begins with "<!--", ends with "-->" and does not contain "--" or ">"
anywhere in the comment.
See <URL:HTML Help> for a more complete discussion.

5. How can I check for errors?

The easiest way to catch errors in your HTML is through the use of a program called a validator. A
validator is a program which knows all the rules in HTML, reads your source document and outputs
a list of mistakes.
While checking for errors in the HTML, it is also a good idea to check for hypertext links which are
no longer valid. There are several link checkers available for various platforms which will follow
all links on a site and return a list of the ones which are non-functioning.
You can find a list of validators and link checkers at <URL:HTML Help>. Especially
recommended is the use of an SGML-based validator such as the WDG HTML Validator
<URL:HTML Help> or W3C HTML Validation Service <URL:w3.org>.

r
a

6. What is a DOCTYPE? Which one do I use?

According to HTML standards, each HTML document begins with a DOCTYPE declaration that
specifies which version of HTML the document uses. The DOCTYPE declaration is useful
primarily to SGML-based tools like HTML validators, which must know which version of HTML
to use in checking the document's syntax. Browsers generally ignore DOCTYPE declarations.
See <URL:HTML Help> for information on choosing an appropriate DOCTYPE declaration.

2. Web Publishing

2.1. Where can I put my newly created Web pages?

Many ISPs offer web space to their dial-up customers. Typically this will be less than 5MB, and
there may be other restrictions; for example, many do not allow commercial use of this space.
There are several companies and individuals who offer free web space. This usually ranges from
100KB up to 1MB, and again there are often limitations on its use. They may also require a link to
their home page from your pages. The following page has pointers to several lists of free web space
providers: <URL:Yahoo Free Pages>.
There are also many web space providers (aka presence providers) who will sell you space on their
servers. Prices will range from as little as $1 per month, up to $100 per month or more, depending
upon your needs. Non-virtual Web space is typically the cheapest, offering a URL like:
http://www.some-provider.com/yourname/ For a little more, plus the cost of registering a domain
name, you can get virtual web space, which will allow you to have a URL like
http://www.yourname.com/.
If you have some permanent connection to the Internet, perhaps via leased line from your ISP then
you could install an httpd and operate your own Web server. There are several Web servers
available for almost all platforms.
If you just wish to share information with other local users, or people on a LAN or WAN, you
could just place your HTML files on the LAN for everyone to access, or alternatively if your LAN
supports TCP/IP then install a Web server on your computer.

2.2. Where can I announce my site?

comp.infosystems.www.announce -- a moderated newsgroup specifically geared toward this subject. You


need to obtain its FAQ list before posting to it.
http://www.submit-it.com/ lets you submit site information to 20 different major index sites for free. If you
wish to pay you may submit your site to over 400 sites.
http://ep.com/faq/webannounce.html is the How to Announce your New Web Site FAQ.

2.3. Is there a way to get indexed better by the search engines?


Yes. Use a meaningful <TITLE> and headings (<H1>, <H2>, and so on). The indexing programs of
some search engines (including AltaVista and Infoseek) will also take into account the following
tags in the <HEAD> part of your documents:
<META
NAME="keywords"
CONTENT="keyword
keyword
keyword
<META NAME="description" CONTENT="description of your site">

keyword">

3DJH 48

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Both may contain up to 1022 characters, but no markup other than entities. If you use a keyword
too often in the <META NAME="keywords"> tag, the indexing program may ignore your keywords
list altogether. At this writing, "too often" means "more than 7 times" to some popular engines, but
that may change in the future as indexing programs are changed to defend against "cheaters."
Search Engine Watch at <URL:http://searchenginewatch.com/> is a Web site dedicated to search
engines and strategies for Web page authors.

2.4. How do I prevent my site from being indexed by search engines?


See <URL:WebCrawler>.

i
d

2.5. How do I redirect someone to my new page?

The most reliable way is to configure the server to send out a redirection instruction when the old
URL is requested. Then the browser will automatically get the new URL. This is the fastest and
most efficient way, and is the only way described here that can convince indexing robots to phase
out the old URL. For configuration details consult your server admin or documentation (with
NCSA or Apache servers, use a Redirect statement in .htaccess).
If you can't set up a redirect, there are other possibilities. These are inferior because they tell the
search engines that there's still a page at the old location, not that the page has moved to a new
location. But if it's impossible for you to configure redirection at your server, here are two
alternatives:
Put up a small page with text like "This page has moved to http://new.url/ -- please adjust your bookmarks."
A Netscape and MSIE solution, which doesn't work on many other browsers (and screws up the "back"
button
in
Netscape)
is:
<META

r
a

HTTP-EQUIV="Refresh"

CONTENT="x;

URL=new.URL">

which will load the new URL after x seconds. This should go in the HEAD of the document. But if you do
this, also include a short text saying "Document moved to new URL so-and-so" for other browsers. (The
screwing-up bit refers to the fact that if you press "Back" after you have been redirected, you will be taken
to the document with the META refresh. Then the refresh will be activated, and so you'll jump to the page
you just tried to leave.)

2.6. How do I password protect my web site?

Password protection is done through HTTP authentication. The configuration details vary from
server to server, so you should read the authentication section of your server documentation.
Contact your server administrator if you need help with this.
For example, if your server is Apache, see <URL:Apache>.

2.7. How do I hide my source?

You can't. The source is necessary for the browser to display your document. You have to send the
complete, unencrypted source to the browser. Even if a particular browser doesn't have a "View
source" option, there are many that do, and you can always retrieve the document by hand (using
telnet) to get its source. Or check the browser's cache.
You can of course put a hundred empty lines above the actual source. Then newbies who don't see
the scrollbars will think there is nothing there.

2.8. How do I detect what browser is being used?

Many browsers identify themselves when they request a document. A CGI script will have this
information available in the HTTP_USER_AGENT environment variable, and it can use that to
send out a version of the document which is optimized for that browser.
Keep in mind not all browsers identify themselves correctly. Microsoft Internet Explorer, for
example, claims to be "Mozilla" to get at Netscape enhanced documents.
And of course, if a cache proxy keeps the Netscape enhanced document, someone with another
browser will also get this document if he goes through the cache.
For these reasons and others, it is not a good idea to play the browser guessing game.

2.9. How do I get my visitors' email addresses?

You can't. Although each request for a document is usually logged with the name or address of the
remote host, the actual username is almost never logged as well. This is mostly because of
performance reasons, as it would require that the server uses the ident protocol to see who is on the
other end. This takes time. And if a cache proxy is doing the request, you don't get anything
sensible.
But just stop to think for a minute... would you really want every single site you visit to know your
email address? Imagine the loads of automated thank you's you would be receiving. If you visited
20 sites, you would get at least 20 emails that day, plus no doubt they would send you invitations to
return later. It would be a nightmare as well as an invasion of privacy!
In Netscape 2.0, it was possible to automatically submit a form with a mailto as action, using
JavaScript. This would send email to the document's owner, with the address the visitor configured
in the From line. Of course, that can be "[email protected]". This was fixed by Netscape
2.01.

3DJH 49

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

The most reliable way is to put up a form, asking the visitor to fill in his email address. To increase
the chances that visitors will actually do it, offer them something useful in return.

3. Web Design
3.1. How do I include one file in another?
HTML itself offers no way to seamlessly incorporate the content of one file into another.
True dynamic inclusion of one HTML document (even in a different "charset") into another is
offered by the OBJECT element, but due to shortcomings of browser versions in current use, it
seems unwise to rely on this yet for essential content. The same can be said for IFRAME.
Two popular ways of including the contents of one file seamlessly into another for the WWW are
preprocessing and server-side inclusion.
Preprocessing techniques include the C-preprocessor and other generic text manipulation methods,
and several HTML-specific processors. But beware of making your "source code" non-portable.
The HTML can only be validated after pre-processing, so the typical cycle "Edit, Check, Upload"
becomes "Edit, Preprocess, Check, Upload" (here, "Check" includes whatever steps you use to
preview your pages: validation, linting, management walk-through etc.; and "upload" means
whatever you do to finally publish your new pages to the web server).
A much more powerful and versatile pre-processing technique is to use an SGML processor (such
as the SP package) to generate your HTML; this can be self-validating.
Examples of server-side inclusion are Server Side Includes "SSI" (Apache, NCSA and some other
web servers) and "ASP"; processing occurs at the time the documents are actually retrieved. A
typical inclusion looks like

i
d

r
a

<!--#include virtual="/urlpath/to/myfile.htm" -->

but be sure to consult your own server's documentation, as the details vary somewhat between
implementations. The whole directive gets replaced by the contents of the specified file.
Using server-side inclusion (a potentially powerful tool) merely as a way to insert static files such
as standard header/footers has implications for perceived access speed and for server load, and is
better avoided on heavily loaded servers. If you use it in this way, consider making the result
cacheable (e.g., via "XBitHack full" on Apache; setting properties of the "Response" object in
ASP). Details are beyond the scope of this FAQ but you may find this useful:
http://www.pobox.com/~mnot/cache_docs/
Proper HTML validation of server-side inclusion is only possible after server-side processing is
done, e.g. by using an on-line validator that retrieves the document from the server.

3.2. Which should I use, &entityname; or &#number; ?

In HTML, characters can be represented in three ways:


1. a properly coded character, in the encoding specified by the "charset" attribute of the "Content-type:"
header;
2. a character entity (&entityname;), from the appropriate HTML specification (HTML 2.0/3.2, HTML 4.0
etc.);
3. a numeric character reference (&#number;) that specifies the Unicode reference of the desired character.
We recommend using decimal references; hexadecimal references are less widely supported.
In theory these representations are equally valid. In practice, authoring convenience and limited
support by browsers complicate the issue.
HTTP being a guaranteed "8-bit clean" protocol, you can safely send out 8-bit or multibyte coded
characters, in the various codings that are supported by browsers.

A. HTML 2.0/3.2 (Latin-1)

By now there seems no convincing reason to choose &entityname; versus &#number;, so use
whichever is convenient.
If you can confidently handle 8-bit-coded characters this is fine too, probably preferred for writing
heavily-accented languages. Take care if authoring on non-ISO-8859-based platforms such as Mac,
Psion, IBM mainframes etc., that your upload technique delivers a correctly coded document to the
server. Using &-representations avoids such problems.

B. A single repertoire other than Latin-1

In such codings as ISO-8859-7 Greek, koi8-r Russian Cyrillic, and Chinese, Japanese and Korean
(CJK) codings, use of coded characters is the most widely supported and used technique.
Although not covered by HTML 3.2, browsers have supported this quite widely for some time now;
it is a valid option within the HTML 4.0 specification--use a validator such as the WDG HTML
Validator at http://www.htmlhelp.com/tools/validator/ which supports HTML 4.0 and understands
different character encodings.
Browser support for coded characters may depend on configuration and font resources. In some
cases, additional programs called "helpers" or "add-ins" supply virtual fonts to browsers.
"Add-in" programs have in the past been used to support numeric references to 15-bit or 16-bit code
protocols such as Chinese Big5 or Chinese GB2312.

3DJH 50

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

In theory you should be able to include not only coded characters but also Unicode numeric
character references, but browser support is generally poor. Numeric references to the "charsetspecified" encoding may appear to produce the desired characters on some browsers, but this is
wrong behavior and should not be used. Character entities are also problematical, aside from the
HTML-significant characters &lt;, &amp; etc.

C. Internationalization per HTML 4.0

Recent versions of the popular browsers have support for some of these features, but at time of
writing it seems unwise to rely on this when authoring for a general audience. If you'd like to
explore the options, you can find comprehensive background documentation and some practical
suggestions at
http://www.czyborra.com/
http://www.hut.fi/u/jkorpela/chars.html
http://ppewww.ph.gla.ac.uk/~flavell/charset/

i
d

3.3. Should I use lower case or upper case for tags?

Tags are case insensitive, so it doesn't matter. This is just a matter of style. (You may have noticed
that this FAQ is not absolutely consistent in capitalization.) Many people prefer upper case, as it
makes the tags "stand out" better amongst the text.
Attribute names can also be upper or lower case, as you prefer. But some attribute values are case
sensitive. For example, <OL TYPE=A> and <OL type=A> are the same, but <OL TYPE=a> is different
from both of them. (For clearer communication, it's worth getting the terminology right. In this
example, OL is the element, TYPE is the attribute name, and A and a are the attribute values. The tag
is <OL TYPE=A>.)
Entity names like &nbsp; are sometimes incorrectly referred to as tags. They are all case sensitive.
For example, &Eacute; and &amp;eacute; are two different and valid entities; &NBSP; is invalid.

r
a

3.4. For what screen size should I write?

HTML does not depend on screen size. Normally, the text will be wrapped by the browser when the
end of its display area is encountered. (Note that graphical browsers are often used with windows
that are smaller than the full area of the screen.)
Preformatted lines (text within <PRE> elements) should only ever exceed 70 characters if the nature
of the content makes it unavoidable. Longer lines will cause ugly line breaks on text-mode
browsers, and will force horizontal scrolling on graphical browsers. Readers strongly dislike
horizontal scrolling, except where they can realise that the nature of the content made it inevitable.
Images cannot be wrapped, so you have to be careful with them. It seems that 400 or 500 pixels is a
reasonable width; anything above 600 will mean a certain percentage of users will have to scroll to
see the rightmost bit. This percentage increases with your image width. Keep in mind that not
everyone runs his browser at full screen!
(WebTV users have no ability to scroll horizontally, so anything beyond 544 pixels will be
compressed by their browser. Some other devices may be even more limited.)

3.5. Why does my page display fine in browser X but incorrectly or not at all in browser
Y?
There are several possibilities.
First, you may have some incorrect HTML. Browsers vary in their ability to guess what you meant.
For instance, Netscape is much more fussy about tables than MS Internet Explorer, so a page with
incorrect tables may look fine in MSIE but not display at all in Netscape. See the answer to "How
can I check for errors?" for tips on finding your HTML errors. (In fact, even correct nested tables
may not display correctly in Netscape. See "Can I nest tables within tables?" below for what you
can do about that.)
Second, you may have valid HTML that different browsers interpret differently. For instance, it is
not clear from the spec what should be done with a string of &nbsp; characters. Some browsers will
collapse them for rendering as a single space; others will render one space per &nbsp;.
Other possibilities are a bug in one or the other browser, or different user option settings.
See also the ansewrs to "Why are my hyperlinks coming out all wrong or not loading?" and "Why
are my images coming out all wrong or not loading?"

3.6. How do I freeze the URL displayed in a visitor's browser?


This is a "feature" of using frames: The browser displays the URL of the frameset document, rather
than that of the framed documents. (See the answer to the question "How do I specify a specific
combination of frames instead of the default document?").
However, this behavior can be circumvented easily by the user. Many browsers allow the user to
open links in their own windows, to bookmark the document in a specific frame (rather than the
frameset document), or to bookmark links. Thus, there is no reliable way to stop a user from getting
the URL of a specific document.

3DJH 51

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Furthermore, preventing users from bookmarking specific documents can only antagonize them. A
bookmark or link that doesn't find the desired document is useless, and probably will be ignored or
deleted.

3.7. How do I make a table which looks good on non-supporting browsers?


See Alan Flavell's document on tables for a good discussion at <URL:Flavell>.

3.8. Can I nest tables within tables?


Yes, a table can be embedded inside a cell in another table. Here's a simple example:

i
d

<table>
<tr>
<td>this is the first cell of the outer table</td>
<td>this is the second cell of the outer table,
with the inner table embedded in it<br>
<table>
<tr>
<td>this is the first cell of the inner table</td>
<td>this is the second cell of the inner table</td>
</tr>
</table>
</td>
</tr>
</table>

r
a

The main caveat about nested tables is that Netscape has problems with them if you don't close
your TD and TR tags meticulously. You're best advised to include every </TD> and </TR>, even
though the HTML spec doesn't require them; otherwise Netscape users may not be able to view
your page.

3.9. How do I center a table?

The "correct" way of doing it is <TABLE ALIGN=CENTER>, but this doesn't work in several popular
browsers. Put <CENTER>; around the entire table for these browsers.
This causes some problems with browsers that do support CENTER but not tables, such as Lynx. In
these browsers, the contents of the cells are now displayed centered, which is not what is intended.
To avoid this, you can put the cell's contents in <P ALIGN=left> or <DIV ALIGN=left> depending
on the amount of text in the cell.

4. Hyperlinks
4.1. Should I end my URLs with a slash?

The trailing slash is used to distinguish between directory and file URLs. A file URL is an URL for
a file, and a directory URL refers to a directory. For example, the URL for the WDG's HTML
reference is http://www.htmlhelp.com/reference/ and the URL for the overview of HTML 3.2
elements is http://www.htmlhelp.com/reference/wilbur/overview.html
If you request a directory URL without the trailing slash, the browser will actually ask for a FILE
with that name. This file doesn't exist on the server, so the server sends back a message saying that
the browser should ask for the directory. It uses a redirection message for this. The browser then
sends another request, this time for the directory, and finally gets what was asked for in the first
place. This wastes time and network resources.
When you write a document, all directory URLs should end with a slash. Since you already know
you are linking to a directory, why force the user to make that second request, when it could have
been done using only one?
And by the way, it is NOT the browser which appends the slash. The browser cannot know if what
you are asking for is a file or directory, not even when the final part of the URL does not have an
extension. http://www.somewhere.com/src/something/README is a perfectly valid URL, has no
extension in the final part, yet refers to a file and not a directory.
The only apparent exception is when you refer to an URL with just a hostname. Since it is obvious
that when you use http://www.htmlhelp.com you actually want the main index "/" from our server,
you do not have to include the / in this case. It is regarded as good style to do so, however.
For a full discussion of the proper form of URLs, see RFC 1738 at <URL:cis> and, for relative
URLs, RFC 1808 at <URL:cis>.

4.2. How do I create a link that opens a new window?


<A TARGET="_blank" HREF=...> opens a new, unnamed window.
<A TARGET="foobar" HREF=...> opens a new window named "foobar", provided that a window

or frame by that name does not already exist.


Note that links that open new windows can be annoying to your readers if there is not a good reason
(from the reader's perspective) for them.

4.3. How do I get a button which takes me to a new page?


This is best done with a small form:

<FORM
<INPUT
</FORM>

3DJH 52

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

ACTION="http://url.you.want.to.go.to/"
TYPE=submit
VALUE="Text
on
button"

METHOD=GET>
NAME=foo>

If you want to line up buttons next to each other, you will have to put them in a one-row table, with
each button in a separate cell.
Note that search engines might not find the target document unless there is a normal link
somewhere else on the page.
A go-to-other-page button can also be coded in JavaScript, but the above is standard HTML and
works for more readers.

i
d

4.4. How do I get a back button on my page?

In HTML, this is impossible. Going "back" means that you go to the previous page in your history.
You might be able to create a link to the URL specified in the "HTTP_REFERER" environment
variable in your document, but that only creates a link to a new location in your history. Even
worse, the information in that variable can be plain wrong. Some browsers incorrectly send the
variable when you use a bookmark or type in an URL manually, and some don't send that variable
at all. This would result in an empty link.
A JavaScript could use "history.back()" to do this, but this only works in Netscape 2 or higher and
MSIE 3 or higher, and even then only if the user has not disabled JavaScript.
For a more detailed explanation, please see Abigail's "Simulating the back button" at
<URL:Abigail>.

r
a

4.5. How do I create a link that sends me email?


Use a mailto: link, for example

Send
me
email
<A HREF="mailto:[email protected]">[email protected]</A>.

4.6. How do I specify a subject for a mailto: link?

at

You can't, not in any reliable way. The methods that are frequently posted don't do the job on all
browsers (or even all popular browsers), and many of them have an important drawback: if your
visitors are using an older browser such as Netscape 1.22, their mail will be lost.
If you really need a subject, you can do it by providing a form on your page, which submits data to
a CGI program that emails the form data to you with your desired subject line. However, the form
must have an input field for the visitor's email address, and you must hope that the visitor enters it
correctly.
Here are some other ways to transmit subject-type information:
Create email aliases that are used only for certain mailto links, so you'll know that anything sent to a given
alias is in response to the corresponding Web page(s).
The mail handlers for many Web browsers include an "X-Url" header that specifies the URL of the Web
page that contained the mailto link. If you configure your mail reader to display this header, you'll see
which Web page the sender is responding to much of the time.
Use <A HREF="mailto:user@site" TITLE="Your Subject">. Most browsers will ignore the TITLE
attribute, but some minor browsers will use it as a subject for the email message. All browsers will send the
mail.
Use <A HREF="mailto:user@site?subject=Your%20Subject">, which puts "Your Subject" (the space
is encoded as "%20") in the "Subject" header field of the email message in most current browsers. The
details of this recent RFC can be found at <URL:isi>. Note however that you will lose mail from users of
older browsers, so you should consider whether the pre-filled subject is worth lost mail.

4.7. How do I eliminate the blue border around linked images?


<IMG ... BORDER=0>

4.8. How do I turn off underlining on my links?

If you want to turn off link underlining when you're looking at pages in your browser, check your
browser's configuration options. In Netscape 3, for example, see Options | General Preferences |
Appearance; in Netscape 4 it's Edit | Preferences | Appearance | Colors; in Internet Explorer see
View | Options | General.
If you want to prevent links on your page being underlined when your visitors see them, there's no
way in HTML to accomplish this. You can suggest this presentation using style sheets by defining
a:link, a:visited, a:active {text-decoration: none}

4.9. How can I have two sets of links with different colors?
You can suggest this presentation using style sheets. In your style sheet, define something like this:
a:link
{color: blue;
background: white}
a:visited
{color: purple; background: white}
a:active
{color: red;
background: white}
a.foo:link
{color: yellow; background: black}
a.foo:visited {color: white; background: black}
a.foo:active {color: red;
background: black}
Then use CLASS="foo" to identify the links of the second color in your HTML, like this:
<A CLASS="foo" HREF=...>...</A>

3DJH 53

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

4.10. Why are my hyperlinks coming out all wrong or not loading?

Most likely you forgot to close a quote at the end of the HREF attribute. Alternatively, perhaps you
used a ">" character somewhere else inside a tag. Although this is legal, several older browsers will
think the tag ends there, so the rest is displayed as normal text.
This especially happens if you use comment tags to "comment out" text with HTML tags. (See the
answer to "How can I include comments in HTML?") Although the correct syntax is <!-- -->
(without "--" occurring anywhere inside the comment), some browsers will think the comment
ends at the first ">" they see.
Validators will show you any syntax errors in your markup, but checkers such as Weblint and
HTMLchek can show you where you are liable to provoke known browser bugs. See also the
answer to "How can I check for errors?"

i
d

4.11. Why does my link work in Internet Explorer but not in Netscape?

Is there a space, #, ?, or other special character in the path or filename? Spaces are not legal in
URLs. If you encode the space by replacing it with %20, your link will work.
You can encode any character in a URL as % plus the two-digit hex value of the character. (Hex
digits A-F can be in upper or lower case.) According to the spec, only alphanumerics and the
special characters $-_.,+!*'() need not be encoded.
You should encode all other characters when they occur in a URL, except when they're used for
their reserved purposes. For example, if you wanted to pass the value "Jack&Jill" to a CGI script,
you would need to encode the "&" character as "%26", which might give you a URL like the
following: http://www.foo.com/foo.cgi?rhyme=Jack%26Jill&audience=child. Note that the "?" and
other "&" character in this URL are not encoded since they're used for their reserved purposes.
See section 2.2 of RFC 1738 at <URL:w3.org> for the full story.

r
a

5. Other Media

5.1. How do I let people download a file from my page?

Once the file is uploaded to the server, you need only use an anchor reference tag to link to it. An
example would be:
<a href="../files/foo.zip">Download Foo Now! (100kb ZIP)</a>

It is possible that the server might need to be configured for some different file types. (See the next
Q&A.)

5.2. Why did my link to a _______ file only download a bunch of characters instead?

If you are trying to link to a particular type of file and it is not returning your desired response,
chances are that the server needs to have the type configured. Talk to your system administrator
about getting them to add the content type. Here is a list of common types that often need
configuring:
Content Type
Description
Application/msword
Microsoft Word Document
application/octet-stream Unclassified binary data (often used for compressed file or executable)
application/pdf
PDF Document
application/wordperfect6.0 WordPerfect 6.0 Document
application/zip
ZIP archive
audio/x-wav
WAV audio format
audio/midi
MIDI audio format
audio/x-pn-realaudio
RealAudio
image/gif
GIF image format
image/jpeg
JPEG image format
image/png
PNG image format
text/html
HTML document
text/plain
Plain text
video/mpeg
MPEG video format
video/quicktime
QuickTime video format
video/x-msvideo
AVI video format
Another method of ensuring that your file is properly sent to the client is to compress it into a
standard compression format. Virtually all servers are set to handle the .zip extension and it is
widely recognized by users.
Some servers (NCSA, Apache, and others) can be configured to support user-configured content
types. Details are server dependent, so consult your server admin or documentation.

5.3. How do I force a download?


You can't, because the Web doesn't work that way.

3DJH 54

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Here's the explanation. When someone downloads a document, the server tells the browser what
type of file it is. The browser then displays it or picks the appropriate helper application. If the
server doesn't know the file type, it tells the browser that the file is "text/plain", or just plain text
(true for most servers). You may need to ask your server admin to configure this particular file with
the MIME type you want.
"Forcing" a download is not what you are supposed to do. After all, what is more convenient than
having the proper application started when I download a particular file? Browsing through a
download directory can be quite a pain. And most browsers allow the user to download to disk if
they want to.
If the file must be saved to disk, if there is absolutely NO other way to handle it, the MIME type
should be "application/octet-stream".

i
d

5.4. How do I make animated GIFs?

Check out the following resources:


http://members.aol.com/royalef/gifanim.htm
http://www.adobe.com/studio/tipstechniques/GIFanimation/main.html
http://www.webreference.com/dev/gifanim/

5.5. Why am I getting a colored whisker to the left or right of my image?

This is the result of including "white space" (spaces and newlines) before or after an IMG inside an
anchor. For example:

r
a

<A
<IMG
</A>

HREF=...>
SRC=...>

will have white space to the left and right of the image. Since many browsers display anchors with
colored underscores by default, they will show the spaces to the left and right of the image with
colored underscores.
Solution: don't leave any white space between the anchor tags and the IMG tag. If the line gets too
long, break it inside the tag rather than outside it, like this:
<A
SRC=...></A>

HREF=...><IMG

Style checkers such as Weblint will call attention to this problem in your HTML source.

5.6. Why are my images coming out all wrong or not loading?

Most likely you forgot to close a quote at the end of the SRC attribute. Alternatively, perhaps you
used a ">" character in an ALT text or somewhere else inside a tag. Although this is legal, several
older browsers will think the tag ends there, so the rest is displayed as normal text.
This especially happens if you use comment tags to "comment out" text with HTML tags. (See the
answer to "How can I include comments in HTML?") Although the correct syntax is <!-- -->
(without "--" occurring anywhere inside the comment), some browsers will think the comment
ends at the first ">" they see.
Validators will show you any syntax errors in your markup, but checkers such as Weblint and
HTMLchek can show you where you are liable to provoke known browser bugs. See also the
answer to "How can I check for errors?"

5.7. Can I put markup in ALT text?

No. Character entities (&copy;, &#nnn; and such) are permitted, though.
If you want to know how to write good ALT texts without markup, please see Alan Flavell's essay
on choosing ALT texts at <URL:flavell>.

5.8. How do I get an audio file to play automatically when someone visits my site?
Most browsers support the EMBED element for this, provided that the user has a suitable plug-in
for the sound file. You can reach a slightly wider audience if you use BGSOUND as well. To avoid
problems with browsers that support both, place the BGSOUND in a NOEMBED container:
<EMBED
SRC="your_sound_file"
HIDDEN=true
<NOEMBED><BGSOUND SRC="your_sound_file"></NOEMBED>

AUTOSTART=true>

For more on the EMBED element, see <URL:Developer Netscape>. See <URL:MSDN> for more
information on BGSOUND. Note that these elements are proprietary and not in any HTML
standard. (The HTML standard way of doing this is not well supported.)
Be aware that some users find it annoying for music to automatically start playing. They may not
have the volume set properly on their speakers, or they may be listening to something else. As a
courtesy to your users, you may prefer to offer the sound file as a link:
<A HREF="your_sound_file">Listen to my sound! (5 kB MIDI)</A>

5.9. How can I strip all the HTML from a document to get plain text?
One of the easiest ways is to open a document in a graphical browser such as Internet Explorer or
Netscape, select all the text and copy it to the clipboard. Most browsers also have a "save as"
function which will allow you to save the file as plain text.
Lynx users can use "lynx -dump http://..." on the command line to print to file and append a list of
referenced URLs as footnotes. If you want the output file without the footnotes, use the "p"
command to "print" to a text file.

3DJH 55

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

You can use 1st Page to strip all HTML tags. Goto Tools -> Strip All Tags from the 1st Page menus.

6. Presentational Effects
6.1. How can I make a custom rule?
Your best option is likely a centered IMG with a line of "--" characters as ALT text:
<P ALIGN=center><IMG SRC="custom-line.gif" ALT="--------------------"></P>

For an experimental but somewhat more graceful approach, read about CSS1 and the Decorative
HR at <URL:flavell>.

6.2. How can I make a list with custom bullets?

i
d

There are several methods, none completely satisfactory:


Use the list-style property of Cascading Style Sheets. This should be the preferred method of using custom
bullets, but unfortunately it's not widely supported by browsers. However, non-supporting browsers will
see a normal bullet, so using this method today is not a problem. See <URL:HTML Help> for more
information on style sheets.
Use a <DL> with <DD> tags with preceding images (with ALIGN and suitable ALT text) and no <DT>; this
won't be as beautiful as a "real" list.
Use a two-column table, with the bullets in the left column and the text in the right. Since browsers show
nothing before downloading the entire table, this can be slow with long lists.
Create the bullet with the indent built in. For example, if you use a bullet that is 10 pixels across you can
make the background 25 pixels (transparent) and put the bullet all the way on the right. This will create a
15-pixel indent to the left of the bullet. It will add slightly to the byte size of the graphic but since it is all
one color it won't add much. This method doesn't work well with any list items that are longer than a line
(and remember that you don't know how long a line will be on the visitor's screen).

r
a

6.3. Where can I get a "hit counter"?

A hit counter is a small script or program that increases a number every time a document is
accessed from the server.
Why do you want one? If you believe that it will tell you how many times your documents have
been accessed, you are mistaken. No counter can keep track of accesses from browser caches or
proxy caches. Some counters depend on image-loading to increment; such counters ignore accesses
from text-mode browsers, or browsers with image-loading off, or from users who interrupted the
transfer. Some counters even require access to a remote site, which may be down or overloaded,
causing a delay in displaying your documents.
Most web servers log accesses to documents stored on the server machine. These logs may be
processed to gain information about the *relative* number of accesses over an extended period.
There is no reason to display this number to your viewers, since they have no reference point to
relate this number to. Not all service providers allow access to server logs, but many have scripts
that will output information about accesses to a given user's documents. Consult your sysadmin or
service provider for details.
Counter services and information are available from Yahoo's list of counters: @ Yahoo Access
Counts/
Log analysis tools and scripts are at @Yahoo analysis tools/A>
<URL:Markwelch Counters> is another good source for counter information.

6.4. How do I display the current date or time in my document?

With server-side includes. Ask your webmaster if this is supported, and what the exact syntax is for
your server. But this will display the local time on the server, not for the client. And if the
document is cached, the date will of course be incorrect after some time. JavaScript can be used to
display the local time for the client, but again, as most people already have one or more clocks on
their screen, why display another one?
If you plan on putting the current date or time on your pages, using a CGI, JavaScript or VBScript,
take an extra breath and consider that it will take resources, add time to the loading of the page, and
prevent good caching. If you find that you really have a need to use it, for instance to inform
readers of the up-times of an FTP server, then by all means do so. If, on the other hand, your only
reason is 'it looks cool!' - then reconsider.

6.5. How do I get scrolling text in the status bar?


This is not an HTML question; it's done with JavaScript. Check any page which has this feature,
and copy the script from the source.
This script has two big problems. One, usually it uses the decrement operator (c--) at some point.
The "--" sequence in a comment actually closes it on some browsers, so your code may "leak" on
those browsers. The same goes for ">".
Second, keep in mind that many people consider this even worse than <BLINK>, and that it also
suppresses the status information which normally appears there. It prevents people from knowing
where a link goes to.

3DJH 56

6.6. How do I right align text or images?

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

You can use the ALIGN=right attribute on paragraphs, divisions, and headers, just as you use
ALIGN=center to create centered paragraphs and such. This will right align your text (ragged left).
Perhaps what you really want is justified text, in which the left and right edges are both aligned so
that all lines are the same length. (This is sometimes incorrectly called "right justify".) There's no
way to justify text in HTML 3.2, but it can be done in a CSS1 style sheet with "text-align: justify".
(Before you do that, a caveat: though justified text may look pretty, human factors analysis shows
that ragged right is actually easier to read and understand.)
For images, you can use <IMG ALIGN=right SRC="..." ALT="..."> before the running text. The
image will float at the right margin, and the running text will flow around it. Remember to use <BR
CLEAR=right> or <BR CLEAR=all> to mark the end of the text that is to be affected in this way.

i
d

6.7. How can I specify fonts in my Web pages?

If you want others to view your web page with a specific font, the most appropriate way is to
suggest the font rendering with a style sheet. See: http://www.htmlhelp.com/reference/css/font/fontfamily.html
The FONT element can also be used to suggest a specific font. Use of the FONT element brings
numerous
usability
and
accessibility
problems,
see:
http://www.mcsr.olemiss.edu/%7Emudws/font.html
More
information
about
the
FONT
element
can
be
found
at:
http://www.htmlhelp.com/reference/html40/special/font.html
Either way, authors run the risk that a reader's system has a font by the same name but which is
significantly different. (e.g., "Chicago" can be a nice text font, or a display font with letters formed
by "bullet holes", or a dingbat font with building images for creating skylines).
Also, authors are limited to choosing a font (or a group of similar fonts) that are commonly
available on many systems. If a reader does not have the font installed on their system, they will see
a default font. Some browsers may use a less legible substitute font than their normal default font in
cases where "the specified font wasn't found".

r
a

6.8. How do I indent the first line in my paragraphs?


Use a style sheet with the following ruleset:
P { text-indent: 5% }

See <URL:HTML Help> for more information on style sheets.

6.9. How do I indent a lot of text?

Use a style sheet to set a left margin for the whole document or part of it:
/* Entire document */
BODY { margin-left: 20% }

/* Part of a document with CLASS="foo" */


.foo { margin-left: 15% }

See <URL:HTML Help> for more information on style sheets.

6.10. How do I do a page break?

Page breaks are offered in Cascading Style Sheets, Level 2, but they are not well supported by
browsers. See <URL:w3.org> for information on CSS2 page breaks.
In general, page breaks are not appropriate on the Web since what makes a nice page break for you
with your font and font size may be a poor page break for me with my font and font size.
If you need to produce a nicely formatted printed copy of your HTML documents, you might also
consider using special purpose tools rather than your browser's Print function. For example,
html2ps generates nicely formatted PostScript output from HTML documents, and HTML Scissor
uses special HTML comments for suggesting page breaks.

6.11. How do I have a fixed background image?


Use a style sheet with the following ruleset:

body { color: black; background: white url(foo.gif) fixed }

Note that while Internet Explorer 3+ respects the fixed property, Netscape does not.

6.12. How do I have a non-tiled background image?


Use a style sheet with the following ruleset:

body { color: black; background: white url(foo.gif) no-repeat }

7. HTML Forms

7.1. How do I use forms?

Information relating to the use of forms is available at <URL:jkorpela>.

7.2. Why won't my form email the user's data to me?


Forms that use ACTION="mailto:..." are unreliable. They may work for some of your users, but
they will fail for others who have different software configurations.
The only reliable solution is to use a CGI (or other server-side) program to process your forms and
mail the results to you. If you can run CGI programs on your server, see the list of prewritten scripts

3DJH 57

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

at <URL:CGI Resources>. If you can't run CGI programs on your own server, see the list of
remotely hosted form-to-email services at <URL:CGI Resources>.

7.3. How do I make a form so it can be submitted by hitting ENTER?


The short answer is that the form should just have one <INPUT TYPE=TEXT> and no TEXTAREA,
though it can have other form elements like checkboxes and radio buttons. For a more detailed
answer, see <URL:flavell>.

7.4. How can I make a form with custom buttons?


Rather than a normal submit button (<INPUT TYPE=submit ...>), you can use an image of a
custom submit button. Use <INPUT NAME=foo TYPE=image SRC="http://url.to/image.gif">.
There is no way to do this for the reset button.
Most browsers will also send the x and y coordinates of the location where the user clicked on the
image to the server. They are available as "foo.x=000&foo.y=000" in the CGI input.

i
d

7.5. Can I have two or more Submit buttons in the same form?

Sure. This is part of HTML 2.0 Forms support (some early browsers did not support it, but browser
coverage is now excellent).
You will need to give your Submit buttons a Name attribute, and, optionally, a Value attribute. In
order to determine which button was used, you will want to use distinctive Names, or Values, or
both. Browsers will display the Value, in addition to sending it to the server, so choose something
that's meaningful to the user.
Example:
-or<INPUT
TYPE=SUBMIT
NAME=join
VALUE="I
want
to
join
now">

r
a

<INPUT TYPE=SUBMIT NAME=info VALUE="Please send full details">

If you're unsure what results you're going to get when you submit your form, NCSA has a standard
script which you can use. Code this, for example (assuming method "post"):
<form method="post" action="http://hoohoo.ncsa.uiuc.edu/htbin-post/post-query">

and then go through the motions of submitting your form. The NCSA server decodes the form
input, and displays the result to you.

7.6. How can I allow file uploads to my web site?

First of all, the RFC for this is located at <URL:ics>.


File upload is handled by the CGI.pm Perl5 library available from <URL:cshl>.
These things are necessary for Web-based uploads:
An HTTP server that accepts uploads.
Access to the /cgi-bin/ to put the receiving script.
A form implemented something like this:
<form
File
Notes
<input
</form>

method="POST"
enctype="multipart/form-data"
to
upload:
<input
type=file
about
the
file:
<input
type=text
type=submit
value=Press>
to
upload

action="fup.cgi">
name=upfile><br>
name=note><br>
the
file!

Not all browsers support form-based file upload, so try to give alternatives where possible.

8. HTML Frames

8.1. How do I update two frames at once?

There are two basic techniques for updating multiple frames with a single link: The HTML-based
technique links to a new frameset document that specifies the new combination of frames. The
JavaScript-based solution uses the onClick attribute of the link to update the additional frame (or
frames).
The HTML-based technique can link to a new frameset document with TARGET="_top" (replacing
the entire frameset), but there is an alternative if the frames to be updated are part of a nested
frameset. In the initial frameset document, use a secondary frameset document to define the nested
frameset. For example:
<FRAMESET COLS="*,3*">
<FRAME SRC="contents.html" NAME="Contents">
<FRAME SRC="frameset2.html" NAME="Display">
</FRAMESET>
A link can now use TARGET="Display" to replace simultaneously all the frames defined by
frameset2.html.
The JavaScript-based solution uses the onClick attribute of the link to perform the secondary

update. For example:

<A HREF="URL1" TARGET=Frame1


onClick="top.Frame2.location='URL2';">Update frames</A>
The link will update Frame1 with URL1 normally. If the reader's browser supports JavaScript (and
has it enabled), then Frame2 will also be updated (with URL2).

3DJH 58

8.2. How do I get out of a frameset?

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

If you are the author, this is easy. You only have to add the TARGET attribute to the link that takes
readers to the intended 'outside' document. Give it the value of _top.
It is in current implementations not possible to display a frame in the full browser window, at least
not very easily. You would have to read source to determine the URL of the current frame, and then
request that URL manually.
I would recommend that authors who want to offer readers this option add a link to the document
itself in the document, with the TARGET attribute set to _top so the document displays in the full
window if the link is followed.

i
d

8.3. Is there a way to prevent getting framed?

"Getting framed" refers to the technique of using an existing frameset to display someone else's
document against his wishes into the current display. This can happen quite easily if one of the
documents in the frames uses a link that does not use the TARGET attribute, as the destination of that
link will be displayed in the current frame.
To avoid "framing" other people's documents, you must add TARGET="_top" to all links that lead to
documents outside your intended scope.
Unfortunately, there is no way to specify that a particular document should be displayed in the full
browser window, rather than in the current frame. The only workaround is to configure the server to
send out Window-Target: _top in its HTTP responses, but this is not something that all authors
can do.
The HTML specifications say that META can be used to mimic HTTP responses in HTML.
However, inserting <META HTTP-EQUIV="Window-target" CONTENT="_top"> in the document
does not work as expected.
Another attempt is to use <BASE TARGET="_top"> in the document, but this only specifies the
default target frame for links in the current document, not for the document itself.
If the reader's browser has JavaScript enabled, the following script will automatically remove any
existing framesets:

r
a

<SCRIPT TYPE="text/javascript">
<!-if (top.frames.length!=0)
top.location=self.document.location;
// -->
</SCRIPT>

An alternative is

<SCRIPT TYPE="text/javascript">
<!-function breakOut() {
if (self != top)
window.open("my URL","_top","");
}
// -->
</SCRIPT>
</HEAD>
<BODY onLoad="breakOut()">

8.4. How do I specify a specific combination of frames instead of the default document?
This is unfortunately not possible. When you navigate through a site using frames, the URL will not
change as the documents in the individual frames change. This means that there is no way to
indicate the combination of documents that make up the current view.
The author can provide and link to multiple frameset documents, one for each combination of frame
content. These frameset documents can be generated automatically, possibly even being created on
the fly by a CGI program.

8.5. Why do my links open new windows instead of updating an existing window?
If you use a name that does not point to a currently available frame, then a new browser window
will be opened, and this window will be assigned the name you used.
In HTML 4.0, the TARGET attribute value is case-insensitive, so that abc and ABC both refer to the
same frame/window, and _top and _TOP both have the same meaning. However, most browsers
treat the TARGET attribute value as case-sensitive and do not recognize ABC as being the same as
abc, or _TOP as having the special meaning of _top.

8.6. How do I remove the border around frames?


Removing the border around frames involves both not drawing the frame borders and eliminating
the space between the frames. The two major frames-capable browsers use different proprietary
attributes to achieve this.

3DJH 59

:HE 7HFKQ
7HFKQRRORJ\ 0D WHULD
WHULDOOV

Netscape 3.0 only recognizes the BORDER attribute on FRAMESET. [What about later versions of
Netscape? What do they do?] It can be set to 0, in which case the border will not be shown, and the
spacing will be set to zero.
Microsoft Internet Explorer recognizes the FRAMEBORDER and FRAMESPACING attributes on
FRAMESET, but in some versions also on FRAME for individual frames. Both attributes must be set to
0.
So, the most widely supported way to display borderless frames is <FRAMESET ... BORDER=0
FRAMEBORDER=0 FRAMESPACING=0>.
Note that these attributes are proprietary and not part of the HTML 4.0 specification. Also,
removing the border around a frame makes it impossible to resize it, as this border is also used in
most GUIs to change the size of the window.

i
d

8.7. How do I change the title of a framed document?

The title displayed is the title of the frameset document - the HTML document containing the
<FRAMESET> and <FRAME> elements - rather than the titles of any of the pages within frames. To
change the title displayed, link to a new frameset document using TARGET="_top" (replacing the
entire frameset).

8.8. How do I make sure my framed documents are displayed inside their frameset?

When the sub-documents of a frameset state are accessed directly, they appear without the context
of the surrounding frameset.
If the reader's browser has JavaScript support enabled, the following script will restore the
frameset:

r
a

<SCRIPT TYPE="text/javascript">
<!-if (parent.location.href == self.location.href) {
if (window.location.replace)
window.location.replace('frameset.html');
else
// causes problems with back button, but works
window.location.href = 'frameset.html';
}
// -->
</SCRIPT>

A more universal approach is a "restore frames" link:

<A HREF="frameset.html" TARGET="_top">Restore Frames</A>

Note that in either case, you must have a separate frameset document for every content document.
If you link to the default frameset document, then your reader will get the default content
document, rather than the content document he/she was trying to access. These frameset documents
should be generated automatically, to avoid the tedium and inaccuracy of creating them by hand.
Note that you can work around the problem with bookmarking frames by linking to these separate
frameset documents using TARGET="_top", rather than linking to the individual content documents.

8.9. Are there any problems with using frames?

The fundamental problem with the design of frames is that framesets create states in the browser
that are not addressable. Once any of the frames within a frameset changes from its default content,
there is no longer a way to address the current state of the frameset. It is difficult to bookmark - and
impossible to link or index - such a frameset state. It is impossible to reference such a frameset state
in other media. When the sub-documents of such a frameset state are accessed directly, they appear
without the context of the surrounding frameset. Basic browser functions (e.g., printing, moving
forwards/backwards in the browser's history) behave differently with framesets.
Furthermore, frames focus on layout rather than on information structure, and many authors of
framed sites neglect to provide useful alternative content in the <NOFRAMES> element. Both of these
factors cause accessibility problems for browsers that differ significantly from the author's
expectations and for search engines.
For further discussion, see <URL:HTML Help>

8.10. Why aren't my frames the exact size I specified?


Netscape Navigator seems to round pixel-based frame dimensions to the nearest whole percentage,
and to use those percentage-based dimensions when laying out the frames. Thus, frames with pixelbased dimensions will be rendered with a slightly different size than that specified in the frameset
document. There is no way to prevent this behavior.
To accomodate this, you should design your site to accomodate variations in the browser's
presentation. This is a good idea in general, but especially so in this situation.

You might also like