You are on page 1of 182

Choosing a layout method is often very personal.

One person might prefer absolute positioning while


another only uses floats with relative sized blocks.
- Mr. Nishant Rai
Syllabus
Course Contents:

Module I

Introduction to html programming

History of HTML, Structure of HTML, Adding Comments, Formatting Text,


Creating List, Creating Definition List, Creating Hyper Text Links, Creating Link
Lists, Inserting Inline Images, Creating Image Links, Horizontal Rules, Address
Tag, Working with Text

Changing font Sizes and Colors, Using Background Image, Marquee Tag.

Module II

Tables and frames, Creating Tables, Table Element, Adding Border, Adding
Column Headings, Adding Spacing and Padding, Adding a Caption, Setting the
table Width and Height, Add Row Headings, Aligning Cell contents, Setting
Column Width, Centering a Table, Inserting and Image, Spannig Columns,
Spanning Rows Assigning Backgroung Colors, Frame Elements, Creation of
Frame Based Pages, Noframes Element.

Module III

Forms and Java Script Introduction to Forms, Form Elements, Front level
validations using JavaScript

Module IV

Cascading style sheets, Overview of style sheets, Different ways to use style
sheets, Selectors DIV and SPAN Elements, Adding style to a Document, Use id
Classes and Ids, Style Sheet Properties.

Module V: XML

Introduction to XML, XML Basics, XML Structure, Developing a DTD from XML
code, Viewing XML, Viewing XML using the XML Data Source Object, Viewing
XML using Style Sheets.

Text & References:


Text:

HTML, DHTML, JavaScript, Perl, CGI, Ivan Bayross, BPB Publication.

References:

HTML Complete Reference, BPB Publication.

Internet for everyone, Alexis Leon and Mathew Leon, Leon Tech world.
Module I
Introduction to HTML
Basic Web Design
This hands-on workshop introduces you to the basic principles of Web site design and
authoring using HTML. You will then use FrontPage to create your web page or site and
publish it to the World Wide Web for viewing.

Objectives
Understand and apply design principles when creating and modifying a Web site.
Recognize HTML and Web terminology such as hypertext, tags, browser, and
HTML.
Identify the basic structure of an HTML document and create a simple Web page
using HTML.
Create a new Web site or modify an existing website using FrontPage.
Use tables to design the layout of a Web page.
Understand how typography works on the Web and format fonts and paragraphs..
Set Web page properties such as background colors and images.
Understand graphic formats for Web pages; insert graphics, modify picture
properties

Developing a Web Site


The Five Golden Rules
As with any other project, the first phase in creating a new
web site is planning. This involves determining the site’s
Create a clear visual
navigation structure, content, and page layout. It is only
hierarchy on each
after this has been accomplished that HTML coding or
page.
authoring tools like FrontPage can be used effectively to
actually create the site. Take advantage of
conventions.
The planning process involves: Break pages into
Define site purpose clearly defined
o What are the web site’s objectives? areas.
o Who is the target audience? Make it obvious
o What is their connectivity (dial up, what’s clickable.
broadband, network, etc.)? Minimize noise.
o What computers (PC/Mac) and browsers
(IE, Netscape, Opera, etc.) do they use? Source:
Don’t Make Me Think, Steve
Define content Krug
o What you have and what you need.
o How it will be organized. Categorize
information rather than defining categories
and filling them. Build the site structure around content organization.
o What graphics are required and how many? Remember, the larger the
number of graphics, the longer the page will take to download.
Develop a file naming convention and stick to it.

Web files and folders should not have any spaces and be in lowercase.
Use the underscore (_) to connect words in file names.
File names cannot contain colons (:), asterisks (*), questions marks
(?), or other special characters.

Avoid spaces in file or folder names. If necessary use an underscore between


words.
Determine site architecture and navigation. A simple flowchart-style sketch
usually works best. Hierarchical models are best suited to the web.

Use sticky notes to organize your navigation structure. Use one sticky
note per page and arrange them on a wall or table till you achieve
your desired hierarchy. Index cards can be used in a similar manner.

Sketch page layouts and content layouts to create appropriate page design.
Assess sketches for appropriateness, placement, consistency and usability, and
revise if necessary.

Designing Navigation Bars


The main goal of your website should be to make it easy for users to perform useful
tasks. Develop a clear information architecture that is simple, consistent, and follows
convention.

Key Elements of Navigation

Site ID.
Global navigation bar.
―You are here‖ indicator.
Local navigation bar.
Breadcrumb trail
Small text version of navigation bars (optional)
Source: Don’t Make Me Think, Steve Krug
Site ID Global Navigation

Breadcrumb Trail
“You are here” indicator

Local Navigation

You will know you have succeeded if your site navigation helps users answer these basic
questions:
Where am I? (Site ID)
Where page am I on? (Indicator)
Where can I go? (Navigation)

Page Design
With web pages, the layout design process accounts for the arrangement of text and
graphics elements on the page. These elements can be broadly divided into:
Page Header: Located at the top of the page, it includes the page banner or title
and the navigation bars.
Page Footer: Located at the bottom of the page, this is where you insert copyright
and authoring information, the date of the most recent update, institutional
affiliation.
Side Navigation: This is usually a rail along the side of the page that displays the
global or local navigation.
It is usually a good policy to sketch out the page layout and identify the position of
each element on that page as demonstrated in the diagram below.

Page
Header

Navigation
Panel

Page
Footer

Home Page Layout

Has to convey site identity and mission: what it is and what it’s
for.
Has to provide an overview of what the site has to offer, and how
it’s organized.
Should provide a way to search the site.
Has to appeal to diverse interests.
Source: Don’t Make Me Think, Steve Krug

Design Concepts
When designing a web site, you need to consider four basic design elements:
Appropriateness
o Does it match with the site’s target audience?
o Do the graphics mesh with the site’s intended purpose?
o Do the tone and style of the language complement the site’s objectives?
Placement
o Place the most important information at the top of the page.
o Use white space to create breaks between page elements.
Consistency
o Place page elements like titles, banners, logos, and navigation elements in
the same spot on every page.
o Consistent visual cues provide the user with a reference point, making it
easier for them to navigate the site.
Usability
o Make the site self-explanatory. Don’t make your users think!
o Make your ―clickables‖ obvious.
o Follow conventions.
o Keep your text brief and to the point. The less there is to scan, the easier it
will be for your users to find their information.
o Design for the lowest common denominator of 800x600 pixels in screen
resolution.
o Screen-size page banners and navigation bars should not exceed 760
pixels in width, and 410 pixels in height.



Introduction to HTML
What is HTML?
An acronym for Hypertext Markup Language, HTML is the language used to create web
documents. Contrary to popular notion, HTML is not a programming language. It is
simply a set of codes that define the layout and content of a web page so that they can be
read and displayed by a web browser. A non-proprietary language, HTML can be created
by a simple text editor as well as a sophisticated web authoring tool like FrontPage.
The World Wide Web Consortium, also know as the W3C, monitors the development of
HTML. As new features are added and obsolete ones deprecated (removed), it is assigned
version numbers. The most recent version is HTML 4.01.

HTML Documents
HTML documents are made up of tags or angled brackets (<>) that contain an element
within them to determine the layout and formatting of the web page. For example, <B> is
the tag used to define text in bold where ―B‖ is the element contained within the tag.
Elements can also include attributes, or additional information for that element.
Attributes are included inside the start tag. For example, you can specify the alignment of
images (top, middle, or bottom) by including the appropriate attribute with the image
source HTML code.

Structure
The basic HTML document is contained within the <HTML> </HTML> tags and
comprises two sections: Head and Body.
The Head contains the page title and meta-tags within the <HEAD> </HEAD> tags. Any
JavaScript code that is used, as well as Cascading Style Sheet information is also
contained within the Head. This section will not be displayed on the web page.
The Body holds the actual content of the page (text, graphics, lists, etc.) contained within
the <BODY> </BODY> tags. The <HTML>, <HEAD>, <TITLE>, and <BODY> tags
are also referred to as document tags.
A basic HTML document would look something like this:
<HTML>
<HEAD>
<TITLE>A Simple HTML Example</TITLE>
</HEAD>
<BODY>
Welcome to the world of HTML. This is the first paragraph.
</BODY>
</HTML>

Tags are case insensitive, i.e. <B> will work as well as <b>.
Not all tags work with all web browsers. If a browser does not
recognize a tag, it simply ignores it. It will display the
information contained within the tags however.

Creating an HTML Document


Since HTML documents are essentially text files with the extension .htm or.html, any
basic text editor like Notepad WordPad can be used to create one. You can also the
HTML view in authoring systems like FrontPage or Dreamweaver, or HTML hand
coding applications like Home Site.
HTML documents do not recognize white spaces created by formatting tools such as
spaces, linefeeds, and carriage returns. These are automatically compressed into a single
space when the page is displayed in the browser. For instance, the HTML code in the
example above can also be written out as
<HTML>
<HEAD><TITLE>A Simple HTML Example</TITLE></HEAD>
<BODY>Welcome to the world of HTML. This is the first
paragraph.</BODY>
</HTML>
and it would still display in exactly the same manner in the browser. However, it is harder
to read and edit in this format. Consequently, for clarity in reading and editing HTML, it
is best to structure the document using carriage returns and indents.

Markup Tags
The information contained in the Body section of an HTML document is formatted using
markup tags. These tags allow us to create paragraphs, line breaks, headings, lists, etc.
They can also be used to set the position of the content using alignment attributes. The
most common markup tags are:
Heading
These tags are used to highlight text by making them bigger and bolder than normal text.
There are six levels of headings numbered 1 through 6, where 1 is the biggest and 6 is the
smallest heading. Headings are specified as <Hy> </Hy> where H stands for heading and
y is the level number (1 to 6).
E.g.:
<HTML>
<HEAD>
<TITLE> Headings</TITLE
</HEAD>
<BODY>
<H1>Level 1 heading</H1>
<H2>Level 2 heading</H2>
</BODY>

</HTML>

Paragraph
These tags, denoted by <P> </P>, are used to define paragraphs. Since HTML does not
recognize carriage returns, it is especially important to use these tags to indicate
paragraphs, or you will end up with as one long block of text.
E.g.:
<HTML>
<HEAD>
<TITLE> Working with Paragraphs </TITLE
</HEAD>
<BODY>
<P>This is the opening paragraph for this page. It does not have much information at
the moment, but it indicates how a paragraph is constructed in HTML.
</P>
<P>This is the second paragraph on this page.
</P>
</BODY>
</HTML>

Paragraphs can be positioned or aligned relative to the sides of the page by using the
ALIGN=―alignment‖ attribute within the opening tag where the value for alignment is
left, right, center, or justified. The default alignment for a paragraph tag is left.
E.g.
<HTML>
<HEAD>
<TITLE> Working with Paragraphs </TITLE
</HEAD>
<BODY>
<P align = ―center‖>This is the opening paragraph for this page. I have used the
attribute align with the value center to put it in the middle of the page.
</P>
<P align = ―right‖>This is the second paragraph on this page and it is right aligned.
</P>
</BODY>
</HTML>

Line Break
The line break tag <BR> is used to simulate the effect of creating a line break by pressing
the Enter key on the keyboard. It is one of the few HTML tags that is not paired with a
closing tag.
E.g.
<HTML>
<HEAD><TITLE> Page with Line Breaks </TITLE
</HEAD>
<BODY>
Trinity University<BR>
One Trinity Place<BR>
San Antonio, TX 78212<BR>
USA
</BODY>
</HTML>

Comments
Comments are one of the most useful tools in HTML as they can be used to explain and
clarify the structure of the HTML code to other readers. They can also be used to include
information such as the name of the person editing a file or the software and version used
in creating a file. Comments do not appear on the web page. To include a comment in
your HTML file, enter:
<!-- Your comment goes here -->

Introduction to FrontPage
What is FrontPage?
FrontPage is an application used to create web pages. As an authoring tool, FrontPage
includes tools that allow you to design, create, manage, and publish web pages without
needing prior knowledge of HTML. However, a basic grounding in HTML allows you to
tweak and optimize the HTML code that FrontPage generates.
Creating a New Web Page
To launch FrontPage 2002, click on the shortcut on your desktop
(see image on the right). If no icon is available on the desktop, click
on the Start button in the lower left corner of the screen, then
Programs, and then on Microsoft FrontPage.
Unlike previous versions of FrontPage where a new page
automatically appeared on launching the application, when you first launch FrontPage
2002, it displays an empty screen (grey area). To create your first web page click File 
New  Page or Web or on the Create a new normal page icon.
Your screen should now look like this.

Source: Microsoft Office XP Inside Out


The Views bar, on the left of the screen, allows you to view your web
page or site, in many different ways. Notice that the topmost button
titled Page seems to be ―depressed.‖ This indicates that you are in the
Editor view. This view is primarily used when creating and editing a
web page or site.
Folders, shows you your web site in ―file‖ form. You can’t see
anything at the moment because we haven’t created a web site.
Reports will show you the status of all the pages in your web site as
you create them.
Navigation will show you, as you create your web site pages, a little
organization chart. The lines connecting the boxes (as shown in the
Navigation icon button), indicate the hyperlinks between the pages.
Tasks is a little word processor that lets you maintain a ―To Do” list
once you begin creating your web site.
Click back on the Page view to begin building your web page.

Page Views
FrontPage allows you to work on your page in three views:
Normal View or the WYSIWYG (What You See Is
What You Get) editor. This is the most commonly
used view.
HTML View, which displays the HTML code generated for the page. This is
useful if you want to modify or tweak the HTML code.
Preview Page View displays the page as it would appear on a web browser. You
cannot make any modifications in this view.

To select a specific view, click on the appropriate tab in the lower left hand corner of the
Page View window.

Use the Reveal Tags (Ctrl+/) option under View in the Menu Bar to
display HTML tags in the Normal View. These tags are for
information only and cannot be edited or changed in this view.
Page Properties
The page properties option allows you to change the default look (white) of your
webpage by adding a background images or color, page titles, and even sound and
animation.

To view the Page Properties screen, select


Format  Background in the Menu Bar.
You can also right-click on the page and select
Page Properties in the pop-up menu.

You should now see the Page Properties screen shown below.. As you can see, you can
set a number of page options here. For this class, we will only work with title, and
background color and image.

General
In the title box, type in a new
page title, appropriate to your
page. It is not a good idea to
have background sounds on
your web page as it slows the
download.

Background
Click on the Background tab
to change screen options. To
add a background image, click
on the Browse button and
navigate to the location of the
desired image.

To change the default


background and text colors,
click on the little arrow to drop
down the menu.
You can also change hyperlink colors in the same manner. However, it is advisable to
stay with the convention i.e.:
Blue for a page that has not been visited yet.
Purple for a page that has been viewed.
Red is the color of the link as it is being pressed.

Light colored backgrounds with dark text work well together.


A dark background can add drama, but needs a bright text color for
contrast..
Bright colors are eye-catching, but can tire a reader. Use them sparingly.
Use background images that have subtle patterns and textures. A busy
background image makes it harder for the user to read the content.

Working with Text


To place content in a new page simply start typing in the information onto the page, like
you would in a word processor. Check that you are in the Page View (the Page button in
the View bar will have a square around it) and that your cursor is flashing on the left
hand side of the white area.
At the upper left corner, above the white area, you should
see the indicator new_page_1.htm. If you don’t, click on
the Page button again.
Type in a heading for your page (E.g. My First Web Page) and then press the Enter key.
Every time you press the Enter key, FrontPage automatically generates a paragraph tag
(<P> </P>) with a blank line after it.
To insert a line break (<BR>) instead of a paragraph break, use the Shift-Enter
combination.

When modifying a web page, it is best to view the formatting marks.


Use the Show All button - - to display formatting marks.

Formatting Text
You can format text to be in different fonts, sizes, styles, and colors using the lists and
buttons on the toolbar or the Format  Font option in the Menu Bar.

Font List
Size List
Font Type
It is best to select a simple, san-serif font that is easily available on most computers to
avoid variations in how the page is displayed. Choose fonts such as Arial, Verdana, or
Helvetica that are easy to read and available on most computers.

Avoid leaving the font setting at Normal or Default. This will


display the page in whatever font the user has set as default.

Font Style
This usually refers to setting text as bold, italics, headers, lists, etc.. An easy method to
convert text to bold or italics is to select the text and then click on the Bold ( ) or
Italics ( ) button.

Don’t use the underline style as it will look like a hyperlink and
confuse the reader.

To set text as a header or list, select the appropriate option


from the Style menu on the Tool Bar. Header sizes range
from 1 to 6, with 1 as the largest and 6 as the smallest.

Font Size
In web documents, font sizes have different values from the point sizes used in word
processors. The latter are indicated in parentheses next to the HTML sizes for a sense of
proportion. A point size of 2 or 3 works the best for paragraph text. Select the desired
size from the list or the Font dialog box.

The Font dialog box offer allows you to set text effects such as
superscripts, subscripts, strikethrough, etc. Not all of them are
supported by browsers, and some, like Blink, can also be annoying.
Avoid using them.

Font Color
You can select font color along with other options in the
Font dialog box. You can also use the Font Color button
on the Tool Bar.
Formatting Paragraphs
Paragraphs are aligned or positioned relative to the sides of the web page as Left, Right,
Centered, or Justified. You can align a paragraph with any of the following methods:
Right-click in the paragraph and select the Paragraph command from the menu.
Select Format  Paragraph
Use the Align Left ( ), Align Right ( ), Center ( ), or Justify ( ) buttons
on the Tool Bar.
The first two methods will open a dialog box where you can set the alignment as well
other options such as text indents and line spacing.

Inserting a Picture
Graphics for web documents should be in one of the following formats:
GIF (Graphic Interchange Format): Limited to 256 colors, therefore, best suited for
logos and clip art (non-photo images)
JPEG (Joint Photographic Experts Group): This format supports millions of colors
and is ideal for photographs. Save scanned photos in this format.

To insert your picture, click on Insert


 Picture in the Menu Bar. Select
From File or Clip Art to specify the
file location.
When the Picture menu screen appears,
navigate to the location of the desired
image, select it, and then click Insert to
place it on the page.

In order for the page to load correctly, all the ―parts‖ of the web page
(graphics, animations, video files, photos, sounds, etc.) have to be located
in the ―same place‖. If the web ―page‖ can’t find items, you will not be
able to see them in your page.
Make sure you put your image files in the same location as your web
page.

Modifying Picture Properties


Once you have inserted the image, you can change its size and positioning on the screen.
To resize an image, click on it once to select and display the sizing handles (small
―squares‖ at each of the corners and in the middle of the top, bottom, and side edges).
Use these handles to change image proportions.

Dragging on a corner handle sizes the graphic proportionately.


Dragging the middle handle will distort the image.

For precise sizing as well as to set other options, right-click on the image and select
Picture Properties from the menu to display the Picture Properties dialog box.

Change the Alignment of the


image depending on how you
want it positioned on the page.

To add a border, enter a value


(in pixels) in the Border
Thickness box. The higher your
value, the thicker your border
will be. The default value is 0 or
No Border.

Use the Horizontal spacing and


Vertical spacing options to add
white space around the picture,
both above and below (vertical)
or on both sides (horizontal).
This prevents text from running
into the image.

Cropping Graphics
You can also resize an image by cropping it so that you only retain the details you want.
Basic cropping can be done in FrontPage itself as follows:
Select View  Toolbars  Pictures to bring up the Pictures toolbar.

Click on the Crop button ( ) to display the cropping box on the graphic.
Drag the cropping box handles to size the box and click on the Crop button again
to crop the graphic.

It is highly recommended that you use an image editing application like


Adobe Photoshop to resize and crop images, and then insert the modified
images into your web page.
Hyperlinks
A web page’s power lies in its ability to link text and/or an image to another document or
section of a document. Text hyperlinks are underlined and highlighted in blue to make it
easy for the reader to pick them out while scanning the page.
Select the text or graphic that will function as the hyperlink, then select Insert 
Hyperlink from the Menu Bar or use the shortcut Ctrl+K. You can also click on the
Hyperlink button on the Tool Bar.

In the Insert Hyperlink dialog box, click on the Hyperlink button at the top of the
dialog box.

Hyperlink
button

A Text Help will appear indicating that this button will ―Browse to the web.‖ You will
then be taken to the default page in your browser. In the Address Area, type in the
address of the web page or site you would like to link to and tap the Enter key to go to
that page. When you see the web site, click on the Front Page button at the bottom of
your screen in the task bar.
This will take you back to FrontPage 2002 and the Insert Hyperlink dialog box.

Click on the Browsed Pages button and select your site from the list of choices that
appears. The Address area at the bottom of the menu screen will also indicate the web
address to which you browsed. Click on OK to complete placing the hyperlink.

Web address

Bookmark Links
Bookmark links are used to link to a section within the same document. It is particularly
useful with long documents that would require the user to scroll up and down. There are
two steps to adding a bookmark link:
Create the bookmark.
Create a link to the bookmark.

To create a bookmark, position the cursor by the first word of


the section you want to bookmark and select Insert 
Bookmark from the Menu Bar. Give the bookmark a
suitably descriptive name and select OK. In the Normal Page
View, a bookmark will show with a dashed underline.

To create the hyperlink to the bookmark, select the text to be hyperlinked, then select
Insert  Hyperlink from the Menu Bar or use the shortcut Ctrl+K. You can also click
on the Hyperlink button on the Tool Bar.
This will open up the Insert Hyperlink dialog box. Click on the
Bookmark… button and select the appropriate bookmark. The
hyperlinked text will now appear as blue underlined on the page.
To test your link, hold down the Ctrl key and click on the link.

Email Links
Email links are used so that users can email webmasters or other contact individuals their
comments and feedback. To create an email link, select Insert  Hyperlink from the
Menu Bar or use the shortcut Ctrl+K. You can also click on the Hyperlink button on
the Tool Bar. In the Insert Hyperlink dialog box, click on Email Address and fill out
the email address.

Saving Your Web Page


It’s wise to save your web page periodically so that you don’t lose your work. You can
save your file by selecting the Save option from the File menu (File  Save), or by
clicking the Save button.
When you save a web page for the first time, the Save As dialog box will appear. The
Save In box displays the location name. Click on the arrow on the right hand corner of
the box to display more locations. When the Save In box displays the desired location,
type in the file name in the File name box and click the Save button. FrontPage will
automatically add the extension .htm to the file name.

More locations
Location name

File name

FrontPage will try to use your title for the name of the web page.
If it is more than 8 characters long, some older computer systems and
servers might not work well with the name.
Also, the name should not have an apostrophe (’) as this is a reserved
Java character and could cause later problems as well.
Tables
A table on a web document is essentially a grid of rows and columns. Each intersection
of a row and a column creates a cell. Tables make it easier to design page layouts because
they allow you to display information in a formatted tabular form.

Table properties for each web page should be determined and sketched out as early as
possible. Several small tables will load faster than one long table. Sometimes,
depending on the content, you may need to tables within tables. These are called nested
tables.

Creating a Table
To create a table on your page, place the cursor at the point you want the table to be and
select Table  Insert  Table from the Menu
Bar. This will display the Insert Table dialog box
shown below.

Use the Rows and Columns options to determine the


number of rows and columns in the table. (This is where having a sketch becomes
handy.)
Select OK once you have entered your options.
You can create a basic table using the Table button ( ) on the Tool
Bar. Click the button and drag the mouse over the grid, highlighting the
cells that should appear on the table. When the table size has been
selected, click the mouse button again.

Table Properties
Specify width sets the width of the table by a distinct number of pixels or by a
percentage of the screen width. Use the In pixels option, when you want the table to be a
certain width and avoid horizontal size changes.

Alignment refers to the table's position on the page as in centered, left, right, or justified.
The default is usually left alignment.

Cell padding is the number of pixels between the text and the cell walls.

Cell spacing is the number of pixels between each table cell.

Specify height is usually not necessary to set since the height depends on the number of
rows in the table.

Border size indicates the thickness of the border around each cell. Tables used for
content layout should have a border of 0 to hide the borders. Tables that are used to
display tabular information can have their borders set to higher values.
E.g.

Table with no border The same table with a border of 5 pixels

Border color defines the color used for the border. For example, the border color in the
table above is grey.

Background color adds a colored background to the table cells.


E.g.
Use background picture add a background image to the table.
E.g.

Working with Cells


To add content (text or graphic) to a cell, click in the cell to place the cursor there, then
type to enter text or insert the graphic.

Within a cell, the formatting options are the same as within the document. Therefore,
pressing the Enter key will create a paragraph break, while pressing Shift+Enter will
create a line break.

Pressing the Down Arrow (↓) key will move the cursor out of the table and to a new
paragraph below.

Cell Properties
To modify cells properties, first select the cells to be changed, then select Tables 
Properties  Cell from the Menu Bar. You can also right-click within a cell and select
Cell Properties from the menu. Either option will bring up the Cell Properties dialog
box.
Horizontal alignment defines the position of the content within the cell. The default
is the Left side of the table cell. You can change this to Centered, Right, or
Justified.

Vertical alignment refers to the position of the contents relative to the top and
bottom of the cell. The default is at the Middle.

Specify width and specify height defines the width and height of the cells. Percentages
refer to the portion of the table, not the entire screen.

The Header cell option will automatically bold and center the cell content.

Border color changes the color of the cell border as demonstrated below.

Background color changes the cell's background color.

Background image adds a graphic to the background of each cell.

Spanning Cells
Sometimes, you may need to create a cell that spans rows or columns; a cell that carries
the page banner or title for example. In such situations, you will need to span that cell
across columns or rows as the case may be. Using the table used in the above examples, it
would work like this:

Insert a new row at the top of the table.


Type the text of the row that will be spanned across the columns into the first cell.
Highlight
both cells in the top row and select Table  Merge Cells from the Menu Bar.
You can also right-click and select it from the popup menu.
Inserting Rows and Columns
To add rows or columns to a table, place a cursor in the cell that the new row or column
will be adjacent to. Then select Table  Insert  Rows or Columns from the Menu
Bar to open the Insert Rows or Columns dialog
box.

To insert a row, select Rows and enter the


Number of Rows.
Then select the Location of the new row by
selecting Above selection or Below
selection from where you placed the cursor
in step 1.
Click Columns to insert a new column and
the choices will change. Enter the Number
of columns and the Location left or right of
the selected point.
Click OK.

You can also insert a row or column right-clicking in the cell the new row or
column will be adjacent to. Select Insert Row or Insert Column from the
popup menu.


Creating a Website
In this section, you will learn to create a small web site using FrontPage. It is
recommended that you familiarize yourself with the basic concepts of web design, and
learn to use FrontPage to create and edit web pages prior to creating a web site.

In the chapter Introduction to FrontPage, you learnt to hyperlink to other web pages
and sites. When creating a web site, FrontPage automatically creates the links to the other
pages in your web site.

Launch FrontPage by clicking on the shortcut on your desktop (see


image on the right). If no icon is available on the desktop, click on
the Start button in the lower left corner of the screen, then
Programs, and then on Microsoft FrontPage. Take a few
moments to review what the screen should look like and re-familiarize yourself with the
various buttons on the top and left side of the screen.

If you still have your single web page on the screen, select File  Close in the
Menu Bar. If you are prompted to save your changes, select Yes.
To create a new web site, select File  New  Page or Web in the Menu Bar. This
will bring up a ―Task Pane‖ on the
right hand side of your screen.

The Task Pane is Office 2002’s alternative to the dialog box. It is a Web-style
command area that you can dock along the right or left edge of your screen or
float anywhere on the screen.
Source: Microsoft Office SP Inside Out

Place your cursor over the small yellow folder


with an ―earth‖ on it or on the text Empty Web.

You will notice that the words Empty Web are


now underlined in blue. You will also notice that
your cursor will change to the ―small pointy
hand‖ hyperlink icon. Click on Empty Web to
display the Web Site Templates dialog box.

To create a space for your web site, you need to


do the following in the dialog box:

First (1) , make sure that the upper left icon One Page Web is highlighted. If
it is not, click on it.
Second (2), in the ―white area‖ under Options, specify the location of your
new web by typing in c:\webtest.

If your Web Site Templates dialog box should looks like the one on the following
page, click OK. This will take you back to the FrontPage 2002 main screen.

It may appear that nothing has happened. However, if you look at the upper left
corner of your screen you will see that the web site c:\webtest has been created (se
image below).

Since this is a web site, and the Views Bar on the left of the screen is set on Page,
you will have to select another button in the Views Bar to be able to see and work
with your web site.
1
.
2
.

To visually see/confirm that your web site has been


created by FrontPage, click on View in the Menu
Bar. In the drop-down menu, click on Folder List .

The Folder List will now appear on the left side of your screen to the right of the
Views Bar. The Folder List indicates that your new web site is located on the C: drive in
the Folder webtest. Notice also that two new folders have been created by FrontPage:
private and images. FrontPage has also created your initial home page called index.htm
To create our web site we’ll want to be in the Navigation View, so click on the
Navigation button on the View Bar. When this process is complete
you will see your initial Home Page of the web site in the center of
the screen.

Take a few minutes to look at all of the “stuff” on the screen. Take note of the words
below the Home Page (index.htm), they’re important.

Saving Your Web Site


If you haven’t already, you’ll notice that the Save option under File in the Menu Bar is
grayed out, as is the Save button in the Tool Bar. One of the neat things in FrontPage
2002 is that it automatically saves your web site as you make a change.

To see this, select File  Exit in the Menu Bar. FrontPage will close. Now open
FrontPage as you did at the beginning of this tutorial. Your new web site will shows up
just as you had left it. This is a new feature of FrontPage 2002.

Working on Your Web Site


To begin working on your web site pages, select File  Open and click on the small
triangle to the right of the Look in area. Navigate to your saved Web (webtest), select
index.htm (or the file you want to work on), and click on Open. Then switch to the
Navigation View so you can get started creating your web site

If your Folder List view area is still


visible, simply click on the small ―X‖
in the upper right corner of the
Folder List view area.

You will still have to save individual web page


changes as you work on them.
Creating Web Site Structure
You should be in Navigation View at this point.

First, click on the Home or Index Page in the middle of the screen. Prior to your click,
it will appear as a light yellow icon, when you click on it, it will turn blue. This indicates
to FrontPage which page you desire to work on. In this case you will add, and
automatically link, three additional pages below your main home page.

If you accidentally double-clicked on the Home/Index Page icon, FrontPage will


assume you want to edit the page and load it in the Editor. Simply click on the
Navigation button in the View Bar and you’ll be back where you want to be.

Again, make sure the Home Page icon is blue. To add the first page
under your home page, click on the New Page button (looks like a sheet
of paper) in the upper left corner of the screen. As soon as you click,
your screen will change to reflect that you have just created New Page 1 below your
Home Page (index.htm).

This is where FrontPage really does its work. When you add a new
page, FrontPage automatically hyperlinks it to the corresponding
page. Your screen should now look like the one at the right.

Add two more pages under your Home Page (index.htm). Each
time, click on the Home Page (index.htm) to turn it blue, and then
click on the New Page button. Your screen should now look like
the one below:.

Next, we’ll add two pages under New Page 3. The process is similar to what we just did.
First, click on New Page 3, to turn it blue, and then click on the New Page button. Do
this twice. Your web site should now look like the one below.
If you make a mistake as you are adding new pages, simply
click-on the erroneous new page and tap the Delete key.
Or right click on the page and select Delete from the popup
menu.

You can also click on the Undo button.

You now have the beginning of a small web site.

Before you can look at it however, you need to do a very important task. You need to
tell FrontPage what you want to see on your web pages in your web site. To do this,
select Format  Shared Borders in the Menu Bar. This will bring up the Shared
Borders dialog box.

Shared borders allow you to display content that is identical to all


pages without having to repeat the process for each page. If you add
or edit an element in a shared border in one page, it will affect the
content in all the pages that display that shared border.

Typically, a top shared border will contain a page banner and


navigation bar, the left another navigation bar, and the bottom,
information such as email, copyright notice, etc.

To make the titles and the links of each web page visible, select All Pages. Also check
the squares to the left of Top and Include navigation buttons, and Left, and Include
navigation buttons.

Your Shared Borders screen should look exactly like the one on the following page.
When it does, select OK.
To see what your site looks like at this point, double click on the Home Page
(index.htm) icon. You can also right-click on the Home Page (index.htm) icon and
select Open from the popup menu. This will load the Home Page in the Editor (Page
View).

Take a few moments to look at the top of the page in the Editor (Page View). It should
look like the view below.

Observe that the title to the Home Page (index.htm) appears at the top of the page in the
Editor (Page View) – just as it did when FrontPage created it.

Also, New Page 1, 2 and 3 on the left side of the page are links to the pages that you
created one level below the Home Page (index..htm).

As indicated earlier, you will return to the Navigation View and re-name these pages so
that they make more sense to your web site. Don’t worry about the dashed lines, these
are simply there to assist you later in the Page View. They will disappear when you view
your web site in a browser.

Viewing Your Website in a Browser


To see what the site would look like on the Web, in Page View, click
on the browser button in the Tool Bar. Or select File  Preview in
Browser from the Menu Bar.

When you choose Preview in Browser, FrontPage will ask you to


choose a browser available on your computer. Internet Explorer is
the default browser at Trinity University.

However, when possible, it is recommended that you view the site


in other browsers such as Netscape and AOL to ensure
compatibility.

Your initial view of your Home Page (index.htm) should look like the image below.

In the browser, your ―blank‖ website will respond like any other website. When you
move the cursor over the titles New Page 1, New Page 2, and New Page 3, you will
notice that the pointing hand appears, indicating a hyperlink.

Click on New Page 1, it should look like the image below.


The text buttons on the line below the title New Page 1 are hyperlinks back to the
Home Page and to pages 2 and 3. When you created your Shared Borders, you set it up
so that links to pages that are above or on the same level as the current page (New Page
1 in this example) show below the page title.

It does not matter if there are more than three pages above, or on the same level as the
current page, all the pages will show with their names. These are part of the automatic
hyperlinks that FrontPage creates.

Now click on New Page 3 in the browser. Your browser should now look like the image
below.

Pages
Below
New
Page 3 Pages Above and
at the Same Level
as New Page 3

Remember the two new pages you created below New Page 3? These now show up as
New Page 4 and New Page 5 on the left side of the page. The line below New Page 3
now contains the text links for pages above or on the same navigation level as New Page
3.

Creating Titles for Website Pages


To get an idea of how page titles are displayed in FrontPage, click on the Folders button
in the View Bar. You should now see the following screen:

The Name column on the left side of the screen displays the file names (index.htm,
new_page_1, etc.) for each page. The Title column displays the actual page names as
they appear on the Navigation View boxes (index.htm, New Page 1, etc.). When you
rename the page titles, the new titles will appear in the Title column.

To rename a file name (new_page_1.htm in this example), right-


click on the file name in the Folder View in the View Bar, select
Rename, and type in the desired file name.

Remember the file name conventions outlined earlier in this


book when renaming files.

Return to the Navigation View in the View Bar to give your pages new titles.

Click once on the Home Page (index.htm) box to turn it blue.


Then click on the title (index.htm) and wait a few moments till
the title is highlighted in blue. Your screen should look like the
image on the right.

In a Windows program this indicates that you can edit the text. You can start typing
immediately to replace index.htm, or you can delete the text and then type in the new
page title.

For now, type in First Name’s Home Page where First Name’s is
your first name, and tap the Enter key when you are finished. Select
View  Refresh on the Menu Bar to update your changes. You
will see the page title is now the one you entered.

Place the following titles for the other pages in your website in a similar manner. Once
you get the hang of this, you can change the titles to anything you desire, add more pages,
etc.
New Page 1: About Me
New Page 2: About My Family
New Page 3: My Hobbies
New Page 4: Type-in the name of a hobby
New Page 5: Type-in the name of another hobby

When you are done, select View 


Refresh on the Menu Bar to
update your changes

Now return to the Folder view by


clicking on the Folder button on the
View Bar. Your Title column,
should look similar to this one.
To see what your updated site looks like in the browser, first return to the Navigation
view by clicking on the Navigation button in the View Bar.

Double-click on your home page icon (ABC’s Home Page) or right-


click on the home page icon and select Open from the popup menu.
This will load the page in the Page View.

In Page View, click on the browser button in the Tool Bar, or select
File  Preview in Browser in the Menu Bar.

If nothing seems to happen, or it looks like your browser hasn’t


opened, look at the Task Bar at the bottom of your screen. Your browser button
should be flashing blue. If it is, click on it to bring up your web site.

Click around your web site. You will notice that FrontPage has automatically changed
all of your pages and buttons.

Themes
For a website to be effective, it needs to have consistent design. FrontPage allows you to
create this easily by using themes, or consistent formatting features that are applied to all
the elements of a page. Applying the same theme to all the pages gives the entire website

Themes affect the following web page characteristics:

Background color or image.


Text colors and fonts used with paragraph styles (Normal and Heading 1 to
Heading 6).
Text hyperlink colors.
Images used for bullets in bulleted lists.
Images used for horizontal rules.
Text color and font, and images used in page banners and navigation bars.
Table border colors.
Source: Microsoft Office XP Inside Out

a consistent look. (You can change them page by page later if you so desire).

If you are not there already, return to FrontPage by clicking on the FrontPage button in
the Task Bar at the bottom of the screen. It does not matter which view (Page,
Navigation, etc.) you are in when you return to FrontPage.
Select Format  Theme in the Menu Bar. This will take you to the Themes dialog
box.. When it first appears, you will notice that the
display area is blank. this is because at this point, you
have not yet selected a theme to view.

Select a theme from the choices in the left side of the


dialog box. When you do, your selection will be
highlighted in blue and the theme will appear in the
sample screen. Go through the choices to pick one you
like.

When you have decided on a theme, make sure you select one of the options under Apply
Theme to:.

If you select All pages, the theme will be applied to all the pages in your website.
If you choose Selected page(s), FrontPage will apply the theme to only those
pages.

Remember the consistency rule while making your choice! Click OK when you are
ready.
This will bring up the following message screen:

It indicates that all of your formatting will be changed to the theme you selected. Click
Yes.

To see if your theme has been applied to the website, click on the Navigation button in
the Views Bar. When you see your website organization chart, double-click on your
home page at the top of the chart. As before, this will take you to the Page view and
your home page. You will notice that the theme you chose has been applied to this
page.

You are now ready to save your website and view it in a web browser. To save your
pages, select File  Save All in the Menu Bar.

When you are in the Page view, you’ll need to save


your changes to each page just like you did when
creating a single web page.

You can save each page individually, or all of them at


the same time with the Save All option.

Don’t forget to save frequently as you are editing


your individual web pages.

You are now ready to view your updated website in the browser. Click on the Preview in
Browser button, or select File  Preview in Browser in the Menu Bar to open your
website in the browser. Browse around to see how everything works.

Once you have created a website, you can make changes to it


at any time by selecting File  Open Web in the Menu Bar.
Make sure that you are in the Folder or Navigation view in
the Views Bar when you do this.
Publishing Websites
For people to see it on the Web, you will need to publish your website. In other words,
you need to copy it to a specified location on a Web server.

Trinity’s web server is indicated by Web on TUCC-Web’ (W:):. You can access it by
clicking on the My Computer icon on the desktop, or by right-clicking the Start button
and selecting Explore from the popup menu.

As you can see, there are two parts to the Web server.
The trinity folder is used to allocate web space
to campus departments so they can publish
departmental websites.
The users folder is the personal web space allocated to faculty and staff to publish
non-departmental websites. This space is available on request.

To publish your website, select File  Publish Web from the Menu Bar. This will
display the Publish Destination dialog box as shown below.

In the Enter publish destination box, type the full URL (address) of the location you
want to publish to as indicated in the picture.
Don’t use the Browse button to navigate to the W: drive! You need to enter the
complete URL.

You will now be prompted to enter your username and password as shown below. When
typing in your username, make sure you use the following format: trinity\username.
Once you connect, you will see the Publish Web dialog box displayed on the following
page.

local remote
view view

The top part of the dialog box indicates the location you are publishing from and the one
you are publishing to. Use the Change button to change the publishing location if you
need to.

The middle area of the dialog box is divided into two parts:
The local view is on the left.
The remote view is on the right.

If you are publishing for the first time, simply click on the Publish button to copy your
files to the specified web location. If your website has subwebs (websites within
websites), make sure you have checked off on the Include subwebs option. In fact, it is a
good policy to check this off always before publishing.

If you are publishing a modified/edited website,


you can opt to publish only the changed pages by
clicking on the Options button in the Publish web
dialog box.
Once the “publish” is complete, you will see the following dialog box. Select Click here
to view your published web site to view your web site on the Web.

Congratulations! You have successfully created your first website.

HTML TAG LIST

BASIC TAGS
<html>...</html>
Creates the html document

<head>...</head>
Contains the head information, such as the title and meta tags which are not visible to the
user

<title>...</title>
Contains the title of the document which appears at the top of the browser window

BODY
<body>...</body>
Contains the viewed portion of the document

<body bgcolor="?">
Sets the color of the background in hexadecimal code

<body background="filename.xxx">
Sets an image as a page's background (wallpaper)

<body text="color">
Specifies the color of normal text in hexadecimal code

<body link="color">
Specifies the default color of unvisited links in hexadecimal code
<body alink="color">
Specifies the color of links on click in hexadecimal code

<body vlink="color">
Specifies the color of followed links in hexadecimal code

FORMATTING
<p>...</p>
Creates a new paragraph

<p align=?>
Aligns a paragraph to the left, right, or center

<br>
Inserts a line break

<blockquote>...</blockquote>
Indents text from both sides

LISTS
<dl>...</dl>
Creates a definition list

<dt>
Precedes each definition term

<dd>
Precedes each definition

<ol>...</ol>
Creates a numbered list

<li>...</li>
Precedes each list item, and adds a number

<ul>...</ul>
Creates a bulleted list

<div align=?>
A generic tag used to format large blocks of HTML, also used for stylesheets

TEXT ATTRIBUTES
<pre>...</pre>
Creates preformatted text
<hl>...</hl> to <h6>...</h6>
Creates headings – H1 largest, H6 smallest

<b>...</b>
Creates bold text

<i>...</i>
Creates italic text

<tt>...</tt>
Creates teletype, or typewriter-style text

<cite>...</cite>
Creates a citation, usually italic

<em>...</em>
Emphasizes a word (with italic or bold)

<strong>...</strong>
Emphasizes a word (with italic or bold)

<sub>...</sub>
Subscript - text is lower than baseline

<sup>...</sup>
Superscript - text is higher than basline

FONT ATTRIBUTES
<font>...</font>
Changes font attributes for text within the tags

<font size="value">...</font>
Sets the font to a size from 1 to 7, with 1 the smallest and 7 the largest

<font face="name">...</font>
Sets the font face

<font color="color">...</font>
Sets the font color using hexadecimal code or ―color‖ <font color=‖blue‖>

IMAGES
<img>
Embeds an image in the document at the location of the tag
IMAGE FORMULA
<IMG SRC=”filename.xxx”>
<img src="url" alt="text">
Adds an image with a text description

<img src="url" alt="text" align="direction">


Aligns an image to the left, right, center, bottom, or top

<img src="url" alt="text" border="number">


Sets the size of the border around an image

<img src="url" alt="text" height="pixels">


Sets the height of an image

<img src="url" alt="text" width="pixels">


Sets the width of an image

<img src="url" alt="text" hspace="pixels">


Sets a horizontal margin to be placed around an image

<img src="url" alt="text" vspace="pixels">


Sets a vertical margin to be placed around an image

<img src="url" alt="text" usemap="map-name">


Designates an image as a client-side image map

LINKS
URL FORMULA
<A HREF=”URL”>LinkText</A>

<a>...</a>
Designates the origin and destination of a hyperlink

<a href="#name">...</a>
Links to a target location in the current page

<a href="URL#name">...</a>
Links to a target location in a page outside the current page

<a name="name">...</a>
Sets a target location within a document

<a href="mailto:email@something.com">...</a>
Creates a mailto link

TABLES
<table>...</table>
Generates a table

<table border="pixels">
Sets the size of cell borders

<table cellspacing="pixels">
Sets the amount of space between cells

<table cellpadding="pixels">
Sets the amount of space between a border and cell content

<table height="pixels" or "%">


Sets the height of a table

<table width="pixels" or "%">


Sets the width of a table

<td>...</td>
Defines a table data cell

<td colspan="columns">
Sets a cell to span columns

<td rowspan="rows">
Sets a cell to span rows

<td nowrap>
Prevents the lines within a cell from wrapping

<th>...</th>
Defines a table header with bold, centered table data

<tr>...</tr>
Defines a table row

<tr align="?"> or <td align="?">


Aligns the contents of a row or cell to the left, right, or center

<tr valign="?"> or <td valign="?">


Sets the vertical alignment of a row or cell to the top, middle, or bottom

FRAMES
<frameset>...</frameset>
Specifies the layout of subsections in the main browser window
<frameset rows="value,value">
Defines the rows within a frameset

<frameset cols="value,value">
Defines the columns within a frameset

<noframes>...</noframes>
Provides alternate content for browsers that do not support frames

<frame src="?">
Defines the appearance and content of a single frame

<frame name="name">
Labels the frame for targeting by other frames

<frame marginwidth="#">
Sets the margin width of a frame

<frame marginheight="#">
Sets the margin height of a frame

<frame scrolling="value">
Creates a frame scrollbar

<frame noresize>
Prevents the resizing of a frame

It is best to not use frames for usability reasons and so that search engines can spider the
site effectively

HORIZONTAL RULES
<hr>
Inserts a horizontal rule

<hr size=?>
Sets size (height) of rule

<hr width=?>
Sets width of rule, in percentage or absolute value

<hr noshade>
Creates a rule without a shadow

FORMS
<form>...</form>
Generates a container for all form elements

<form action="url">
Designates the path of the script to process input from the form

<form method="get|post">
Instructs the browser how to interact with the form URL

<form accept="media type">


Defines which MIME types are supported by the server processing the form

<form accept-charset="text">
Defines which character sets are supported by the server processing the form

<form enctype="media type">


Defines the format of the submitted data

<option>
Defines each menu item

<select name="name">...</select>
Generates a pull-down menu

<input type="checkbox">
Generates a check box

<input type="hidden">
Conceals a field from view

<input type="image">
Generates an image that acts like a Submit button

<input type="password">
Generates a one-line password box

<input type="radio">
Generates a radio button

<input type="text">
Generates a one-line text box

<input type="submit">
Generates a Submit button (send form)

<input type="reset">
Generates a Reset button (clear form)

SPECIAL CHARACTERS
&amp;
&
Ampersand

&trade;

Trademark

&reg;
®
Registered trademark

&copy;
©
Copyright

&quot;
"
Double quote marks

&#147;

Left quote

&#148;

Right quote

&frasl;
/
Forward slash

&lt;
<
Less than arrow

&gt;
>
Greater than arrow

&raquo;
»
Right pointing double angle quotation mark
&laquo;
«
Left pointing double angle quotation mark

&#151;

Em-dash

&pound;
£
Pound sign (GBP currency)

&deg;
30°
Degree

&frac14;
¼
Quarter

&frac12;
½
Half

&frac34;
¾
Three quarters

&middot;
·
Middle dot

&iexcl;
¡
Inverted exclamation mark

&spades;
?
Black spade suit

&clubs;
?
Black club suit
&hearts;
?
Black hearts suit

&diams;
?
Black diamond suit
MODULE

Advance HTML & CSS


HTML Versions
You should be aware that there are historically many versions of the HTML
specification. You will read most about the HTML 3.0, 3.2, and 4.0 specification. I
have tried to display HTML tags and attributes that are supported by the 3.2 and 4.0
specification, but cannot guarantee that all tags and attributes contained herein will
work in all versions of HTML. There are several HTML common document types when
refering to HTML 4.0 which are:
Strict - HTML 4.0 without frame or HTML 3.2 depreciated feature support.
Frame - HTML 4.0/3.2 with frame support.
Transitional or loose - Supports features of HTML 3.2 that are being depreciated in
HTML 4.0. This DTD does not support framesets. Some depreciated tags/elements
not supported by strict HTML 4.0 are CENTER, FRAME, FRAMESET, NOFRAMES,
IFRAME, ISINDEX, DIR, MENU, APPLET, BASEFONT, FONT, S, STRIKE, and U.

This document covers most commonly used HTML elements and attributes, but not
all. For an excellent source of information regarding available HTML 4.0 elements and
attributes, refer to the Web Design Group's web page, HTML 4.0 Reference section.
Used in combination with information from the Web Design Group and the World
Wide Web Consortium web pages (See the links section or "Recommended Reading"
section of this document for URL) this document should provide a thorough
introduction to HTML.

HTML Support
You should also know that many of the element tags are being depreciated in favor
of cascading style
sheets. This means that some of the attributes with regard to text fonts and color
are being depreciated and these values are to be controlled using the style sheets.
This makes it easier to control the attributes of multiple HTML documents such as the
HTML in this document from one cascading file sheet file. You should learn at least
minimal control of attributes using style sheets before writing great quanties of
documents and thereby being forced to go back and change your files. Some
examples in this document demonstrate the use of style sheet and inline style
commands. Many of the elements not supported by the strict HTML 4.0 document
type definition (DTD) will be noted with the word "depreciated" where they are
presented.
One other consideration to be aware of is that various client web browsers have
various support for various methods of setting attributes and displaying information
that is contained in web pages. For instance, not all older web browsers support
frames, but most clients should have web browsers today that support frames. Also
some style sheet properties may be supported by some browsers but not by others.
The best way to determine what will work is to read referenced documentation and
experiment.

Getting ready to create a website


You can create your web site off line using a standard text editor, an HTML text
editor, or a HTML graphics editor. I recommend using an HTML text editor which lets
you see the HTML tags in a different color than the surrounding text which makes
them easier to see. The free ware editor, Arachnophillia, is a good choice to begin
with. There are also some editors which perform validation dynamically. One of these
may be an even better choice if you can obtain one.

Directory Structure
You will want to create your web pages in a separate directory on your computer and
as you link deeper into your web pages you will want to create more sub-directories.
Normally, I use the following structure:
mainpage - The main folder for your web page, name it an appropriate name for
your web site. Your HTML files for your home page will go here.
gifs - Where I put all gif files to be used in common with the mainpage and other
pages such as buttons used to provide links to other parts of my web page. I
usually place all backgrounds here. I do not put pictures for specific sections
here. For example, all pictures that are used in "The CTDP Networking Guide" are
placed with the HTML files in that folder.
subject1 - In the case of the CTDP, this may be "Linux". Your html and graphics files
for a particular web page subsection will go here. Subject1/sub1 - Sub subjects of
subject 1.
subect1/sub2

subject2 - This may be "networking".


subject2.

Starting with a Template


To begin your first web page, you will want to create a template from which you can
start all your pages which has the basic structure of an HTML document as shown in
the "HTML document Structure" section of this document. You can copy the example
file shown there into your editor's file or make your own. You will want to follow the
standard HTML structure of HTML, HEAD, and BODY elements. If you want to set
your HTML page with multiple frames, for example with an HTML index on the left
side for easier document viewing, you will need to become familiar with the section
on FRAMES before you begin. If working with frames is initially too complicated, stick
with the standard HEAD, BODY structure until you gain familiarity.
HTML Structure
HTML uses tags that are encased in brackets like the following:
<>
HTML documents consist of elements which are constructed with tags. For instance,
a paragraph is considered to be an html element constructed with the tags <P> and
</P>. The <P> tag begins the paragraph element and the </P> tag ends the
element. The following is a paragraph element.
<p>This is a sample paragraph element. Any text in a paragraph goes here.</p>
Not all tags have a tag for ending the element such as the line break, <br> tag. The
HTML document is begun with the <html> tag and ended with the </html> tag.
Elements of an HTML document include the HEAD, BODY, paragraphs, lists, tables,
and more. Elements may be embedded within each other. Also some elements have
attributes embedded in the tag that define characteristics of the element such as
the placing of text, size of text, source of an image, and other characteristics
depending on the element. These attributes are listed in this document when the
element is discussed in detail.
An HTML document is structured with two main elements:
1 HEAD
2 BODY

An Example HTML File


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"><html><head> <meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1"> <meta name="GENERATOR"
content="Arachnophilia 3.9"> <meta name="description" content="Comprehensive
Documentation and information about HTML."> <meta name="keywords"
content="HTML, tags, commands"> <title>The CTDP HTML Guide</title>
<link href="style.css" rel="stylesheet" type="text/css"><!-- Background white, links
blue (unvisited), navy (visited), red (active) --
></head><body><center><h1>HTML Document
Structure</h1></center><p>This is a sample HTML file.</p></body></html>
Comments begin with <! and end with the > bracket. The tags "HTML", "BODY", and
all others may be in capital or small letters, however the new XHTML standard
requires small letters so small letters are recommended.
In the above file, there is a header and a body. Normally you can copy this file and
use it as a template to build your new file while being sure to make some
modifications. You can edit HTML using a standard editor, but it is easier to use an
HTML editor like Arachnophilia since it displays the tags with different colors than the
text is displayed in. Also note the LINK element above which specifies a style sheet
to be used. This is a file with a name "style.css". This is a text file that may be
created with a text editor but must be saved in plain text format. See the section
called "Setting Document Style" for more information about style sheets.
The center tag used above is depreciated. It is best to use style sheets to center
headers and other items. This is covered in more detail later.
HTML Header
The Header
The header contains several notable items which include:
1 doctype - This gives a description of the type of HTML document this is.
2 meta name="description" - This gives a description of the page for search
engines.
3 meta name="keywords" - This line sets keywords which search engines may
use to find your page.
4 title - Defines the name of your document for your browser.

The header in our example document:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"><html><head> <meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1"> <meta name="GENERATOR"
content="Arachnophilia 3.9"> <meta name="description" content="Comprehensive
Documentation and information about HTML."> <meta name="keywords"
content="HTML, tags, commands"> <title>The CTDP HTML Guide</title><link
href="style.css" rel="stylesheet" type="text/css"></head>
The <!DOCTYPE> Line
The <!DOCTYPE> line is used to define the type of HTML document or page. It has
no ending tag. The three document types that are recommended by the World Wide
Web Consortium (W3C) are:
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">This implies strict
adherence with HTML 4 standards.
2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">This
supports frameset tags. Some documentation claims this sets strict adherence with
HTML 4 standards, however by using HTML validators for testing, I concluded that
this is the same as
1 Transitional with frameset support.
2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">This is
used to support depreciated HTML 3.2 features. It does not support frames.

Note: I have noticed that capitalization is important in the document type


declaration. Not all validators will recognize lower case when the text "-//W3C//DTD
HTML 4.01//EN" is "-//w3c//dtd html 4.01//en". Therefore it is best if you use the
upper case values as in the example above.
Elements in the Header
Elements allowed in the HTML 4.0 strict HEAD element are:
BASE - Defines the base location for resources in the current HTML document.
Supports the TARGET attribute in frame and transitional document type definitions.
LINK - Used to set relationships of other documents with this document.
META - Used to set specific characteristics of the web page and provide
information to readers and search engines.
SCRIPT - Used to embed script in the header of an HTML document.
STYLE - Used to embed a style sheet in the HTML document.
TITLE - Sets the document title.

The additional element allowed by the HTML 4.0 transitional standard is:
ISINDEX (Depreciated) - Allows a single line of text input. Use the INPUT
element rather than ISINDEX.

The <META> Element


The <META> element is used to set specific characteristics of the web page and
provide information to readers and search engines. It has no ending tag. Attributes
http-equiv - Possible values are: refresh - The browser will reload the
document after the specified seconds specified with the CONTENT value have el
lapsed. Ex: <META HTTP-EQUIV=refresh CONTENT=45>
expires - Gives the date that content in the document is considered
unreliable.
reply-to - A an email address of the responsible party for the web page. This
attribute is
not commonly used. Ex: <META HTTP-EQUIV=reply-to
CONTENT="ctdp@tripod.com">

name - Provides non-critical information about the document possibly useful


to someone looking at it. Possible values are: author - The person who made the
page or the HTML editor name . Ex: <META NAME=author CONTENT="Mark Allen">
description - An explanation of the page or its use, used by search engines
at times to provide a page summary. Ex: <META NAME=description CONTENT="The
CTDP Home Page">
copyright - A copyright notice for the page. Ex: <META NAME=copyright
CONTENT="Copyright 2000, Mark Allen">
keywords - A list of keywords which are separated by commas. These
keywords are used by search engines. EX: <META name="keywords"
content="computer documentation, computers, documentation, computer help">
This section is very important if you want your web page to be found by search
engines. Please note that keywords are separated by commas, not spaces and
that the words "computer documentation" are treated by search engines as
one word. If someone enters the phrase "computer documentation" when doing a
search, it gives the web page a much greater chance of being found than just having
the separate keywords "computer" and "documentation".
date - <META name="date" content="2000-05-07T09:10:56+00:00">

content - Specifies a property's value such as the content of this document is


text/HTML.
scheme - Names a scheme to be used to interpret the property's value.

The <BASE> Element


This element defines the way relative hyper links are handled in the body of the
document. It has no ending tag. It supports the TARGET attribute in frame and
transitional document type definitions. Only one BASE element may exist in the
header.
If you copy the websites page from the CTDP website at
http://ctdp.tripod.com/websites.html to your website at
http://yoursite.yourwebserver.com/websites.html, then any relative links on the
copied page will try to link to the http://ctdp.tripod.com page rather than the
http://yoursite.yourwebserver.com page and you may get the "file not found" error
from your browser. Inserting the <base> tag into the copied page will fix the
problem.
<base href="http://www.comptechdoc.org/">
Without this tag, if there were a relative link to "linux/index.html" on this page, the
user's web browser would look for the file in
"http://yoursite.yourwebserver.com/linux/index.html" which would not exist unless it
were also copied over and placed at the same relative location on your website.
The <LINK> Element
Used to set relationships of other documents with this document. For example a style
sheet that is used to control element style (as in the above example) may be defined
with this element. Attributes:
CHARSET - The character encoding of the link. An example is "ISO-8859-1".
HREF - The location and name of the resource.
HREFLANG - Describes the expected language. An example value is "en" for
English.
MEDIA - Describes the type of display the content is designed for. Possible
values include all, aural, braille, handheld, projection, print, screen, tty, and tv.
REL - Relationship to the linked resource.
REV - Relationship from the linked resource to the document. Possible values
of REL and REV include alternate, appendix, stylesheet, bookmark, chapter,
contents, copyright, glossary, help, index, next, prev, start, section, and subsection.
The value "made" supported by HTML 3.2 is not supported by HTML 4.0.
TYPE - Describes the expected content of the resource the link points to.
Typical values include application/java, text/html, text/css, image/jpeg, and
text/javascript.

An additional attribute allowed by the HTML 4.0 transitional standard is:


TARGET - Specifies the frame target the referenced page will be put into. The
target may me a named window or one of the special reserved names below. If the
target is a named window that exists the web page the link points to will be loaded
into that window. If a window by that name does not exist, a new window with that
name will be created. _blank - The web linked page loads in a new window and does
not name the window.
_parent - The new page will load in the parent frame or window.
_self - The new page will load in the same window that the link is in. If the
link is in a frame, it will load inside the frame. This is the default target.
_top - The new page will load into the top window reguardless of how many
framesets deep the link is embedded.

An example:
<link href="style.css" rel="stylesheet" type="text/css">
The <TITLE> Element
The text between the <title> and </title> tags is the title of the document.
An example:
<title>The CTDP HTML Guide</title>
The <SCRIPT> Element
Used to embed script in the header of an HTML document. Attributes:
CHARSET - The character encoding of the script such as "ISO-8859-1".
DEFER - The script will not be parsed until the document is loaded.
LANGUAGE - Describes the name of the script language.
SRC - The external location where the script may be. In this case the script in
not includes in between the SCRIPT tags, but an external file is loaded.
TYPE - Describes the content type of the script language.

The <STYLE> Element


This element is used to embed a style sheet in the HTML document. Attributes:
MEDIA - Same as described in the LINK element above.
TITLE - The style sheet title
TYPE - The content type.

If this element is used an external style sheet is not used as can be done using the
LINK element, above. The style sheet information is embedded between the <style>
and </style> tags.
HTML Body
The Body
The body will define the rest of the HTML page which is the bulk of your document. It
will include headers, paragraphs, lists, tables, and more. These elements are
described fully in the rest of this document.
An example body section:
<body text="#000000" bgcolor="#FFFFFF" link="#0000FF" vlink="#000080"
alink="#FF0000"><h1 style="text-align: center">HTML Document
Structure</h1><p>This is a sample HTML file.</p></body></html>
The above example is similar to the body section in the example in the "HTML
Document Structure" section with the exception that this example controls the body
background, wallpaper, and link color directly rather than using style sheets. As you
can see below many of the attributes to control the BODY are depreciated in favor of
style sheet use.
The BODY Element Tags and Attributes
The <body> tag is used to start the BODY element and the </body> tag ends it. It
is used to divide a web page within one or more sections. Its tags and attributes are:
<body> - Designates the start of the body. ONLOAD - Used to specify the
name of a script to run when the document is loaded.
ONUNLOAD - Used to specify the name of a script to run when the document
exits.
BACKGROUND="clouds.gif" - (Depreciated) Defines the name of a file to use
for the background for the page. The background can be specified as in the following
line. <body text="#000000" bgcolor="#FFFFFF" link="#0000EF" vlink="#51188E"
alink="#FF0000" background="clouds.gif">
BGCOLOR="white" - (Depreciated) Designates the page background color.
TEXT="black" - (Depreciated) Designates the color of the page's text.
LINK="blue" - (Depreciated) Designates the color of links that have not
been visited.
ALINK="red" - (Depreciated) Designates the color of the link currently being
visited.
VliNK="green" - (Depreciated) Designates the color of visited links.

</body> - Designates the end of the body.

For the depreciated attributes noted above, see the "Setting document
style" section for an example of how to set the same attributes using a style
sheet. If the colors are defined with "#FFFFFF" as done in the above example, the
values indicate the intensity of the colors, red, green, and blue in hexadecimal. The
leftmost two "FF" indicate the strength of the color red, the center indicates the
strength of the color green, and the rightmost two indicate the strength of the color
blue. The values may be a hexadecimal value from 0 through FF which in decimal is
0 through 255. The highest value being the highest strength of the respective color.
This format is "RRGGBB". You can also specify the color with one of the following
standard colors.
1 black
2 white
3 red
4 green
5 blue
6 yellow
7 magenta or fuschia
8 cyan or aqua
9 purple
10 gray
11 lime
12 maroon
13 navy
14 olive
15 silver
16 teal

Setting a background image on the page


To set up a background on the web page use a BODY statement with the
BACKGROUND attribute defined as follows:
<body text="#000000" bgcolor="#FFFFFF" link="#0000FF" vlink="#000080"
alink="#FF0000" background="clouds.gif">
This method is depreciated and authors are encouraged to use style sheets.
HTML Frames
Frames can be used to split a web page so you can load multiple HTML files or pages
into one web page. This will cause the web browser to display multiple pages at one
time. A common example of this technique which I like to use is to display an index
of a document on the left side of the browser window with descriptions and links so
when the reader clicks on the link, that page is displayed on the right side of the
browser window. Using frames may be a bit complicated at first for those new to
HTML, so you may want to skip this section or skim it, then come back to it when
you want to create frames in your HTML documents.
Important Note about Frame use
Should you decide to use frames on your web page, you should be aware of some
things.
Not all browser and webcrawler programs support frames. This is especially
important with regard to webcrawlers since, if your pages are not browsed by
webcrawlers, search engines may not log your pages for those searching for your
subject material. Therefore, you should utilize the NOFRAMES tag described below to
support frames. In your file that contains the FRAMESET, you may support this by
including a copy of your index body in the NOFRAMES section.
Also, to support users that can't see frames, you should put a link at the top
and bottom of the page that allows them to get back to your main index or home
page.
The Frameset DTD must be specified on the first line as in the below example
rather than the strict or transitional DTD in order to support frames.

When I start an html document, I typically call the first page in the document
"index.html". This is because it is a standard name used by web servers for the
home page, and it is easy to remember that most html documents start with the
name "index.html". The "index.html" file and all associated html files it will link to
which are a part of the document are contained in the same sub directory on the
computer. Therefore, when writing this document I started with the following HTML
file as my "index.html" file. Note: Some experts would argue the wisdom of naming
your file "index.html", in favor of a more descriptive title that would show up on
search engines. What you do should depend on your needs.
<!DOCTYPE HTML PUBliC "-//W3C//DTD HTML Frameset 4.01//EN"><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Arachnophilia 3.9">
<META NAME="FORMATTER" CONTENT="Arachnophilia 3.9"> <meta
name="keywords" content="Documentation, networking, howto, routing,
information, routers, firewalls, firewall, IP, masquerading, masquerade, arp, rarp,
tcp, udp, protocol, protocols"> <title>The CTDP HTML
Guide</title><head><frameset border="1" cols="200,*" frameBorder="0"
frameSpacing="4"><noframes><body><p>You should include HTML here to
support webcrawlers and browsers that don't support frames. You may want to
include a second copy of your index, and set your wallpaper and colorsin the BODY
statement above the same as you would in your index
file.</p></body></noframes><frame name="left" src="htmlindex.html"><frame
name="right" src="htmlintroduction.html"></frameset></html>
Notice that in this example there are initially no <body> tags. The only <body> tags
occur inside the NOFRAMES section which supports browsers that are not frames
capable. The <body> tag is replaced by the <frameset> tags. The <frame> tags are
used to define each element in the FRAMESET. Notice that there is no </frame> to
end the FRAME element. You should also note that rather than setting the document
type (in the first line, above) to Transitional, it is set to Frameset in order to
support frames.
Tags and associated attributes for FRAMES
<FRAMESET> - Used to divide the browser window into separate frames that
can display multiple documents ROWS="10" - Splits the window vertically into a
number of rows specified by one of: A number of rows.
A percentage of the total window height. EX: ROWS="10%".
An asterisk means the frame will occupy all the remaining space. It will divide
the space evenly between frames if multiple frames are specified with the asterisk.
ColS="10" - Splits the window horizontally into a number of columns specified
by one of: A number of columns.
A percentage of the total window width. EX: ColS="10%".
An asterisk means the frame will occupy all the remaining space. It will divide
the space evenly between frames if multiple frames are specified with the asterisk.

ONLOAD - Used to specify the name of a script to run when the document is loaded.
ONUNLOAD - Used to specify the name of a script to run when the document exits.
FRAMESPACING="12" - (Depreciated) Defines the space between the frames in
pixels.
FRAMEBORDER="NO" - (Depreciated) Defines whether a border for the frames
should be displayed. The choices are YES or NO.
BORDER="5" - (Depreciated) The size of the frame border in pixels.

<FRAME> - Specifies a frame to be placed inside a FRAMESET.


FRAMEBORDER - Determines if there is a visible border for the frame. The possible
values are 0 and 1 with a default value of 1.
LONGDESC - A frame long description.
NAME=left - Defines the name of the frame. In this case, the name of the
frame is "left". This will be used in A (anchor) references later to place various
content into the frame.
SRC="htmlindex.html" - Specifies the location or the URL (Universal Resource
Location) of the document that will be placed in the frame.
MARGINHEIGHT="5" - The number of pixels left above and below a document
that is in a frame.
MARGINWIDTH="10" - The number pixels to left on the right and left side of a
document in a frame.
SCRolliNG="AUTO" - Specifies the possible existence of scrollbars in a frame.
Possible values are YES, NO, and AUTO, with AUTO as the default.
NORESIZE - Keeps this frame from being resized with the mouse.
SCRolliNG - Determines if the frame can use a scroll bar if it exceeds the size
of the available area on the browser. Possible values are yes, no, and auto.

<NOFRAMES> - Used for web browsers that don't support FRAMESETs. It provides
an alternate body in documents that are FRAMESET documents. The <BODY> and
</BODY> tags which define the BODY element are normally inside the
<NOFRAMES>...</NOFRAMES> tags.
</NOFRAMES> - Ending tag for the NOFRAMES element..
</FRAMESET> - Used to end a frameset.

Another example
Another, slightly more complicated example is:
<frameset rows="10%, *"> <frame name="top" src="topselect.html">
<frameset cols="10%, 30%, 30%, 30%"> <frame name="leftbar"
src="myindex.html"> <frame name="mleft" src="mleft.html"> <frame
name="mmiddle" src="mmiddle.html"> <frame name="mright" src="mright.html">
<frameset></frameset>
This example uses two framesets. The first divides a top section and a bottom
section. The second frame set divides the rest of the window (90%) into four
sections, the first composing the leftmost 10%, and each of the other three sharing
30%.
How to get new information into the frame
To make frames useful, you will need to use anchor links to direct the contents of
HTML files to them. This is done using the TARGET attribute with the anchor tag as
follows:
<a href="htmlstructure.html" target="right">HTML Document Structure</a>
In my first example, I defined a frame with the name "right". When the user clicks
on this link with their web browser, the HTML file pointed to by the link will be
directed to the target named "right" which is defined on the right side of the browser
window. The anchor statements shown above are placed in the file called
htmlindex.html which resides on the left side of the browser window. This allows the
user to control the contents of the right side of the browser with the index file, full of
anchor links, which resides in the left side of the browser window. A sample
abbreviated index file is listed below:
<head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-
1"> <meta name="GENERATOR" content="Arachnophilia 3.9"> <meat
name="FORMATTER" CONTENT="Arachnophilia 3.9"> <title>The CTDP HTML
Guide</title></head><body><h3>HTML Index</h3><hr><ol><li><a
href="htmlintroduction.html" target="right">Introduction</a><h3>Structure</h3>
<li><a href="htmlstructure.html" target="right">HTML Document
Structure</a><li><a href="htmlhead.html" target="right">The Header
Section</a><li><a href="htmlbody.html" target="right">The Body
Section<a><li><a href="htmlframes.html" target="right">Using
Frames</a><h3>Layout Mechanisms<h3><li><a href="htmlparagraphs.html"
target="right">Headers and Paragraphs<a><li><a href="htmllists.html"
target="right">Lists</a><li><a href="htmltables.html"
target="right">Tables</a></ol><center><a href="../index.html" target="_top"
onMouseOver="window.status='To Computer Tech Home Page' ;return true"
onMouseOut="window.status='';return true"><img src="../greenhomebutton.gif"
alt="Home" vspace=3 border=0 height=33
width=115<a></center></body></html>
Categories
HTML Guide Contents Page

HTML Element Categories


It is important to be aware, when using HTML and style sheets that HTML elements
are categorized into several categories. Some style properties apply to some
categories of elements and not to others. The following types of elements exist:
Block - Include a line break before and after the element.
Inline - Included with the text as part of a line.
List Item - Elements that support providing a list of items. List item elements
are block level elements.

Block HTML Elements

A block with centered Description Comment


contents is definedName
ADDRESS Supplies contact information for the -
document
BLOCKQUOTE Used to quote in block form -
CENTER Depreciated -
DIV A container allowing specific style to be -
added to a block of text.

DIR A container allowing specific style to be -


added to a block of text.

FRAMESET A container allowing multiple frames (HTML -


documents) to be placed on a web
browser.
H1, H2, H3, H4, H5, H6 Headings -
HR Horizontal rule -
ISINDEX An input prompt for a single line of text Depreciated
NOFRAMES Alternate content for browsers that do not -
support frames.

NOSCRIPT Alternate content for browsers that cannot -


run script programs

P Paragraph - Should not contain other block -


elements including tables, but may contain
list elements
PRE Preformatted text is rendered with spaces and -
carriage returns as typed.

TABLE Used to present an ordered set of data. Table Includes table sub
subelements work as block elements. elements

FORM Used to present a form to the client. Form -


subelements work as block elements.

List item elements are also considered to be block elements.


List-item Elements

Name Description Comment


DIR Directory List Depreciated
DL Definition List -
LI List Item -
OL Ordered (numbered) List -
UL Unordered List -

Block/Inline HTML Elements


The elements in this list may be considered block or inline elements, depending on
how they are used. They are considered inline elements if used inside a paragraph
(P) or another inline element.

-Name Description Purpose Comment


APPLET For placing Java applets in the page. - (Depreciated)
BUTTON Used to define a FORM submit, reset, - -
or push button.

DEL Used to indicate deleted content Phrase Both a block and


inline element
IFRAME Inline frame - (Depreciated)
INS Marks inserted content Phrase Both a block and
inline element
MAP Establishes an image map to be used - -
with an IMG or OBJECT element

OBJECT Used to include applets, images, videos - -


and sound on the web page.
SCRIPT Defines a script to be run on the client computer. - -

Inline HTML Elements

Name Description Purpose Comment


A Anchor - -
ABBR Denotes an abbreviation Phrase -
ACRONYM Denotes an acronym. - -
AREA Define a map region in an image. Inside the MAP -
element
B Bold Font -
BASEFONT Allows font changes - Depreciated
BDO Overrides text direction with values - -
of ltr (left to right) or rtl (right to
left).
BIG Sets size of text to big Font -
BR Break Treated special -
by style sheets.

CITE Used to mark titles of articles or Phrase -


other publications.

CODE Denotes computer program code. Phrase -


DFN Denotes a definition. Phrase -
EM Denotes emphasis Phrase -
FONT Allows font changes. - (Depreciated)
I Sets text to italics Font -
IMG Allows placement of a graphical - -
image in the page.

INS Denotes inserted text. Phrase -


KBD Denotes information typed from the Phrase -
keyboard.

PARAM Used to add additional parameters - -


to the object or applet elements.

Q Used for short quotations - -


S Strike through text Font Depreciated
SAMP Denotes a sample. Phrase -
SMALL Sets text size to small Font -
SPAN A container used to set special style to specific - -
areas of the page.

STRIKE Sets text to have a line struck through it Font -


STRONG Denotes Phrase -
SUB Subscript - -
SUP Superscript - -
TEXTAREA A form for multiline text input. - -
TT Sets text style to monospaced teletype Font -
U Sets text underlined Font Depreciated
VAR Denotes a variablein a program. Phrase -

HTML Guide Contents Page


HTML Elements
HTML catagorizes elements into specific categories. The two main types of element
categories are:
Block - Include a line break before and after the element.
Inline - Included with the text as part of a line.

See the section called "HTMLElement Categories" for a list of block and inline
elements with short descriptions.
In HTML there are specific rules with regard to what elements a specific element may
contain. For example some elements may only be contained in the HEAD header
element. The paragraph element may not contain block elements. The table below
lists elements and what they may contain:

Name Contained Elements


A inline elements except A
ABBR inline elements
ACRONYM inline elements
ADDRESS inline elements
APPLET PARAM, inline elements block elements
AREA none
B inline elements
BASE none
BASEFONT none
BDO inline elements
BIG inline elements
BLOCKQUOTE block elements, SCRIPT
BODY inline elements, block elements
BR none
BUTTON inline elements excluding A, BUTTON, INPUT, LABEL, IFRAME,
SELECT, and TEXTAREA

CENTER inline elements, block elements


CITE inline elements
CODE inline elements
DD inline elements
DEL inline elements, block elements
DFN inline elements
DIR LI excluding block elements
DIV inline elements, block elements
DL DD, DT
DT inline elements, block elements
EM inline elements
FIELDSET inline elements, block elements, LEGEND
FONT inline elements
FORM block elements excluding FORM
FRAME none
FRAMESET FRAMESET, FRAME, NOFRAMES
H1-H6 inline elements
HEAD BASE, ISINDEX, LINK, META, OBJECT, SCRIPT, STYLE, TITLE
HR none
I inline elements
IFRAME inline elements, block elements
IMG none
INPUT inline elements, block elements excluding BUTTON
INS inline elements, block elements
ISINDEX none
HTML HEAD, BODY, FRAMESET
KBD inline elements
LABEL inline elements excluding LABEL
LEGEND inline elements
LI inline elements, block elements (MENU and DIR list items exclude block
elements)
LINK none
MAP block elements, AREA
MENU LI not containing block elements
META none
NOFRAMES inline elements, block elements, BODY
NOSCRIPT inline elements, block elements
OBJECT PARAM, inline elements block elements
OL LI
OPTGROUP OPTION
http://www.comptechdoc.org/guides/htmlguide/htmlelement.html (2 of 3)7/21/2003 7:44:47 AM HTML Elements

OPTION none (text)


P inline elements
PARAM none
PRE inline elements excluding APPLET, BIG, BASEFONT, FONT, IMG, OBJECT,
SMALL, SUB, SUP

Q inline elements
S inline elements
SAMP inline elements
SELECT OPTION, OPTGROUP
SCRIPT none (script program)
SMALL inline elements
SPAN inline elements
STRIKE inline elements
STRONG inline elements
STYLE none (A style sheet)
SUB inline elements
SUP inline elements
TBODY TR
TD inline elements, block elements
TFOOT TR
TH inline elements, block elements
THEAD TR
TR TH,TD
TEXTAREA none (text)
TITLE none
TT inline elements
U inline elements
UL LI
VAR inline elements
HTML Headers and Paragraphs
HTML Headings
There are 6 levels (H1 through H6). H1 is the largest. Headings are always displayed
as bold text (Unless modified using the STYLE attribute or style sheets). Headings
with numbers above the <h3> tag such as <h4><h5> and <h6> are not normally
used since they are so small.
<h1> - Start heading of level 1.</h1> - End level 1 heading.
Heading attributes are the same as the paragraph attributes, below. No attributes
are supported by strict HTML 4.0 other than common attributes such as STYLE which
are used to set color and position.
HTML Paragraph
The paragraph element begins with the <P> tag and ends with the </P> tag. It
should not contain tables and other block elements. A sample is shown below.
<p>This is a sample paragraph element. Any text in a paragraph goes here.</p>
Paragraph Attributes
ALIGN="CENTER" - (Depreciated) Sets the alignment of the paragraph with
respect to the page size. Values are LEFT, RIGHT, and CENTER.
STYLE="font: 16pt courier" - Sets the style or color of the text. This
statement starts a paragraph with color, blue: <p style="color: green">. The STYLE
attribute is common to most HTML elements (See the "Common Attributes" section).

Paragraph Examples
This is the HTML code for a paragraph demonstrating use of the STYLE attribute
along with the SPAN element.
<p style="text-align: 'center'; font: '16pt'; courier; color: 'blue'">The color of the
sky is blue, but if you look at the <span style="color: 'green'">trees, they are
green</span>. This effect is produced using the &#60span&#62 element with the
style ="color: 'green'" attribute set.</p>
This is how it looks:
The color of the sky is blue, but if you look at the trees, they are green. This effect is
produced using the <SPAN> element with the STYLE ="color: 'green'" attribute set.
An example HTML document using Headers and Paragraphs
This example is from "The CTDP Linux User's Guide":
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"><html><head><meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1"><meta name="GENERATOR"
content="Arachnophilia 3.9"><meta name="description" content="Comprehensive
Documentation and information about Linux."><title>The CTDP Linux User's
Guide</title></head><body><center><h1>Logging in, Logging Out, and Shutting
down</h1></center><h3>Logging in</h3><p>Once you have completed your
system install and booted your system, you should see a login prompt on your
monitor. When you did your Linux install you should have set a root password. You
may have also created a user with a password. Therefore to log in, you will want to
type the name of a user or "root" for the login name and enter the appropriate
password. If you logged in as a normal user and know the root password and want
to use administration commands, you may use the command "su" to become a
"super user". Some systems also support the "sudo" command, which allows
administrative privileges on a command by command basis.</p>
<h3>Logging out</h3><p>Use the command "logout" to exit a given session. If
you have logged in, then typed "su" to become a super user or another user, you
may need to type "exit" until your SHLVL environment value is 1. Then you can type
"logout" to exit your session. The "exit" command will take you back to previous
shell levels.</p><h3>Shutting Down</h3><p>The system is intended to be
shutdown by the system administrator using the shutdown command in one of the
forms shown below. Many systems are set up to capture the
&#60CTRL&#62&#60ALT&#62&#60DEL&#62 keystroke combination to issue the
shutdown command through the init program. This will work on most systems if the
root user is logged in. Examples of using the shutdown command are shown
below.<blockquote>shutdown -h now<br>shutdown -r +10 "Rebooting in 10
minutes"<BR>shutdown -r 13:00<BR></blockquote>The first command will
shutdown and halt the system immediately. The second will reboot the system in 10
minutes and send the message to all users. The third command will shut the system
down and do a reboot at 1:00 in the afternoon.</p></body></html>
Although this document is about paragraphs and headers, there are a few
things worth noting here.
1 In the last paragraph, there is a <blockquote>...</blockquote> element
embedded. Although this works, the use of BLOCKQUOTE in this instance is
improper. Not only should it be done using style sheets, as follows, the use of
BLOCKQUOTE inside the paragraph element, P, is also not proper. The text where
the blockquote is should be changed to: <p class="indent">shutdown -h
now<br>shutdown -r +10 "Rebooting in 10 minutes"<br>shutdown -r
13:00<br></p> Of course the previous paragraph would need to be terminated with
the </p> tag and the following paragraph started with the <p> tag. The style sheet
should contain:

1 ."indent" { margin-right: '5%'; margin-left: '5%'; color: '#0000ff' } This


defines a class called ""indent"" with specific margin characteristics and color which,
when defined in the starting <P> tag, causes the contents of the element to have
the attributes declared for that class.
2 In the last paragraph, the following line: Many systems are set up to capture
the &#60CTRL&#62&#60ALT&#62&#60DEL&#62 keystroke combination to issue
the shutdown command through the init program. appears as follows when displayed
on the web browser: Many systems are set up to capture the <CTRL><ALT><DEL>
keystroke combination to issue the shutdown command through the init program.
This is because there are characters with special meaning in HTML and since HTML
uses the < and > characters to set up tags, there must be a special character
combination to display them so they are not used as part of a tag. These special
characters are listed in the section on text formatting.
3 The <center> and </center> tags are used to center the header,
<h1>...</h1>, at the top of the page. This can also be done with the following code
using the STYLE attribute which conforms to HTML 4.01 by not using depreciated
attributes.

<h1 style="text-align: 'center'">Logging in, Logging Out, and Shutting down</h1>


HTML Lists
HTML 4.0 supports three types of lists which are:
1 OL - Ordered list
2 UL - Unordered list
3 DL - Definition List

Directory and menu lists are depreciated.


Ordered Lists
Tags and Attributes
<OL> - Designates the start of an ordered list TYPE="1" - (Depreciated)
Designates the numerical label type for use in the list. Values are A for capital
letters, a for small letters, I for large Roman numerals, i for small Roman numerals,
1 for numerical integers. Default is "1".
START="3" - (Depreciated) Specifies value the list starts with. This value
must be a number such as 1,2,3,4, etc and causes the first or current item of the list
to begin with that value. If the type is set to "A" and start is set to "3", the list will
start with the letter "C", the third letter of the alphabet. Default is "1".
COMPACT - (Depreciated) The list is displayed with less room between
elements.

<LI> - Designates an item in the list. TYPE="A" - Designates the numerical


label type for use in the list. Values are A for capital letters, a for small letters, I for
large Roman numerals, i for small Roman numerals, 1 for numerical integers.
VALUE="5" - Designates a new value for the list item which affects this value
and those listed below it. This value must be a numerical value. If this value is set to
"5" and the type is "I" the listed value will be the Roman number 5, "V".

</OL> - Designates the end of an ordered list.

Ordered List Example


This is the HTML Code using depreciated attributes:

<ol type="I" start="5"><li>This is the Roman number for 5.<li>This is the Roman
number for 6.<li>This is the Roman number for 7.<li tyle="A" value="10">This is
the letter J, the tenth letter in the alphabet.<li type="1">This is the number
11.<li>This is the Roman number for 12.</ol>
This is the HTML Code using style attributes (CSS has no substitute for the START or
VALUE attributes):
<ol style="list-style-type='upper-roman'" start="5"><li>This is the Roman number
for 5.<li>This is the Roman number for 6.<li>This is the Roman number for 7.<li
style="list-style-type='upper-alpha'" value="10">This is the letter J, the tenth letter
in the alphabet.<li style="list-style-type='decimal'">This is the number 11.<li>This
is the Roman number for 12.</ol>
And this is how it looks:
1 This is the Roman number for 5.
2 This is the Roman number for 6.
3 This is the Roman number for 7.
4 This is the letter J, the tenth letter in the alphabet.
5 This is the number 11.
6 This is the Roman number for 12.
Unordered Lists
Tags and Attributes
<UL> - Designates the start of an unordered list TYPE=DISC - Designates the
shape used for the bullet. Values are CIRCLE, DISC, and SQUARE. The default of the
first embedded list is CIRCLE.

COMPACT - (Depreciated) The list is displayed with less room between


elements.

<LI> - Designates an item in the list. TYPE=SQUARE - Designates the shape


of the bullet for this item.

</UL> - Designates the end of an ordered list.

Unordered List Example


This is the HTML Code using depreciated attributes:
<ul type="square"><li>Item 1.<li>Item 2.<li>Item 3.<li type="disc">Item
4.<li>Item 5.<li>Item 6.</ul>
This is the HTML Code using style attributes:
<ul style="list-style-type='square'"><li>Item 1.<li>Item 2.<li>Item 3.<li
style="list-style-type='disc'">Item 4.<li>Item 5.<li>Item 6.</ul>
And this is how it looks:
Item 1.
Item 2.
Item 3.
Item 4.
Item 5.
Item 6.

If these items show up as the same on your browser, it is probably because your
browser is too old to support these type shapes which were added with HTML 3.2.
Definition Lists
Tags and Attributes
<DL> - Designates the start of a definition list. COMPACT - (Depreciated)
The list is displayed with less room between elements.

<DT> - Designates a definition term.


<DD> - Designates a definition to go with the definition term.
</DL> - Designates the end of a definition list.

Definition list example


This is the HTML code:
<dl><lh>Team Members <dt><b>Team Leader</b> <dd>Sarah Smith
<dt><B>Programmer</b> <dd>Jim Jenkins <dt><B>Engineer</b> <dd>Jeff
Jones <dt><B>Technician</b> <dd>Bill Brown</dl>
And this is how it looks:

Team Members Team Leader


Sarah Smith
Programmer
Jim Jenkins
Engineer
Jeff Jones
Technician
Bill Brown
HTML Tables
HTML Tables are arranged up and down by rows and left and right by columns which
are filled by data cells. A cell may be specify to occupy one or more table rows or
columns.
Tags and Attributes
<TABLE> - Designates the start of a table. ALIGN="left" - Depreciated Sets
the table alignment. Possible values are left, center, or right.
BORDER="5" - Sets the width of the table border in pixels. The default is 0.
CELLSPACING="2" - Sets the amount of space in pixels between the cells that
are in the table.
CELLPADDING="3" - Sets the space in pixels between the edges of each cell
and the contents of the cell.
DATAPAGESIZE="20" - Can be used to set the size of a table page when the
length of the table may exceed content that can fit on one page.
WIDTH="50%" - Sets the width of the table on the page in pixels or a percent
of the page from 1% to 100%.
RULES="ROWS" - Turns on lines around elements of tables. Possible values
are NONE, ROWS, COLS, GROUPS (borders between rows), or ALL. The default is
NONE.
BGCOLOR="#0000FF" - Depreciated Sets the background color of all cells
unless otherwise specified in a table row or table data cell definition.
BACKGROUND="flowers.gif" - Sets a background image like a wallpaper to be
used in the table. This works on some web browsers.
SUMMARY="To compare values" - The reason for the table.
FRAME - Determines which ot the table outer borders are visible. Possible
values are above, below, border, box, hsides (left and right), lhs (left only), rhs,
vsides (top and bottom), or void.

<CAPTION> - Must be first in the table before other elements. Must have the
</CAPTION> closing tag.
<COLGROUP> - Sets the table up in column groups essentially dividing one or
more columns into several groups. Use after CAPTION and before THEAD. Does not
have a closing tag. Attributes: ALIGN - Possible values are center, left, right, char
(Aligns the cell contents on the character specified by the CHAR attribute), and
justify.
CHAR - Alignment character for cells. The character the cell is to be aligned
to.
CHAROFF - Offset alignment character. Default is a period.
SPAN - Defines how many columns are in the group.
VALIGN - Values are baseline, bottom, middle, and top.
WIDTH - The column width in pixels or a percent of the table width.

<THEAD> ALIGN - Possible values are center, left, right, char (Aligns the cell
contents on the character specified by the CHAR attribute), and justify.
CHAR - Alignment character for cells. The character the cell is to be aligned
to.
CHAROFF - Offset alignment character. Default is a period.
VALIGN - Values are baseline, bottom, middle, and top.

<TBODY> ALIGN - Possible values are center, left, right, char (Aligns the cell
contents on the character specified by the CHAR attribute), and justify.
CHAR - Alignment character for cells. The character the cell is to be aligned
to.
CHAROFF - Offset alignment character. Default is a period.
VALIGN - Values are baseline, bottom, middle, and top.

<TFOOT> ALIGN - Possible values are center, left, right, char (Aligns the cell
contents on the character specified by the CHAR attribute), and justify.
CHAR - Alignment character for cells. The character the cell is to be aligned
to.
CHAROFF - Offset alignment character. Default is a period.
VALIGN - Values are baseline, bottom, middle, and top.

<TH> - Designates the start of a table header. Table headers use the same
attributes as data cells. ABBR="SHORT" - Text is entered for this attribute that
contains a short version of the cell content for when space is limited.
AXIS - A categorization of a table cell. This is a list of categories separated by
commas.
ALIGN="RIGHT" - Sets horizontal alignment of the contents of the cell as
LEFT, RIGHT, or CENTER. The default is LEFT.
VALIGN="TOP" - Sets the vertical alignment of the contents of the cells in the
row as TOP, MIDDLE, or BOTTOM. The default is MIDDLE.
CHAR - Alignment character for cells. The character the cell is to be aligned
to.
CHAROFF - Offset alignment character. Default is a period.
ROWSPAN="3" - Sets the number of rows this cell will occupy.
COLSPAN="2" - Sets the number of columns this cell will occupy.
HEADERS - A list of header cells separated by spaces that define the headers
that apply to the TH element.
SCOPE - Values are column, row, colgroup, and rowgroup.
NOWRAP="NOWRAP" - Depreciated Sets the data cell so the contents will
not wrap to another line.
HEIGHT Depreciated - Cell height in pixels.
WIDTH="10%" - Depreciated Sets the width of this column of cells
expressed as a percentage of the table width or as a number of pixels.
BGCOLOR="white" - Depreciated Sets the background color of this cell.

</TH> - Designates the end of a table header.


<TR> - Designates the start of a table row.
ALIGN="CENTER" - Sets horizontal alignment of the contents of the cells in
the row as LEFT, RIGHT, or CENTER. The default is LEFT.
CHAR - Alignment character for cells. The character the cell is to be aligned
to.
CHAROFF - Offset alignment character. Default is a period.
VALIGN="TOP" - Sets the vertical alignment of the contents of the cells in the
row as TOP, MIDDLE, or BOTTOM. The default is MIDDLE.
BGCOLOR="blue" - Depreciated Sets the background color of cells that are
contained in the row.
BACKGROUND="ice.gif"- Sets a background image like a wallpaper to be used
in the row. This works on some web browsers.

</TR> - Designates the end of a table row.


<TD> - Designates the start of a table data cell. ABBR="SHORT" - Text is
entered for this attribute that contains a short version of the cell content for when
space is limited.
AXIS - A categorization of a table cell. This is a list of categories separated by
commas.
ALIGN="RIGHT" - Sets horizontal alignment of the contents of the cell as
LEFT, RIGHT, or CENTER. The default is LEFT.
VALIGN="TOP" - Sets the vertical alignment of the contents of the cells in the
row as TOP, MIDDLE, or BOTTOM. The default is MIDDLE.
CHAR - Alignment character for cells. The character the cell is to be aligned
to.
CHAROFF - Offset alignment character. Default is a period.
ROWSPAN="3" - Sets the number of rows this cell will occupy.
COLSPAN="2" - Sets the number of columns this cell will occupy.
HEADERS - A list of header cells separated by spaces that define the headers
that apply to the TH element.
SCOPE - Values are column, row, colgroup, and rowgroup.
NOWRAP="NOWRAP" - Depreciated Sets the data cell so the contents will
not wrap to another line.
HEIGHT Depreciated - Cell height in pixels.
WIDTH="10%" - Depreciated Sets the width of this column of cells
expressed as a percentage of the table width or as a number of pixels.
BGCOLOR="white" - Depreciated Sets the background color of this cell.
BACKGROUND="ice.gif" - Sets a background image like a wallpaper to be
used in the cell. This works on some web browsers.

</TD> - Designates the end of a table data cell.


</TABLE> - Designates the end of a table.

An example table
This is the HTML code using depreciated attributes:
<table cellspacing="5"><tr align="center" bgcolor="#B0B0FF"><td>ROW 1, COL
1</td><td>ROW 1, COL 2</td><td>ROW 1, COL 3</td></tr><tr align="center"
bgcolor="#B0B0FF"><td colspan="3">ROW 2, COL 1-3</td></tr><tr
align="center" bgcolor="#B0B0FF"><td colspan="2">ROW 3, COL 1-
2</td><td>ROW 3, COL 3</td></tr><tr align="center" bgcolor="#B0B0FF"><td
rowspan="3">ROW 4-6, COL 1</tdD><td>ROW 4, COL 2</td><td>ROW 4, COL
3</td></tr><tr align="center" bgcolor="#B0B0FF"><td>ROW 5, COL
2</td><td>ROW 5, COL 3</td></tr><tr align="center"
bgcolor="#B0B0FF"><td>ROW 6, COL 2</td><td>ROW 6, COL
3</td></tr></table>
This is the HTML code using style attributes:
<table cellspacing="5"><tr style="text-align='center'; background-
color='#B0B0FF'"><td>ROW 1, COL 1</td><td>ROW 1, COL 2</td><td>ROW 1,
COL 3</td></tr><tr style="text-align='center'; background-color='#B0B0FF'"><td
colspan="3">ROW 2, COL 1-3</td></tr><tr style="text-align='center';
background-color='#B0B0FF'"><td colspan="2">ROW 3, COL 1-2</td><td>ROW 3,
COL 3</td></tr><tr style="text-align='center'; background-color='#B0B0FF'"><td
rowspan="3">ROW 4-6, COL 1</tdD><td>ROW 4, COL 2</td><td>ROW 4, COL
3</td></tr><tr style="text-align='center'; background-
color='#B0B0FF'"><td>ROW 5, COL 2</td><td>ROW 5, COL 3</td></tr><tr
style="text-align='center'; background-color='#B0B0FF'"><td>ROW 6, COL
2</td><td>ROW 6, COL 3</td></tr></table>
This is how it looks:
ROW 1, COL 1 ROW 1, COL 2 ROW 1, COL 3
ROW 2, COL 1-3
ROW 3, COL 1-2 ROW 3, COL 3
ROW 4-6, COL 1 ROW 4, COL 2 ROW 4, COL 3

ROW 5, COL 2 ROW 5, COL 3


ROW 6, COL 2 ROW 6, COL 3
This table sets the row colors independently for effect rather than setting the
background color for the entire table.
Another example table
This is the HTML code:
<tr><th colspan="3"> This is a list of example Linux commands</th></tr><table
rules="rows"><tr><td nowrap="nowrap">find /home -user mark</td><td
width="20"></td><td>Will find every file under the directory /home owned by the
user mark.</td></tr><tr><td nowrap="nowrap">find /usr -name *spec</td><td
width="20"><td><td>Will find every file under the directory /usr ending in
".spec".</td></tr><tr><td nowrap="nowrap">find /var/spool -mtime
+40</td><td width="20"></td><td>Will find every file under the directory
/var/spool that has data older than 40 days.<td><tr></table>
The HTML attributes, NOWRAP, and WIDTH are depreciated but I can't get the style
attributes of WHITESPACE and BORDER-WIDTH to work here as replacements.
This is how it looks:
This is a list of example Linux commands
find /home -user Will find every file under the directory /home owned by the
mark user mark.
find /usr -name *spec Will find every file under the directory /usr ending in ".spec".
find /var/spool - Will find every file under the directory /var/spool that has
mtime +40 data older than 40 days.

This table uses the nowrap="nowrap" attribute to keep the first cell in each row from
wrapping. It also used a width attribute with value of 20 and no text in the cell to allocate
some blank space between column 1 and column 3.
TBODY Tag
Technically the TBODY tag is to be used one or more times inside each occurance of
the TABLE element. However, in many cases it may not be used. The THEAD and
TFOOT tags may be optionally used one time inside a TABLE element.
HTML Attributes
Common attributes are applicable to many or most HTML elements. These attributes
allow additional setting of style or other characteristics to the element. The attributes
outlined on this page are common in many HTML elements.
ID attribute
Used as a unique identifier for elements for style sheets. In HTML page:
<hr id="firsthr">
In style sheet:
hr#firsthr { color: #80b0ff; height: 15; width: 100% }
CLASS attribute
Used to specify similar attributes for dissimilar elements by putting them in the same
class. In HTML page:
<p class="indent">
In style sheet:
.indent { margin-right: 5%; margin-left: 5%; color: #0000ff }
STYLE attribute
Used to set various element attributes to specific values. Example:
<h1 style="text-align: center">Common Attributes</h1>
TITLE attribute
A tool tip on visual browsers.
LANG attribute
An international attribute which is used to set the international language type.
lang="en"
DIR attribute
An international attribute which is used to set whether text is read left to right or
right to left.
dir="ltr"
Reserved Attributes
There are also reserved attributes used with the following elements. Reserved
attributes may be used to bind HTML documents to XML documents. Elements that
use reserved attributes:
BUTTON
DIV
INPUT
OBJECT
SELECT
SPAN
TABLE
TEXTAREA

The reserved attributes are:


datasrc - Specifies the source of data using a URI.
datafld - Specifies a column or property name.
dataformatas - Specifies how the data is to be formatted with possible values
being "html" or "text".
HTML Formatting
As you may have seen already, there are many ways to format text in HTML. Besides
paragraphs, here are two main commands for managing text in block form.
pre - Used to direct the browser to display a section of text exactly as it is
typed with spaces included.
blockquote - Used to format a block of text as a long quote indented more
than the surrounding text on the left and the right.

The PRE element


PRE element attributes
WIDTH="20" - (Depreciated). The WIDTH attribute specifies the number of
characters across the screen to display. This is very rarely used.

PRE element example


The PRE element is handy for showing program code or part of file content as in this
example. This is the HTML code:
Edit the file "/etc/auto.misc" adding lines like:<pre> cd -fstype=iso9660,ro
:/dev/cdrom fl -fstype=auto :/dev/fd0</pre>
This is how it looks:
Edit the file "/etc/auto.misc" adding lines like:
cd -fstype=iso9660,ro :/dev/cdrom fl -fstype=auto :/dev/fd0
The BLOCKQUOTE element
This element may contain other block elements such as headers , paragraphs,
preformat blocks and tables. It should not be contained inside a paragraph element.
It should not be used to produce indentation. Style sheets should be used possibly
with the CLASS attribute to create indentation. Attribute:
cite="uri" - Specifies the URI of the source of the quote.

BLOCKQUOTE element example


This is the HTML code:
<p>The preamble of the Constitution says:<br></p><blockquote>We the People of
the United States, in Order to form a more perfect Union, establish Justice, insure
domestic Tranquility, provide for the common defence, promote the general Welfare,
and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and
establish this Constitution for the United States of America.</blockquote>
This is how it looks:
The preamble of the Constitution says:
We the People of the United States, in Order to form a more perfect Union, establish
Justice, insure domestic Tranquility, provide for the common defence, promote the
general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity,
do ordain and establish this Constitution for the United States of America.
The following code will produce the same effect using style sheets. In the HTML file:
<p>The preamble of the Constitution says:<BR></p>
<p class="indent">We the People of the United States, in Order to form a more
perfect Union, establish Justice, insure domestic Tranquility, provide for the common
defence, promote the general Welfare, and secure the Blessings of Liberty to
ourselves and our Posterity, do ordain and establish this Constitution for the United
States of America.</p>
In the style sheet:
.indent { margin-right: 5%; margin-left: 5%; color: #0000ff }
HTML Line Formatting
There are several methods of managing lines which are:
BR - Line break. Start a new line.
HR - Used to draw lines across the page

The BR element
An example of use of the BR element
The BR element has no ending tag. Here are two lines as they may be written
without using a <br> tag.
This is line 1.This is line 2.
This is what you would see:
This is line 1. This is line 2.
Here are the same two lines as they are written with a <br> tag.
This is line 1.<br>This is line 2.
This is what you would see:
This is line 1.This is line 2.
The HR element
HR Element Attributes

The HR element has no ending tag.


SIZE=7 - (Depreciated). Sets the thickness or size of the line in pixels.
ALIGN="RIGHT" - (Depreciated). Sets the alignment of the line on the page
to LEFT, RIGHT, or CENTER. The default is CENTER. The alignment is without
purpose if the line width is 100%.
WIDTH="50%" - (Depreciated). Sets the width of the line across the page
as a % or in pixels. The default is 100%.
COLOR="green"; - (Depreciated). Sets the color of the line. It may be
expressed as one of the words, red, blue, green, etcetera, but may also be
expressed in the #RRGGBB color format.
NOSHADE - (Depreciated). A boolean value to set the line to a solid line.

An example using the HR element


Here is how the <hr> tag appears as HTML code:
Above the line.<hr>Below the line.
Here is how it looks:
Above the line.
Below the line.
The line, above, is set according to the defaults or the style sheet associated with
this HTML document. To change its characteristics, I only need to change the style
sheet. Note: Attempting to change the line characteristics using depreciated
attributes such as ALIGN, WIDTH, or COLOR will not override values set by the style
sheet. Only the use of the STYLE attribute will override those values.
Here's a colored line in HTML code (The top coding example uses HTML 3.2 without
embedded style commands and the bottom coding uses HTML 4.01 with embedded
style commands:
<hr size="15" align="left" width="50%" color="blue"><hr style="color: 'blue';
height: '15'; text-align: 'left'; width: '50%'">
Here's how it looks:
http://www.comptechdoc.org/guides/htmlguide/htmlformatline.html (2 of 3)7/21/2003 7:44:55 AM HTML Line Formatting
Here's another colored line in HTML code (The second line uses style commands to
set attributes rather than directly using some of the older attributes that are being
depreciated):
<hr size="15" align="left" width="100%" color="#FF0000"><hr style="height: '15';
text-align: 'left'; color: '#FF0000'; width: '100%'">
Here's how it looks:
Here's a line in white:
Shucks! The background.
HTML Text Formatting
There are many tags used to format text. They are listed below:
<b>..</b> - Sets bold text.
<big>..</big> - Sets larger than normal text.
<em>..</em> - Sets text in italics and denotes emphasis.
<i>..</i> - Sets text in italics.
<small>..</small> - Makes text smaller than normal.
<strike>..</strike> - Draws a line through the text as a "strikeout".
<strong>..</strong> - Same as bold but denotes strong emphasis.
<super>..</super> -Superscript.
<tt>..</tt> - Monospaced typewriter font.
<u>..</u> - Underlined text.
<var>..</var> - Mark a variable.

Examples
Here's the HTML code:
This is an example of the <b>&#60;b&#62; tag </b>.<br>This is an example of the
<big>&#60;big&#62; tag</big>.<br>This is an example of the
<em>&#60;em&#62; tag</em><br>This is an example of the <i>&#60;i&#62;
tag</i>.<br>This is an example of the <small>&#60;small&#62;
tag</small>.<br>This is an example of the <strike>&#60;strike&#62;
tag</strike>.<br>This is an example of the <strong>&#60;strong&#62;
tag<strong>.<br>This is an example of the <sup>&#60;sup&#62;
tag<sup>.<br>This is an example of the <sub>&#60;sub&#62;
tag<sub>.<br>This is an example of the <tt>&#60;tt&#62; tag<tt>.<br>This is an
example of the <u>&#60;u&#62; tag</u><br>This is an example of the
<var>&#60;var&#62; tag</var><br>
Here's how it looks:
This is an example of the <b> tag.This is an example of the <big> tag.This is an
example of the <em> tag.

This is an example of the <i> tag.This is an example of the <small> tag.This is an


example of the <strike> tag.This is an example of the <strong> tag.This is an
example of the <sup> tag.This is an example of the <sub> tag.This is an example of the
<TT> tag.This is an example of the <u> tag.This is an example of the <var> tag.
Other tags associated with text are:
ABBREV - Denotes an abbreviation
ACRONYM
AU - Author
CODE - Denotes program code and should be set in the same format as the
PRE tag, but does not work either with all browsers or all HTML versions.
DEL - Denotes deleted text.
DFN - Denotes the definition of a term
INS - Denotes inserted text
KBD - Text to be typed at the keyboard, such as a computer command. The
test is displayed in a mono spaced format.
PERSON
Q - Quotation.
SAMP - Denotes sample text.

Each of these tags require an ending tag.


The FONT tag
The font element is being depreciated and replaced by style sheet attributes.
The <FONT> element is used to set a section of text with a specific font. It uses the
<FONT> tag to begin and the </FONT> for the end tag.
FONT Attributes and Tags
<FONT> - Begins the FONT element. SIZE="4" - Sets the font size using a
value, between 1 and 7. The default value is 3. It can be specified with a "+n" value
to set the size relative to the current size.

COLOR="blue" - Sets the text color.


FACE="roman" - The font name to be used. If there is more than one font
name separated by commas the first font that can be found is used.

</FONT> - Ends the FONT element.


<BASEFONT> - Used to set the default font size on the current page.
SIZE="2" - Specifies default font size with a value between 1 and 7.
HTML SPAN and DIV Elements
There are a few elements that support additional formatting capabilities both for
inline elements and block elements. These include the DIV and SPAN element. The
SPAN element is used in line with text to modify the characteristics of a small section
of text. The DIV element is very useful for adding certain block element style
characteristics to inline or non-block elements.
The DIV Element
This element is useful for adding style to elements that cannot have specific
characteristics set otherwise without using depreciated attributes. For example, the
CENTER element is being depreciated in HTML 4.0, and there is no inline element
attribute in style sheets that allows the inline elements such as anchors and images
to be centered. Therefore the anchor code that follows is not centered.
Here is the code:
<a href="index.html" target="_top">HTML Guide Contents Page</a>
Here is the effect:
HTML Guide Contents Page
The following code centers the anchor:
<div class="center"><a href="index.html" target="_top">HTML Guide Contents
Page</a></div>
Here's the effect:
HTML Guide Contents Page
What is shown here is a simple, short example. Of course the came effect can be
obtained by placing the anchor inside a paragraph element and setting the "text-
align" value to "center", however the DIV element can be used to apply attributes to
larger sections of the HTML page. Several paragraphs, headers, and lists may be
contained inside the DIV element which is not possible using the paragraph
elements.

The SPAN Element


The SPAN element does not have any unique attributes, only the common attributes.
This is HTML code for an unordered list showing how to make the text and bullets a
different color using the SPAN element.
<ul style="color: 'red'"><li><span style="color: 'green'">Line 1</span><li><span
style="color: 'green'">Line 2</span><li><span style="color: 'green'">Line
3</span></ul>
This is how it looks:
Line 1
Line 2
Line 3

This is the HTML code for a paragraph demonstrating use of the STYLE attribute
along with the SPAN element.
<p style="text-align: 'center'; font: '16pt courier'; color: 'blue'">The color of the sky
is blue, but if you look at the <span style="color: 'green'">trees, they are
green</span>. This effect is produced using the &#60span&#62 element with the
style ="color: 'green'" attribute set.</p>
Here is how it looks:
The color of the sky is blue, but if you look at the trees, they are green. This effect is
produced using the <span> element with the style ="color: 'green'" attribute set.
HTML Characters
There are some characters in HTML that must be displayed using a string of
characters. The string may be a name string or numeric string as in the table below.

Character Description Name string Numeric string


& Ampersand &amp; &#38;
© Copyright &copy; &#168;
" Quotation &quot; &#34;
> Greater than &gt; &#62;
< Less than &lt; &#60;
¢ Cent &cent; &#162;
£ Sterling pound &pound; &#163;
° Degree sign &deg; &#176;
® Trademark sign &reg; &#174;
± Plus/minus signs &plusmn; &#177;
× Multiply sign &#215;
÷ Divide sign &#247;
¦ Broken vertical bar &brvbar; &#166;
§ Section sign &sect; &#167;
¹ Superscript 1 &sup1; &#185;
² Superscript 2 &sup2; &#178;
³ Superscript 3 &sup3; &#179;
½ 1/2 fraction &frac12; &#189;
¼ 1/4 fraction &frac14; &#188;
¾ 3/4 fraction &frac34; &#183;
Æ Capital AE &AElig; &#198;
æ Small AE &aelig; &#230;
É Capital E accented &Eacute; &#201;
é Small e accented &eacute; &#233;

Although these special characters may displayed without the semicolon at the end, it is the
proper standard to use the semicolon.
Style Sheets
Purpose of Style Sheets
The purpose of style sheets is to separate the content of the HTML documents from
their style. This makes control over the style much easier and group efforts easier
since content of an entire set of HTML pages can be easily controlled using one or
more style sheets.
STYLE sheets or the inline STYLE element will allow you to set custom margin sizes,
and the text font, color and sizes of various elements that are used on your web
page. Size of margins can be set in inches (in), pixels(px), percentages (%),
centimeters (cm) or the (em). The unit of em is the em is the height of the font. Two
em units is twice the height of the font. When the em units are used, everything is
scaled relative to the font so the scaling will remain the same regardless of the font
used.
Methods of Including Style
Methods of including style content in an HTML document:
Embedding - Use the STYLE element in the HEAD element to create a style
sheet that is embedded in the header. Example: <style type="text/css"
MEDIA=screen><!-- body {background-color: "#ffffff"; color: "#000000";
background: url('../../../../gifs/flowers.gif') } a:link { color: "#0000ff" } a:visited {
color: "#7f007f" } a:active { color: "#ff0000" } h3 { color: "#600060" }--></style>
Linking - Use the link element in the HTML header to link an external text file
style sheet to the HTML document. Example: <link href="style.css" rel="stylesheet"
type="text/css">
Importing - One style sheet may be imported from another by using the
"@import" command in

the style sheet that is performing the import.


Inline - Style information may be included with each individual element using
the STYLE attribute which is common to all elements. See the "Common Attributes"
section. Many examples in this document show style being controlled using the
STYLE attribute. Although this is acceptable for specific elements whose
characteristics must be different such as the color of a horizontal line, it is wiser to
control most element style using the external style sheets.

The STYLE Element


Attributes:
Type - Defines the content type such as "text/css".
Media - Defines the intended media the page will be displayed on. Values
include all, aural, braille, handheld, print, projection, screen, tty, and tv.
Title - Gives the title sheet an optional title.

Example Embedded Style Sheet


When setting document style, place the STYLE element with the <STYLE> beginning
tag and </STYLE> ending tag between the HEAD and the BODY elements. Therefore
placement would be as follows:
<html><head><title>Example Style Settings</title></head><style
type="text/css"><!-- body {background: #FFFFFF; color: #000000; margin-top:
6%;margin-left: 3%; margin-right: 3%}h1 {font: 14pt ariel; color: #0000FF}h2,
h3, h4 {margin-left: -3%}p {font: 12pt roman; text-indent: 0.5in}a {color:
#00FF00; text-decoration: none}--></style>
Other settable parameters include:
font-style: italic
font-weight: bold
font-size: 200% - Indicates twice the size of normal text.
font-family: roman, serif, "Times New Roman"
text-transform: uppercase
background-color: blue

The section "CSS Properties" contains a more complete list of parameters and the
elements they work with.
Setting an HTML Page with a Style Sheet
To set an HTML page up to use a style sheet, a link must be provided in the header
section as follows:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"><html><head><meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1"><meta name="GENERATOR"
content="Arachnophilia 3.9"><meta name="description" content="The Computer
Technology Documentation HTML Guide - Setting Document Style"><meta
name="keywords" content="Documentation, HTML, html document style, style,
setting document style, setting html document style"><title>The CTDP HTML Guide
- Setting Document Style</title><link href="style.css" rel="stylesheet"
type="text/css"></head><body>...</body>
The Style Sheet File (style.css)
body {background-color: #ffffff; color: #000000; background:
url('../../../../gifs/flowers.gif') }a:link { color: #0000ff }a:visited { color: #7f007f }
a:active { color: #ff0000 }h1, H2 { text-align: center }h3 { color: #600060
}blockquote { color: #0000ff }pre { color: #0000ff }.indent { margin-right: 5%;
margin-left: 5%; color: #0000ff }.center { text-align: center }.firstindent { text-
indent: 2em}div.outline { border-top: solid medium navy }hr { color: #80b0ff;
height: 5; width: 50%; text-align: center }hr#firsthr { color: #80b0ff; height: 15;
width: 100% }
This style sheet is used to set the style for various HTML elements on every page of
this document. To change the style, only the style sheet needs to be changed. Note
that the style sheet sets the wallpaper for the HTML page along with the background
color, foreground color, active link color, visited link color, and unvisited link
color(A:link). It also sets colors for the BLOCKQUOTE and PRE elements along with
defining some CLASS characteristics and one ID characteristic.
Using the CLASS Attribute
The CLASS and ID attributes allow very convenient and precise control of the style of
specific elements in HTML documents. The CLASS attribute allows attributes to be
assigned to almost any element based on a class name. Class style information is
specified in the style sheet with the period, ".", followed by the class name as in the
following example:
.indent { margin-right: 5%; margin-left: 5%; color: #0000ff }
Note that this same line is used in the example style sheet above. To use this in the
HTML file, when the beginning tag of the element is declared, the class is specified as
in the following statement:
<p class="indent">
This causes the paragraph element to have the style characteristics assigned to the
class "indent" so long as those style characteristics are appropriate to the element
they are being applied to. In this case the paragraph element is indented much like
the blockquote element and its color is also set to blue. Classes may also be
assigned to specific elements so they can only be used with that elements.
Assingments in the style sheet to specific elements similar to "PRE.center { text-
align: center }".

Using the ID Attribute


The ID attribute is useful since it allows you to specify exactly which element will
have the desired style. This is done with a line like the following as shown in the
style sheet example above.
hr#firsthr { color: #80b0ff; height: 15; width: 100% }
When the first horizontal line is declared on the HTML page it is declared as follows:
<hr id="firsthr">
The line for the code in this example is at the top of this page. All other lines on the
page appear as defined by the following entry from the above style sheet:
hr { color: #80b0ff; height: 5; width: 50%; text-align: center }
The line appears below and in several other places on this page. Please note that ID
selectors are not required to be associated with a specific element in the style sheet
although I think it makes more sense to do so.
Context Selection
Allows elements containing inline elements to have special assigned values as in the
following example:
table b ( color: red }
This example sets the color of any bold text in a table to red.
Grouping Elements for Style Characteristics
The example above contains the following line:
h1, h2 { text-align: center }
This line allows style characteristics to be assigned to both elements H1 and H2 at
the same time. The elements are separated by commas.

Pseudo Classes
Some elements have specific automatially assigned classes. For example the anchor
(A) element has the classes link, visited, and active. The following lines in the style
sheet assign color style characteristics to these classes.
a:link { color: #0000ff }a:visited { color: #7f007f }a:active { color: #ff0000 }
Note that the element is separated from the pseudo name using a colon. Also a
"first-line" and a "first-letter" pseudo class exists for each block element.
CSS Properties
This section only provides a quick reference for the CSS properties, for complete
details refer to the Web Design Group's web page CSS section.
Application of these properties are based on the element type as described earlier in
the "Element Categories" section.
Box Properties
Name Description Possible Element Example inherited
Values Types
border Sets border See border All {border: No
width, style and width, style, medium solid
color. and color green}

border- Set the bottom See border All {border- No


bottom border width width, style, bottom:
style, and color. and color medium solid
green}

border- Set the bottom thin, All {border- No


bottom- border width medium, bottom-
width thick, or width: thin}
length value
border- Set the border A color value, All {border: No
color color color, #0000ff}
#RRGGBB
border- Set the left See border All {border-left: No
left border width width, style, medium solid
style, and color. and color green}

border- Set the left thin, All {border-left- No


left-width border width medium, width: thin}
thick, or
length value
border- Set the right See border All {border- No
right border width width, style, right:
style, and color. and color medium solid
green}
border- Set the right thin, All {border- No
right- border width medium, right-width:
width thick, or thin}
length value
border- Sets border style none, dotted, All {border: No
style dashed, dashed}
solid, double,
groove,
ridge, inset,
outset

border- Set the top border See border All {border- No


top width style, and color. width, style, top:
and color medium
solid
green}
border- Set the top border thin, All {border- No
top- width medium, top-width:
width thick, or thin}
length value
border- Sets Border width. thin, All {border- No
width medium, width: 8}
thick, or
length value
clear Determines where none, left, All {clear: No
floating elements are right, both left}
allowed.

float Specifies how text is none, left, All {float: No


wrapped and where it right left}
is aligned.

height Height of element auto or a Block elements {height: No


height value and IMG, 200}
INPUT,
TEXTAREA,
SELECT, and
OBJECT

margin Set element margin auto, length All {margin: No


width. A single value value, or 4em 2em
sets all margins, two percent value 4em 2em}
values set top and
bottom, four values
set top, right, bottom,
and left margins.

margin- Set element bottom length value, All {margin- No


bottom margin or percent bottom:
value 4em}
margin- Set element left length value, All {margin- No
left margin or percent left: 4em}
value
margin- Set element right length value, All {margin- No
right margin or percent right:
value 4em}

margin- Set element top margin length value, All {margin- No


top or percent top: 4em}
value
padding Space between border length value, All {padding: No
and content. A single or percent 4em}
value sets all sides, value
two values set
top/bottom and
left/right, three values
set top, right/left, and
bottom, and four
values set top, right,
bottom, and left.

padding- Space between bottom length value, All {padding- No


bottom border and content. or percent bottom:
value 4em}

padding- Space between left length value, All {padding- No


left border and content. or percent left: 4em}
value
padding- Space between right length value, All {padding- No
right border and content. or percent right:
value 4em}

padding- Space between top length value, All {padding- No


top border and content. or percent top: 4em}
value
width Width of element auto or a Block {width: No
height value elements and 40em}
in length or IMG, INPUT,
percentage TEXTAREA,
SELECT, and
OBJECT

Background and Color Properties


Name Description Possible Values Element Types Example inherited
background Set See All {background: #8080ff} No
background background-
color, color,
repeat, background-
image, image,
attachment, background-
or position. attachment,
background-
repeat,
background-
position

background- Determines scroll, fixed All {background-attachment: No


attachment if the scroll}
background
image is
fixed or
scroll.
background- Sets the Named or All {background-color: #8080ff} No
color background value color
color.

background- Sets the url All {background-image: No


image background url('../../../../gifs/flowers.gif')}
image.

background- Sets the top, center, Block and {background-position: left No


position background bottom, left, IMG, top}
image center, INPUT,
initial right, or TEXTAREA,
position. percent SELECT,
values and
OBJECT
background- Sets how repeat, All {background-repeat: no- No
repeat the repeat-x, repeat}
background repeat-y,
image is no-repeat
repeated.
color Sets Named or All {color: green} Yes
element value color
color.
Classification Properties
Name Description Possible Element Example inherited
Values Types

display Sets the type of block, inline, All {display: No


element. list-item, none list-item}

list-style Sets list style type See list-style-type List- {list-style: Yes
and/or position. and list-style- item circle}
position

list-style- Sets image to be url List- {list-style- Yes


image used as the list item image:
item marker. url(this.gif)}

list-style- Sets list style circle, disc, List- {list-style- Yes


type type. decimal, lower- item type: square}
alpha, lower-
roman, none,
square, upper-
alpha, upper-
roman

list-style- Sets where the inside, outside List- {list-style: Yes


position marker is place item circle}
relative to the text
and its wrapping
position.

whitespace Sets treatment of normal, pre, Block {whitespace: Yes


spaces inside the nowrap pre}
element.

Font Properties
Name Description Possible Values Element Example inherited
Types
font Used to define See font-family, All {font: Yes
font properties font-size, font-style, 20pt}
font-variant, and
font-weight.

font- Used to define family name All {font- Yes


family font family to family:
use ariel
roman}
font- Used to define xx-small, x-small, All {font-size: Yes
size font size to small, medium, 18pt}
use large, x-large, xx-
large, larger,
smaller, length
value, or percent
value

font- Used to define font normal, italic, oblique All {font-style: Yes
style style to use italic}

font- Used to determine normal, small-caps All {font- Yes


variant whether to use variant:
normal or small caps small-caps}

font- Sets font weight. normal, bold, bolder, All {font- Yes
weight lighter, 100, 200, 300, weight:
400, 500, 600, 700, 800, 600}
900

Text Properties
Name Description Possible Element Example inherited
Values Types
letter- Sets the space normal or All {letter- Yes
spacing between length value spacing:
characters. 0.2em}
line-height Sets the height normal, a All {line- Yes
of lines. number, a height: 2}
percent of the
element font
size,
text-align Sets the left, right, Block {text-align: Yes
alignment of center, justify center}
text.
text- Sets the none, overline, All {text- No
decoration special underline, line- decoration:
decoration through, blink blink}
attributes of
text.
text- Sets the length or Block {text- Yes
indent element's first percentage indent: 5%}
line amount of value
indentation.
text- Transforms none, All {text- Yes
transform text to one of capitalize, transform:
the set values. uppercase, uppercase}
lowercase
vertical- Sets vertical baseline, sub. Inline {vertical- No
align position. super, top, align: sub}
middle, bottom,
text-top, text-
bottom, or
percent value

word- Sets extra normal or All {word- Yes


spacing space between length value spacing:
words. 0.2em}
HTML Graphics
The <IMG> tag is used to embed graphics in HTML pages. They may be embedded
inside other elements such as anchors. When embedded inside an anchor, then the
user left clicks on the image, they will go to the designated link (rather, their
browser will load a file from the designated link). The <IMG> element has no ending
tag.
IMG Attributes
SRC="../greenhomebutton.gif" - The path and filename of the image which
specifies its location.
ALT="Home" - This is a message displayed if the image could not be found.
ALIGN="TOP" - (Depreciated). Sets the image alignment. The image is
aligned to the left or right column if the value is LEFT or RIGHT,The values, TOP,
MIDDLE, BOTTOM, ABSMIDDLE, and ABSBOTTOM, set the vertical alignment with
items in the same line.
VSPACE=3 - (Depreciated). The space between the image and the text
above and below it in pixels.
HSPACE=5 - (Depreciated). The space between the image and the text to
the left and right of it in pixels.
BORDER=10 - (Depreciated). Sets a border of the specified width in pixels
to be drawn around the image.
HEIGHT=33 - The height of the image. If this is not specified, the image will
be the size as determined by the gif file. This can be set in pixels or a percentage of
the browser window height.
WIDTH=115 - The width of the image. If this is not specified, the image will
be the size as determined by the gif file. This can be set in pixels or a percentage of
the browser window width.
ISMAP - Identifies the image as an image map. The image map lets the user
point and click different parts of the image to load other web pages.
USEMAP - Specifies the client side image map file to be used.

The line break element, <BR> and the horizontal rule element <HR> may be placed
inside the <IMG> element.
Example 1
The following code will display a gif file:
<img src="MyPicture.gif" alt="Outdoor Scene">
This code sets an alternate text of "Outdoor Sceen" in the event the "MyPicture.gif"
file is not
displayable. This usually occur if it cannot be found or if the user has their browser
controls set not to display pictures.
Example 2
In this example the additional feature is added that sets the size of the picture
relative to the size of the browser window. The size of the picture is set to 20% of
the height of the browser window and 40% of the width.
<img src="MyPicture.gif" alt="Outdoor Scene" height="20%" width="40%">
Example 3
If you are interested in displaying pictures that are of significant size which may be
accessed for possible download for sharing with friends or family, this example gives
some valuable advice. If you are interested in making several graphic files
accessable from one page such as files scanned from pictures, it would be worthwhile
to make a file of about one fifth the height and width of the original file, then make it
a link to the original file for viewing or download. This is because the download time
of your web page with many large graphic files may be excessive. In this example
two smaller files are placed on a page next to each other. These files are links to the
larger files to be viewed or downloaded.
<div style="text-align: center"<a href="Picture1.gif"><img src="SmallPicture.gif"
ALT="Picture1" height="20%" width="40%"></a><a href="Picture2.gif"><img
srcC="SmallPicture2l.gif" ALT="Picture2" height="20%" width="40%"></a></div>
In this example the style attribute "text-align: center" is set. See the section on style
and style sheet attributes for more information about this attribute.
Example 4
In this example some JavaScript code is added so the name or description of the
picture is displayed when the viewer places their mouse cursor on the link.
<div style="text-align: center"><a href="Picture1.gif"
onMouseOver="window.status='Picture1' ;return true"
onMouseOut="window.status='';return true"><img src="SmallPicture.gif"
alt="Picture1" height="20%" width="40%"></a><a href="Picture2.gif"
onMouseOver="window.status='Picture2' ;return true"

onMouseOut="window.status='';return true"><img src="SmallPicture2l.gif"


alt="Picture2" height="20%" width="40%"></a></div>
Example 5
The following code will display a linked image that will return you to the HTML start
section:
<div style="text-align: center"><a href="htmlintroduction.html" target="right"
onMouseOver="window.status='To The HTML Start (intro) Page' ;return true"
onMouseOut="window.status='';return true"><img SRC="bluestartbutton.gif"
alt="Home" vspace="3" border="3" height="35" width="120"></a></div>
This is the result:
Image areas and Maps
To use a web browser to click on various areas of an image file and go to a specific
web page depending on the area clicked upon requires the use of the <MAP> and
<AREA> elements. The <MAP> element has an ending tag, </MAP> while the
<AREA> element does not.
MAP and IMAGE Tags and Attributes
<MAP> - Starts a client-side image map. This must be referenced in an image
<IMG> tag. This element will include <AREA> tags.
</MAP> - Ends the image map element.
<AREA> - Defines areas of an image map that the user may click on to
establish a link. SHAPE=RECT - Defines the shape of the click able area. Valid values
are POLY, RECT, and CIRCLE.
COORDS="2,50,102,101" - Defines, in pixels, the top-left and bottom-right
coordinates of the clickable linked region in the image.
HREF="leftwing.htm" - Defines the location of the web page that is loaded
when the area in the image is clicked.
Example Code
<img src="airplane.gif" ismap usemap="#airplane.map"></a> <map
name="airplane.map"><area shape="rect coordsS="2,50,102,101"
HREF="leftwing.html"><area shape="rect" coords="110,10,160,300"
HREF="fusalage.html"> <area shape="rect" coords="162,50,262,101"
HREF="rightwing.html"> </map>

HTML Sound
The BGSOUND element is used to play sounds on a web page. There is no end tag
for the <bgsound> element. To play sounds all that is required is to put a line like
the following on your web page:
<bgsound src="1234usmc.wav" loop="-1">
This line is used on this page to play sound.
BGSOUND element attributes
SRC="1234usmc.wav" - The location or the URL of the WAV, MIDI, or AU file
to play.
LOOP="-1" - The number of times the file will will loop. A value of INFINATE
or -1 will loop indefinitely.
HTML Links
HTML Anchors and Links
Anchors are used to specify link locations or to set anchors for locations to link to.
This enables the person using the browser to click on a link (anchor) and their
browser will go to the location pointed to by the anchor. Anchors begin with the <A>
tag and end with the </A> tag.
Anchor Attributes
NAME - Sets an anchor at a named location in the document for later use by
an anchor tag.
HREF="hw.html" - A hypertext reference which defines the name of the
document or the named location in the document for the anchor link to send the web
browser to.
TARGET - Specifies the frame target the referenced page will be put into. The
target may me a named window or one of the special reserved names below. If the
target is a named window that exists the web page the link points to will be loaded
into that window. If a window by that name does not exist, a new window with that
name will be created. _blank - The web linked page loads in a new window and does
not name the window.
_parent - The new page will load in the parent frame or window.
_self - The new page will load in the same window that the link is in. If the
link is in a frame, it will load inside the frame. This is the default target.
_top - The new page will load into the top window reguardless of how many
framesets deep the link is embedded.

Examples
Example 1 - Named Anchor
At the top of this page is a named anchor which is used for other examples on this
page. Its text is:
<a name="top"></a>
Example 2 - Link to another page

This is an example of HTML source code using an anchor link:


<a href="htmlintroduction.html" target="right">Introduction</a>
Here is how it looks:
Introduction
It will take you to the introduction page if you click on it.
Example 3 - A Mail Link
This example shows how to set up a mail link that invokes the installed mail program
when it is clicked on. Here's the source code:
<a href="mailto: ctdp@operamail.com">ctdp@operamail.com</a>
Below is the implemented example. If you click on it it should invoke your mail
program such as Microsoft Outlook so you can send an e-mail. Feel free to click on it
to see the effect. You can send an e-mail telling us that the example worked or exit
the e-mail program.
ctdp@operamail.com
Example 4 - Image Link
This is an example of HTML source code using an anchor link with a button image
embedded (It also includes some JavaScript):
<a href="htmlgraphics.html" target="right" onMouseOver="window.status='To
graphics page' ;return true" onMouseOut="window.status='';return true"<>img
src="bluestartbutton.gif" alt="Graphics" vspace="3" border="0" height="35"
width="120"></a>
Here's how it looks and works:

It will take you to the graphics page of this document. The JavaScript part includes
the "onMouseOver" and onMouseOut" definitions. They are event handlers for the
MouseOver and MouseOut events. The "window.status" definition is an attribute of
the window object. You can read about JavaScript in the JavaScript Manual.
Example 5 - Local Page Link
Here's an example of HTML source code that will take you to the top of the page:
<a href="#top">Take me to the top of this page.</a>
Here's how it looks and works:
Take me to the top of this page.
Example 6 - Non-Underlined Link
Here's an example of HTML source code that will take you to the top of the page, but
it is not underlined:
<a href="#top" style="text-decoration: none" >Take me to the top of this
page.</a>
Here's how it looks and works:
Take me to the top of this page.
Example 7 - Hidden Link
Here's an example of HTML source code that will take you to the top of the page, but
it is not underlined, nor is the color changed for a normal link color. It is also
embedded with other text to make it harder to find. This link is essentially hidden
and can only be found by placing the mouse directly over

the link.
Take me to the <a href="#top" style="text-decoration: none" style="color='black'"
>top</a> of this page.
Here's how it looks and works:
Take me to the top of this page.
Example 8 - Target set to top
Take me to the <a href="index.html" target = "_top">main HTML</a> page.
Here's how it looks and works:
Take me to the main HTML page.
Example 9 - Target set to self
Take me to the <a href="index.html" target = "_self">main HTML</a> page.
Here's how it looks and works (Use the BACK button on your browser to return):
Take me to the main HTMLpage.
Example 10 - Target set to blank
Take me to the <a href="index.html" target = "_blank">main HTML</a> page.
Here's how it looks and works:
Take me to the main HTML page.
If you continue clicking on this link, it will continue making new pages.
HTML Forms
Forms allow those who come to your website to provide input to your webserver.
Some reasons to use forms are to allow visitors to partake in polls or sign up as a
member. Also orders for merchandise may be placed using forms. Usually the forms
are supported by a client side script program which will be sure the form is properly
filled out before it is sent to the server. Also the form will invoke a script program
which runs on the server. This script program will receive the data and store it on
the server, then respond with a message to the user telling them that the form was
submitted.
This document is not intended to teach script writing, so it will concentrate on the
HTML side of form writing.
Form tags and attributes
<FORM> - Starts an input form. </FORM> - Ends an input form.
ACTION="..." - The address of the script to process this form input.
METHOD="POST" - The method used to send the data from the form to the
server. The options are POST and GET. Normally POST is used.

<BUTTON> - Used to define a FORM submit, reset, or push button.


</BUTTON> - Ends the button. Attributes: ACCESSKEY - A shortkey used to give the
focus to the label.
DISABLED - A boolean value that makes the button unavailable for use.
NAME - Sets the name sent to the server as part of the name/value pair when
the form is submitted.
ONBLUR - Sets a script program to run when the element loses focus.
ONFOCUS - Sets a script program to run when the element gets focus.
TABINDEX - Sets the tabbing order of the element.
TYPE - Sets the button type to one of submit, reset, or button.
VALUE - Sets the value of the button to be sent to the webserver when the
form is submitted.

<FIELDSET> - Allows grouping of form controls. </FIELDSET> ends the fieldset.


<INPUT> - An input element for a form. ACCEPT - The acceptable media
types for file upload.
ACCESSKEY - A shortcut character.
ALIGN="CENTER" - (Depreciated). Sets the way the text and image will
align.
ALT - Alternate text for the image.
CHECKED - This indicates that the item is checked is it is a check box or radio
button.
DISABLED - A boolean value that makes the input object unavailable for use.
MAXLENGTH="7" - The most characters that may be put in a text region.
NAME="RegForm" - The name of the form which is passed to the script
running on the server.
ONBLUR - Sets a script program to run when the element loses focus.
ONCHANGE - Script to run when the element is changed.
ONFOCUS - Sets a script program to run when the element gets focus.
ONSELECT - Script to run when the element text is selected.
SIZE="3" - The number of characters an input region should be filled with.
SRC="bluebutton.gif" - The name of the source file for an image to be
displayed on the form.
TABINDEX - Sets the tabbing order of the element.
TYPE="TEXT" - The type of input to be done. The options are BUTTON,
CHECKBOX, FILE, HIDDEN, IMAGE, RADIO, RESET, SUBMIT, PASSWORD, or TEXT.
VALUE="1" - Specifies the default value for a text item. It specifies the label
of a reset or submit button or the value to be returned when a check box or radio
button is selected.

<LABEL> - Allows an ability to click on a text label to select a form control.


<.LABEL> ends a label. Attributes: ACCESSKEY - A shortkey used to give the focus
to the label.
FOR - Sets the control associated with the label which ust match the control
name.
ONBLUR - Sets a script program to run when the element loses focus.
ONFOCUS - Sets a script program to run when the element gets focus.

<TEXTAREA> - Indicates an element that has multiple text lines.


</TEXTAREA> - Ends a Text entry form element. Attributes: ACCESSKEY - A
shortkey used to give the focus to the element.
COLS="3" - The number of columns in the text area.
NAME="AddressLines" - The name of the textarea which is passed to the
script running on the server.
ONBLUR - Sets a script program to run when the element loses focus.
ONCHANGE - Script to run when the element is changed.
ONFOCUS - Sets a script program to run when the element gets focus.
ONSELECT - Script to run when the element text is selected.
ROWS="3" - The number of rows in the text area.
TABINDEX - Sets the tabbing order of the element.

<SELECT> - Creates a list of items that can be selected. </SELECT> ends the
select area. Attributes: DISABLED - A boolean value that makes the select object
unavailable for use.
MULTIPLE - Allows more than one selection from the scrolling list.
NAME="state" - The name of the selection item that is passed to the script
running on the server.
ONBLUR - Sets a script program to run when the element loses focus.
ONCHANGE - Script to run when the element is changed.
ONFOCUS - Sets a script program to run when the element gets focus.
ONSELECT - Script to run when the element text is selected.
SIZE="1" - The number of selections that will be displayed. If a value of SIZE
is set, the selection will be a scrolling list. If no SIZE value is set the selection will be
a pop-up menu.
http://www.comptechdoc.org/guides/htmlguide/htmlforms.html (2 of 6)7/21/2003 7:45:08 AM HTML Forms
TABINDEX - Sets the tabbing order of the element.

<OPTGROUP> - Sets up choices inside a SELECT menu. </OPTGROUP> ends


the group. Attributes: DISABLED - A boolean value that makes the object
unavailable for use.
LABEL - Describes available choices.

<OPTION> - Used to set items in a list of selectable items. </OPTION> ends


the OPTION element. This is found within the SELECT element. DISABLED - A
boolean value that makes the object unavailable for use.
LABEL
SELECTED - This will be the default value if this attribute is included in the
OPTION element
VALUE="10" - This is the value to be submitted to the CGI script program if
this option is selected when the user submits the form.

An example Form
<h2 style="text-align: center">Computer Technology Documentation
Project</h2><h2 style="text-align: center">Member Registration</h2><hr
style="height: 5" WIDTH=90%> <div style="text-align:
center"><table><td><pre><form name="RegistrationForm" method="post"
action="/cgi-bin/response.pl"><b>First Name: </b><input type="text"
name="firstname"><b>Last Name: </b><input type="text"
name="lastname"><b>Address1: </b><input type="text"
name="addr1"><b>Address2: </b><input type="text" name="addr2"><b>City:
</b><input type="text" name="city"><b>State: </b><select name="state"
size="1"> <option value="1">AL <option value="2">AK <option value="3">AR
<option value="4">AS <option value="5">AZ <option value="6">CA <option
value="7">CO <option value="8">CT
<option value="9">DC <option value="10">DE <option value="11">FL <option
value="12">FM <option value="13">GA <option value="14">GU <option
value="15">HI <option value="16">ID <option value="17">IA <option
value="18">IL <option value="19">IN <option value="20">KS <option
value="21">KY <option value="22">LA <option value="23">MA <option
value="24">MD <option value="25">ME <option value="26">MH <option
value="26">MI <option value="28">MN <option value="29">MO <option
value="30">MP <option value="31">MS <option value="32">MT <option
value="33">NC <option value="34">ND <option value="35">NE <option
value="36">NH <option value="37">NJ <option value="38">NM <option
value="39">NV <option value="40">NY <option value="41">OH <option
value="42">OK <option value="43">OR <option value="44">PA <option
value="45">PR <option value="46">PW <option value="47">RI <option
value="48">SC <option value="49">SD <option value="50">TN <option
value="51">TX

<option value="52">UT <option value="53">VA <option value="54">VI <option


value="55">VT <option value="56">WA <option value="57">WI <option
value="58">WV <option value="59">WY</select><b>Zip: </b><input type="text"
name="zip" maxlength="10" size="10"><b>Area Code/Phone:</b><input
type="text" name="code" maxlength="3" size="3"><input type="text"
name="phone" maxlength="7" size="7"><div style="text-align: center"><input
type="button" name="cmdSubmit" value="Submit"> <input type="reset"
value="clear"></div></pre></form></td></table></div></body>

How the Form Looks:


Computer Technology Documentation Project
Member Registration
First Name: Last Name: Address1: Address2: City: State: Zip: Area
Code/Phone:
HTML Script Embedding
This document is not intended to teach script writing, but will only define some of the
related tags and give an example script so the user can get an idea how to embed
script in HTML. This document also does not explain how to get information entered
in a script form to the server. That is a subject that will be described when the hyper
text transfer protol (HTTP) and server side script writing is discussed.
The script below will check inputs from the form, below, to be sure they have been
entered correctly before sending the data to the server. If you attempt to press
submit in the form below without filling the appropriate fields in, you will see that the
script is active.
SCRIPT Element Attributes
The script element is usually embedded in the document header but may be placed
in the head or the body of the HTML document so long as it occurs before code that
invokes it.
CHARSET - (Depreciated). The encoding of any external script specified such
as "iso-8859-1".
DEFER - (Depreciated). The script is not parsed until the HTML document is
rendered.
EVENT - Specifies the event used to trigger the script.
FOR - Specifies an object (combined with an action) that is used to trigger the
script event
LANGUAGE - (Depreciated). Tells the name of the language the script is
written in. Required for most browsers. Possible values are JavaScript, VBScript, and
JavaScript1.1
SRC - (Depreciated). Specifies an external script which may include a URL
path to another webserver.
TYPE - The new method to specify the script language using MIME
specification rather than the LANGUAGE attribute. This attribute is not widely
supported yet.

The NOSCRIPT element is used to provide alternate content when a browser does
not support script.
Scripting Events
ondblclick
onclick
onkeydown
onkeypress
onkeyup
onmousedown
onmousemove
onmouseout
onmouseover
onmouseup

An example Script
How the script looks:
<!doctype html public "-//w3c//dtd html 4.0 transitional//en"><head><title>New
CTDP Member Registration</title><scrypt type="text/javascript" for="cmdSubmit"
event="onclick" language=JavaScript><!--var MemSubForm;MemSubForm =
document.RegistrationForm;if (MemSubForm.firstname.value.length == 0) {
MemSubForm.firstname.value = prompt("Please enter your first name."); if
(MemSubForm.firstname.value.length != 0) MemSubForm.lastname.focus();}if
(MemSubForm.lastname.value.length == 0) { MemSubForm.lastname.value =
prompt("Please enter your last name."); if (MemSubForm.lastname.value.length !=
0) MemSubForm.addr1.focus();}if (MemSubForm.addr1.value.length == 0) {
MemSubForm.addr1.value = prompt("Please enter your address."); if
(MemSubForm.addr1.value.length != 0) MemSubForm.addr1.focus();}if
(MemSubForm.city.value.length == 0) { MemSubForm.city.value = prompt("Please
enter your city of residence.");

if (MemSubForm.city.value.length != 0) MemSubForm.city.focus();}if
(MemSubForm.state.value == 0) { alert("Please select a 2-letter state
abbreviation."); MemSubForm.state.focus();}else if (MemSubForm.code.value.length
!= 3 || isNaN(MemSubForm.code.value)) { alert("Please enter a valid telephone area
code."); MemSubForm.code.focus(); MemSubForm.code.select( );}else if
(MemSubForm.phone.value.length != 7 || isNaN(MemSubForm.phone.value)) {
alert("Please enter a valid phone number."); MemSubForm.phone.focus();
MemSubForm.phone.select();}else if (MemSubForm.zip.value.length < 5) {
MemSubForm.zip.value = prompt("Please enter a valid zip code."); if
(MemSubForm.zip.value.length != 0) MemSubForm.zip.focus();}// --
></script></head><body>
The Form HTML Code
<h2 style="text-align: center">Computer Technology Documentation
Project</h2><h2 style="text-align: center">Member Registration</h2><hr
size="5" width="90%"> <div style="text-align: center"><table><td><pre>

<form name="RegistrationForm"><b>First Name: </b><input type="text"


name="firstname"><b>Last Name: </b><input type="text"
name="lastname"><b>Address1: </b><input type="text"
name="addr1"><b>Address2: </b><input type="text" name="addr2"><b>City:
</b><input type="text" name="city"><b>State: </b><select name="state"
size="1"> <option value="1">AL <option value="2">AK <option value="3">AR
<option value="4">AS <option value="5">AZ <option value="6">CA <option
value="7">CO <option value="8">CT <option value="9">DC <option
value="10">DE <option value="11">FL <option value="12">FM <option
value="13">GA <option value="14">GU <option value="15">HI <option
value="16">ID <option value="17">IA <option value="18">IL <option
value="19">IN <option value="20">KS <option value="21">KY <option
value="22">LA <option value="23">MA <option value="24">MD <option
value="25">ME <option value="26">MH <option value="26">MI <option
value="28">MN <option value="29">MO <option value="30">MP <option
value="31">MS <option value="32">MT <option value="33">NC <option
value="34">ND <option value="35">NE <option value="36">NH

<option value="37">NJ <option value="38">NM <option value="39">NV <option


value="40">NY <option value="41">OH <option value="42">OK <option
value="43">OR <option value="44">PA <option value="45">PR <option
value="46">PW <option value="47">RI <option value="48">SC <option
value="49">SD <option value="50">TN <option value="51">TX <option
value="52">UT <option value="53">VA <option value="54">VI <option
value="55">VT <option value="56">WA <option value="57">WI <option
value="58">WV <option value="59">WY</select><b>Zip: </b><input type="text"
name="zip" maxlength="10" size="10"><b>Area Code/Phone:</b><input
type="text" name="code" maxlength="3" size="3"><input type="text"
name="phone" maxlength="7" size="7"><div style="text-align: center"><input
type="button" name="cmdSubmit" value="Submit"> <input type="reset"
value="clear"></div></pre></form></td></table></div></body>
How the Form Appears and Works:
Computer Technology Documentation Project
Member Registration

First Name: Last Name: Address1: Address2: City: State: Zip: Area
Code/Phone:

Using Applets
Putting an Applet on a Web Page
<html><head><title>An Applet Example</title></head><body><p>The Applet
example is: <br><applet code="MyApplet.class" width="200" height="50"><param
name="font" value="TimesRoman"><param name="size" value="16">You see this
if your browser does not include Java support.</applet></p></body></html>
If the OBJECT tag is used rather than the APPLET tag, use CLASSID in place of CODE
to specify the file name. A JAR (JAVA Archive) file is a package of the applet (or
application) along with all required supporting class files. The "jar" command is used
to create these JAR files from class and gif files.
Applet Attributes
The APPLET element is depreciated in favor of the OBJECT element for those
browsers that support it. The OBJECT element is described below.
ALT - Alternate text if the applet is not loadable.
CLASS="..." - The name of the applet.
CODE - The name of the applet main class file.
CODEBASE - Specifies a different folder for the browser to look for the applet
file.
WIDTH - The width of the applet output area in pixels.
HEIGHT - The height of the applet output area in pixels.
ALIGN - ALIGN="TOP "- Indicates how the applet should be aligned with any
text that follows it. Values: LEFT
RIGHT

TOP - Align with the topmost item in the line.


BOTTOM
MIDDLE
ABSMIDDLE
ABSBOTTOM
BASELINE
TEXTTOP

PARAM - Used to pass parameters to applets. Parameters expected but not passed
are passed as a NULL. Your program needs to test for NULL parameters and set a
default for any expected parameters. The "getParameter" function is used to get the
passed parameters in the applet.
SRC="..." - The URL of the directory where the compiled applet can be found (should
end in a slash / as in "http://mysite/myapplets/"). Do not include the actual applet
name, which is specified with the CLASS attribute.
HSPACE - Space in pixels between the applet and the text around it.
VSPACE - Vertical space between the applet and other text.
The Object Element
Example
<html><head><title>An Applet Example</title></head><body><p>The Applet
example is: <br><object classid="java:MyApplet.class" codetype="application/java"
width="200" height="50"><param name="font" value="TimesRoman"><param
name="size" value="16">You see this if your browser does not include Java
support.</applet></p></body></html>

Object Attributes
ALIGN - (Depreciated) - Sets alignment to middle, top, bottom, left, or right.
ARCHIVE - Lets the browser download several archive files at once.
BORDER - (Depreciated) - The width of the border.
CLASSID - Determines how the object is implemented.
CODEBASE - Sets relative URI locations.
CODETYPE - Specifies whether it is an application and program language.
DATA - The embedded object Universal Resource Indicator (URI).
DECLARE - The object is not instantiated until a link is later clicked on or an
object uses it.
HEIGHT
NAME
STANDBY - Text to be displayed while the object is loading.
TABINDEX - A numerical value that sets the tabbing order of the object.
TYPE - Sets the media type such as screen, printer, TV.
USEMAP

See the "Recommended Reading" section for sources of a more complete list.
The PARAM Element
Used to set up parameters for the OBJECT and APPLET elements. (Occurs inside
<applet> or <object> tags.) There is no ending tag for this element. Attributes
include:
NAME="..." - The type of information being given to the applet or ActiveX
control.
TYPE - The MIME content type of the resource.
VALUE="..." - The actual information to be given to the applet or ActiveX
control.
VALUETYPE - Sets the type for the VALUE attribute. Possible values include
data, ref, and object.
XHTML
XHTML is the latest World Wide Web Consortium standard as of this writing. It stands
for XML Hypertext Markup Language (XHTML). It replaces HTML but is much like
HTML with some additional rules to add better structure to the language. It, like
HTML, has a strict, transitional, and frameset DTD.
XHTML Rules
The XHTML document must be well formed. This means: There must be one
and only one top level element.
All elements must have a starting and an ending tag with matching starting
and ending names. For instance documents that normally have no closing tag are
normally written: <br><hr><li> Now must be written: <br /><hr /><li />
Element names are case sensitive.
Elements must be nested properly.

Tags must be in lower case letters.


Values of attributes must be in quotes. Formally the following would be OK: <A
href=index.html target=_top> Now use the following: <a href="index.html"
target="_top">
Attributes may not be minimized. <table><tr><td nowrap<find /var/spool -mtime
+40</td></tr>

1 </table> Becomes: <table><tr><td nowrap="nowrap"<find /var/spool -


mtime +40</td></tr></table>
2 A DTD Declaration with head and body elements must be present in the
document. The DTD can be Strict, Transitional, or Frameset (for Frames). An
example DTD declaration is shown below: <!DOCTYPE html PUBLIC "-//W3C//DTD
XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd"> Of course after the DTD declaration an <html> element should
exist which includes both a <head> and <body> element as is contained in a normal
HTML document.
3 The name attribute is replaced by the id attribute. <input type="text"
name="firstname" /> Becomes: <input type="text" id="firstname" />
HTML Tags
Start tag End tag Description
<!DOCTYPE> - Document type.
<ABBREV> </ABBREV> Denotes an abbreviation.
<A> </A> Anchor
<APPLET> </APPLET> Anchor
<AREA> - Defines areas of an image map that the user
may click on to establish a link.

<AU> </AU> Author.


<B> </B> Bold text
<BASE> - Defines the base point from which anchor
references are made.

<BASEFONT> - Used to set the default font size on the


current page.
<BGSOUND> - Used to play sounds on a web page.
<BIG> </BIG> Set text size to larger than normal.
<BLOCKQUOTE> </BLOCKQUOTE> Indents the text as though it were a quote.
<BR> - Break, starts a new line, but doesn't put a
blank line between text.

<BODY> </BODY> Defines the body of the HTML page.


<BUTTON> </BUTTON> Used to define a FORM submit, reset, or push
button.
<CODE> </CODE> Denotes program code and should be set in
the same format as the PRE tag, but does not
work either with all browsers or all HTML
versions.
<DIR> </DIR> directory
<DD> </DD> Designated definition.
<DEL> </DEL> Denotes deleted text.
<DIV> </DIV> Used to offset parts of the HTML document to
perform assignment of special attributes or
controls to that section.
<DFN> </DFN> Denotes the definition of a term.
<DL> </DL> Definition list.
<DOCTYPE> - Document type.
<DT> </DT> Definition term.
<EM> </EM> Sets text in italics and denotes emphasis.
<FIELDSET> </FIELDSET> Allows grouping of form controls.
<FONT> </FONT> Sets a section of text with a specific font.
<FORM> </FORM> Displays a form for user information.
<FRAME> - Specifies a frame to be placed inside a FRAMESET.
<FRAMESET> </FRAMESET> Used to divide the browser window into separate
frames that can display multiple documents.

<H1> </H1> Defines a level 1 header.


<H2> </H2> Defines a level 2 header.
<H3> </H3> Defines a level 3 header.
<H4> </H4> Defines a level 4 header.
<H5> </H5> Defines a level 5 header.
<H6> </H6> Defines a level 6 header.
<HEAD> </HEAD> Defines the head of document.
<HR> - Horizontal rule, starts a new line with horizontal
graphic line between sections.

<HTML> </HTML> Defines an HTML document or page.


<IMG> - Used to embed graphics in HTML pages.
<INPUT> </INPUT> An input element for a form.
<INS> </INS> Denotes inserted text.
<I> </I> Italics
<KBD> </KBD> Text to be typed at the keyboard, such as a
computer command. The test is displayed in a
mono spaced format.
<LABEL> <.LABEL> Allows an ability to click on a text label to select a
form control

<LI> - List item in a list.


<MAP> </MAP> Starts a client-side image map.
<MENU> </MENU> A menu list (Depreciated).
<META> - Meta element defining special characteristics of the
document.
<NOFRAMES> </NOFRAMES> Used for web browsers that don't support
FRAMESETs.
<NOSCRIPT> </NOSCRIPT> Used for web browsers that don't support script
code.
<OBJECT> </OBJECT> Object, the replacement for Applets and more.
<OL> </OL> Numbered or ordered list.
<OPTGROUP> </OPTGROUP> Sets up choices inside a SELECT menu.
<OPTION> </OPTION> Used to set items in a list of selectable items in a
form.
<P> </P> Paragraph.
<PARAM> - Used to set up parameters for the OBJECT and
APPLET elements..

<PRE> </PRE> Preformatted text. Text presented as typed with


tabs, spaces and other whitespace.

<Q> </Q> Quotation.


<SAMP> </SAMP> Denotes sample text.
<SCRIPT> </SCRIPT> Used to embed client side script in HTML code,
usually in the header.

<SELECT> </SELECT> Creates a list of items that can be selected.


<SMALL> </SMALL> Makes text smaller than normal.
<SPAN> </SPAN> Allows text attributes and color to be modified at
any location.
<STRIKE> </STRIKE> Draws a line through the text as a "strikeout".
<STRONG> </STRONG> Same as bold but denotes strong emphasis.
<STYLE> </STYLE> Used to set the style of the web page.
<SUB> </SUB> Subscript.
<SUP> </SUP> Superscript.
<TABLE> </TABLE> Table.
<TD> </TD> Designates a table data cell.
<TEXTAREA> </TEXTAREA> Indicates an element that has multiple text lines
<TH> </TH> Designates a table header.
<TR> </TR> Designates a table row.
<TITLE> </TITLE> Document or page title.
<TT> </TT> Monospaced typewriter font.
<U> </U> Underlined text.
<UL> </UL> Unnumbered list.
HTML Terms
Angle brackets - The characters, < and >, set HTML tags off from the rest of
the text on an HTML page. These two symbols enclose all HTML tags.
Attributes - Defined words used in an HTML tag to modify the tag properties.
They can be used to add or change color or change a size in some element.
BODY - The main part of an HTML document.
Element - An HTML designator that defines special objects such as
paragraphs, lists, and lines in HTML. It usually consists of a beginning and ending
tag, but may have just a beginning tag.
FTP - File Transfer Protocol. A method used to send or receive files between
two computers on the network or internet.
Graphics drawing program - A program used to draw graphics images that
may be used on a web page. Normally these images are stored as gif files, but
several formats may be used.
Header - The beginning part of an HTML document which defines various
characteristics such as the title.
Home page - The main page of an organization or company which is the first
page seen when the organization's URL is visited.
HTML - Hyper-Text Markup Language is the basic language web pages are
written in.
HTML editor - An editor that makes web page creation easier than using a
normal text editor. Although you can write HTML code using a standard text editor, it
is strongly recommended that you use some type of HTML editor even for learning.
There are two categories of text editor. WYSIWYG (What you see is what you get) or
graphical HTML editors which allow the user to see the page as the web browser
would see it as they edit the page. You will not see the HTML elements or tag sets
using this type of editor, so for learning HTML it is not recommended.
A text based HTML editor lets the user see and edit HTML code directly.
Usually the HTML tags are displayed in a different color than the surrounding text
which makes them easier to see and work with. This web page was written using the
Arachnophilia v3.9 HTML editor.

HTTP - Hypertext transfer protocol is the internet protocol used to transport


information between the client browser and the web page server.
Hyperlinks or links - HTML coded locations of other material on the web. They are
usually underlined and consist of a different text color than the surrounding text.
When you click on them they will usually cause your browser to load the page it is
pointing to and you will see the new page displayed.
Tags - Tags are used to surround text which has special meaning in HTML. Tags tell
the browser what to do. The tag set <P> </P> is used to tell the browser that text
between the two tags is to be set apart as a separate paragraph in HTML.
URI - Uniform Resource Identifier which is used as an identifier for a resource. The
URI may include a complete path to the resource or may only be relative without a
complete path.
URL - Uniform Resource Locator. It is used to specify file locations of html or other
files. The
URL "http://ctdp.tripod.com" is the URL for the CTDP home page. The first
section "http:" designates the type of transfer which in this case is Hyper-text
transfer protocol. Other cases include FTP, GOPHER, and FILE.
Web browser - Software used to retrieve and display web pages on the web.
It is considered to be a client program which makes requests to web servers for web
page files. Browsers can all read basic HTML but may be different in other areas such
as being able to display or run script code, video and graphics.
Web server - The computer the web pages are stored on. The web server will
transmit the web pages across the network/internet to the client computer which is
running a web browser.
Recommended Reading
The following sources should be helpful in learning about HTML and the use of style
sheets. They give additional details not listed here.
Web Design Group's web page, HTML 4.0 Reference section. It is an excellent
reference and is also available in an offline viewable format. This is the best source on
the web that I have found describing HTML.
The World Wide Web Consortium Hypertext Markup Language Home Page.
Contains excellent references to multiple sets of HTML documentation including XHTML,
HTML 4.01 and older versions. Also links to information about style sheets can be found
here along with links to HTML document type definitions (DTDs).
The World Wide Web Consortium HTML 4.01 Specification.
The World Wide Web Consortium HTML 4.01 Strict DTD.
The World Wide Web Consortium HTML 4.01 Transitional DTD.
Web Design Group's web page, Cascading Style Sheets Guide. It includes a
tutorial, information about CSS structure, CSS rules, and how to link style sheets to
HTML along with several other references.
The World Wide Web Consortium CSS Level 1 Recomendation.
The World Wide Web Consortium CSS Level 1 Specification.
Module

XML & Java Script


Chapter 1
1 Introduction

This module explains how to use JavaScript to work with XML data. It starts by demonstrating
techniques for obtaining XML data: loading it from the network, parsing it from a string, and
obtaining it from XML data islands within an HTML document. After this discussion of obtaining
XML data, the chapter explains basic techniques for working with this data.

This coverage of basic XML techniques is followed by two sections that demonstrate applications of
those techniques. First, you’ll see how it is possible to define HTML templates and automatically
expand them, using the DOM and XPath, with data from an XML document. Second, you’ll see how
to write a web services client in JavaScript using the XML techniques from this module.

Chapter 2

XML
2.1 Introduction
XML stands for Extensible Markup Language. XML is a public standard developed and
maintained by the World Wide Web Consortium (W3C). The W3C develops inter operable
technologies (specifications, guidelines, software and tools) to increase the potential of
the Web as a forum for information, commerce, communication and collective
understanding. XML is a text-based markup language that is fast becoming
the standard for data interchange on the Web. It was designed to describe data.

XML is a markup language much like HTML. As with HTML, we identify data using tags
(identifiers enclosed in angle brackets). XML tags are not predefined in XML. We must
define our own tags. XML is self describing. XML uses a DTD (Document Type Definition)
to formally describe the data. XML was designed to describe data and to focus on what
data is. HTML was designed to display data and to focus how data looks. HTML is about
displaying information, XML is about describing information.

The tags used to markup HTML documents and the structure of HTML documents are
predefined. For example the HTML tag <B> ... </B> renders the text in bold font style.
The author of HTML documents can only use tags that are defined in the HTML standard.
XML allows the author to define his own tags and his own document structure.
XML can keep data separated from our HTML. XML can be used to store data inside
HTML documents. XML can be used as a format to exchange information.
XML can be used to store date in files or in databases. Thus we can use XML to create an
unlimited number of our own custom tags and attributes, assign a data type to each tag
and attribute, access values associated with the tags, and accomplish all of this in a
custom structured format that we have also created.
As described above, HTML pages are used to display data. Data are often stored inside
HTML pages. With XML this data can now be stored in a separate XML file.

This way we can concentrate on using HTML for formatting and display, and be sure that
changes in the underlying data will not force changes to any of our HTML code.

However, XML can store data inside HTML documents as so-called data islands.

Computer systems and databases contain data in incompatible formats. One of the
big problems is to exchange data between such systems over the Internet. Converting
data to XML can greatly reduce this complexity and create data that can be read by
different types of applications.

XML can also be used to store data in files or in databases. Applications can be written
to store and retrieve information from the store, and generic applications can be used to
display the data.

An XML document is an ordered, labeled tree: character data leaf nodes contain the
actual data (text strings) where usually, character data nodes must be non-empty and
non-adjacent to other character data nodes elements nodes, are each labeled with a
name (often called the element type), and a set of attributes, each consisting of a name
and a value. These nodes can have child nodes.

In addition, XML trees may contain other kinds of leaf nodes: processing instructions
- annotations for various processors
comments - as in programming languages
document type declaration.

In general, we should avoid attributes. Attributes cannot contain multiple values


(elements can). Attributes are not expandable (for future changes). Attributes
cannot describe structures (like child elements can). Attributes are more difficult
to manipulate by program code. Attribute values are not easy to test against DTD
(Document Type Definition).

XML documents may be encoded in a range of character sets. For multi-language


support XML supports 16-bit Unicode (ISO/IEC 10646). Unicode supports all
spoken languages including the European, Semitic, Arabian, Indian, Japenese and
Chinese language. Of the roughly 40 000 characters defined by Unicode about
20 000 characters are used for Mandarin and other Chinese languages, 11 000 for
Hangul (Korean). The remaining 9 000 characters suffice for most characters of the
remaining spoken languages of the world.

Any combination or repeated occurances of space characters, horizontal tabs, line


feeds and/or carriage returns is treated in XML as a single white space. All white
space characters within the content of elements is preserved by parsers while multiple
white space characters within element tags and attribute values may be removed and
replaced with a single white space character.

There are three commonly used end-of-line delimiters, namely carriage-return (CR),
line-feed (LF) or carriage-return + line-feed (CR+LF). To simplify processing, XML
parsers were required to replace all end-of-line delimiters with a single line feed.
The following conditions for an XML document must be satisfied.
1) All XML elements must have a closing tag.
2) XML tags are case sensitive. Opening and closing tags must therefore be written
with the same case. For example, an XML parser interprets <BOOK> and <book> as
two different tags. Recall that HTML tags are not case sensitive.
3) All XML elements must be properly nested.
4) All XML documents must have a root tag. Recall that an XML document is an
ordered, labeled tree.
5) Attributes must always be quoted. XML elements can have attributes in name/value
pair just like in HTML. In XML the attribute value must always be quoted. XML attributes
are normally used to describe XML elememts, or to provide additional information about
elements.

XML names may only start with a letter, an underscore character or a colon. The
subsequent characters may include the latter plus numerals, dashes and full-stops.
Colons should, however, be used for namespace delimiters. Furthermore, XML
names should not start with the three letters XML in any case (xml, Xml, xmL, ...).
Names starting with these characters are reserved for W3C use only. Note that
XML names are case-sensitive.

Since spaces are not allowed in elements names, the underscore (_) is a common
symbol used to add space between words. Capitalizing the first letter of each word in
the element is another way to delineate separate words. Our tags can be composed
of almost any string of characters, with certain limitations: The first character of
an XML tag must be an upper or lower case letter, the underscore, or a colon. The
remaining characters can be composed of any combination of upper or lower case
letters, colons, hyphens, numbers, periods, or underscores.
The very first line of every XML document must be the XML declaration. For
example
<?xml version="1.0" standalone="yes" encoding="ISO-8859-1"?>
where <? begins a processing instruction. xml declares this to be an XML instruction.
version identifies the version of XML specification in use. Version 1.0 is the
only current version so the value must be 1.0. The markup standalone states if
this file is completely by itself. A no value signals the parser that it should import
other mark-up files, such as an external DTD (Document Type Definition).
Since well-formed XML docs are complete by itself, this attribute value would be
yes. The command encoding indicates which international character set is used.
ISO-8859-1 is the default and is essentially the English character set. The markup
?> terminates the processing instruction.
A comment is given by
<!-- This is a comment -->
XML documents require a root element. The root element appears only once and
encapsulates the entire XML elements and data in the document, in the same way
<HTML> ... </HTML> contains the contents of an HTML document.
Since XML uses certain characters for its own syntax, these characters must be supplied
in another way. For this reason XML introduces five standard entity references
&lt; &gt;
These entity references must be used for literal left and right angle brackets which
are used in XML as element tag delimiters.
&apos; &quot;
These entity references must be used for single and double quotes which are used in
XML as element tag delimiters.
&amp;
&amp; must be used for literal ampersands. Ampersands are used in XML for entity
references.

In the following we give an example. The first line is the XML declaration. It
defines the XML version of the document. Furthermore library is the root element
appearing only once and containing all the other elements. We save the XML with
any filename and an .xml extension. Then we load the file onto an XML-parser
such as IE 6, NetScape 6, Opera 4+, Ice Browser, or Mozilla.
<?xml version="1.0" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="library.xsl"?>
<!-- File name: library.xml -->
<!-- address: file://c:\books\java\library.xml -->
<library>
<book>
<title> SymbolicC++ </title>
<subtitle> An Introduction to Computer Algebra </subtitle>
<author> Tan Kiat Shi, Willi Hans Steeb, Yorick Hardy </author>
<ISBN> 1852332603 </ISBN>
<publisher> Springer </publisher>
<city> London </city>
<year> 2000 </year>
</book>
<book>
<title> Classical and Quantum Computing </title>
<subtitle> with C++ and Java Simulations </subtitle>
<author> Yorick Hardy and Willi Hans Steeb </author>
<ISBN> 3764366109 </ISBN>
<publisher> Birkhauser Publishing </publisher>
<city> Basel </city>
<year> 20001 </year>
</book>
</library>
If we consider the XML file from an SQL table point of view then each
<book> ... </book>
block would be one row in the table library.
The following example shows how to use an attribute. The attribute is sex.
<?xml version="1.0" standalone="yes"?>
<people>
<person sex="male">
<lastname> Steeb </lastname>
<firstname> Willi Hans </firstname>
<profession> Professor </profession>
</person>
<person sex="female">
<lastname> de Sousa </lastname>
<firstname> Nela </firstname>
<profession> Lecturer </profession>
</person>
</people>
We can rewrite it without using an attribute.
<?xml version="1.0" standalone="yes"?>
<people>
<person>
<sex> male </sex>
<lastname> Steeb </lastname>
<firstname> Willi Hans </firstname>
<profession> Professor </profession>
</person>
<person>
<sex> female </sex>
<lastname> de Sousa </lastname>
<firstname> Nela </firstname>
<profession> Lecturer </profession>
</person>
</people>

The polynomial
p(x; y) = 2x3y2 ¡ 4y5
could be encoded in XML as
<?xml version="1.0"?>
<polynomial>
<term>
<factor> 2 </factor>
<variable>
<name> x </name>
<exponent> 3 </exponent>
</variable>
<variable>
<name> y </name>
<exponent> 2 </exponent>
</variable>
</term>
<term>
<factor> -4 </factor>
<variable>
<name> x </name>
<exponent> 0 </exponent>
</variable>
<variable>
<name> y </name>
<exponent> 5 </exponent>
</variable>
</term>
</polynomial>

2.2 Schema
A schema is a formal way of defining and validating the content of an XML document.
A well-formed XML document that conforms to its schema is said to be valid.
The schema is how we assign the data types to each tag and any attributes that are
contained in the XML document. A schema is a structured document which must
obey XML syntax rules. It is composed of a series of predefined tags and attributes
that are part of the XML language and are used to set the data types for the values
associated with our custom tags. Not only do we get to create custom XML tags,
but we can also denote that an XML data value is, for example, an integer data
type. Thus we can assign specific data types to specific XML data values. A schema
can be part of the XML document or a separate file.
The XML tags and attributes to create a schema are:
The Schema tag serves as a container element that delimits the beginning and end
of the schema. This tag must be closed.
The xmlns attribute is used to declare the data types of the schema XML namespace.
The value is a URL or URN address that the browser will access to get information
on the data types to allow code validation.
The xmlns:dt attribute is used to declare the data types of the schema XML namespace.
The value is a URL (Uniform Resource Locator) or URN (Uniform Resource
Name) address that the browser will access to get information on the data types to
allow code validation. If we are using IE 5 to view our XML document, then we
must include the xmlns and the xmlns:dt attributes exactly as displayed below
<Schema xmlns="urn:schema-microsoft-com:xml-data"
xmlns:dt="urn:schemas-microsoft-com:datatypes">
...
</Schema>
The AttributeType tag is used to declare the data type for an attribute of an XML
tag. This tag must be closed.
The name attribute provides the name of the attribute.
The dt:type attribute dictates the data type of the attribute.

The permitted values are:


binary boolean byte date
decimal double float int
integer long negativeInteger
nonNegativeInteger nonPositiveInteger
positiveInteger recurringInstant
short string time timeDuration
timeInstant
unsignedByte unsignedShort unsignedInt unsignedLong
The attribute tag is used to associate a previously data typed attribute to a tag.
This tag must be closed.
The type attribute provides the data type of the custom attribute.
The ElementType tag is used to declare the data type for a custom XML tag. The
tag must be closed.
The content attribute describes the intended content of the XML tag. There are
four permitted values:
Type Description
======= ===============================
eltOnly contains only elements
empty contains no content
mixed contains both elements and text
textOnly contains only text
==========================================
The name attribute provides the name of the tag (element).
The dt:type attributes dictates the data type of the tag (element). There are 23
permitted values (see above).
The element tag is used to associate a previously data typed tag to an element.
This tag must be closed.
The type attribute provides the type of the custom XML element.
2.3 Document Type Definition
The purpose of Document Type Definition (DTD) is to define the legal building
blocks of an XML document. A DTD can be declared inline in our XML document
or as an external reference. An example with an external reference is given below.
XML provides an application independent way of sharing data. With a DTD, independent
groups of developers can agree to use a common DTD for interchanging
data. Our application can use a standard DTD to verify that data that we receive
from the outside world is valid. We can also use a DTD to verify our own data.
XML documents (and HTML documents) are made up by the following building
blocks:
Elements, Tags, Attributes, Entities, PCDATA, CDATA
Attributes provide extra information about elements. Attributes are placed inside
the start tag of an element. Attributes come in name/value pairs. PCDATA means
parsed character data. We think of character data as the text found between the
start tag and the end tag of an XML. PCDATA is text that will be parsed by a
parser. Tags inside the text will be treated as markup and entities will be expanded.
CDATA also means character data. CDATA is text that will not be parsed by a
parser. Tags inside the text will NOT be treated as markup and entities will not be
expanded. Entities are variables used to define common text. Entities references are
references are references to entities. For example, the HTML entity reference &nbsp;
is used to insert an extra space in an HTML document. Entities are expanded when
a document is parsed by an XML parser.
<?xml version="1.0"?>
<!-- familytree.dtd -->
<!-- PCDATA parseable character data -->
<!-- attributes keyword ATTLIST -->
<!-- DTD describing an individual person -->
<!ENTITY % reference "person IDREF #REQUIRED">
<!ELEMENT person (name | father)*>
<!ATTLIST person id ID #REQUIRED sex (m | f) #IMPLIED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT father EMPTY>
<!ATTLIST father %reference;>

The XML file is given by


<?xml version="1.0"?>
<!-- familytree.xml -->
<!-- Each person is identified by a unique ID -->
<!DOCTYPE familytree SYSTEM "familytree.dtd">
<familytree>
<person id="p1" sex = "m">
<name> Olaf </name>
</person>
<person id="p2" sex = "m">
<name> Theo </name>
<father person = "p1" />
</person>
<person id="p3" sex = "m">
<name> Ario </name>
<father person = "p1" />
</person>
<person id="p4" sex = "m">
<name> Carl </name>
<father person = "p2" />
</person>
</familytree>
Each person is identified by a unique id. This will be invaluable for later processing
of individuals. For processing the XML file we have to provide an XSL file.

2.4 Displaying XML using Data Binding


Internet Explorer 5 and 6 contain a DSO (Data Source Object) that permits displaying
the data in an XML document on an HTML page by using the technology
of client-side data binding. This involves taking the XML data from the server-side,
transferring the data to the client side for future access, and binding the data to an
HTML tag. The data is treated like a record set in ADO (ActiveX Data Object)
and the data can be manipulated by using the various methods and properties of the
ADO Recordset object. In our example, we use these features to navigate through
our data. Once the data is bound to an HTML tag, it can be viewed on IE 5 and
6. There are fifteen HTML tags that can be used for data binding:
a applet button div frame iframe img input
label marquee object select span table textarea
These fifteen tags can use two special proprietary attributes, datasrc and datafld,
that are only recognized on IE 4, IE 5 and IE 6.
<span> or <div> elements can be used to display XML data.
The datasrc attribute allows the linking of the HTML tag to the XML data document.
The datafld attribute is used to name the XML data field that we wish to
display.
These attributes are very easy to use and only require one line of code to access an
XML data value. The sign # signifies a link. Note that this is a complete HTML
element with both an opening and closing tag.
For our data binding example we use the MyXML.xml file with the library example.
We want to create an HTML page that displays the XML data for the
title subtitle author ISBN publisher city year
We want to be able to scroll through the list of books using navigation buttons
and see the data for any book. To do so, we use the src attribute of an inline xml
element to link our HTML page to the XML document. We use the HTML span
tag for the data binding. We use the datasrc attribute to link each span element
to the xml element. We use the datafld attribute to bind the specified XML data
value to the span element. We use previous and next input buttons to call data
navigation functions. We use MoveNext() and MovePrevious() ADO methods to
navigate our data. We apply RecordCount and AbsolutePosition ADO properties
to limit our data navigation so that we never go to BOF or EOF.

<HTML>
<TITLE> Data Binding </TITLE>
<BODY>
<xml id="xmlLibrary" src="file://c:\books\java\library.xml">
</xml>
<B> Use the buttons to scroll up and down the library </B>
<BR><BR>
TITLE: <span datasrc="#xmlLibrary" datafld="title"></span>
<BR>
SUBTITLE: <span datasrc="#xmlLibrary" datafld="subtitle"></span>
<BR>
AUTHOR: <span datasrc="#xmlLibrary" datafld="author"></span>
<BR>
ISBN: <span datasrc="#xmlLibrary" datafld="ISBN"></span>
<BR>
PUBLISHER: <span datasrc="#xmlLibrary" datafld="publisher"></span>
<BR>
CITY: <span datasrc="#xmlLibrary" datafld="city"></span>
<BR>
YEAR: <span datasrc="#xmlLibrary" datafld="year"></span>
<BR>
<input type="button" value="Previous" onclick="Previous()">
<input type="button" value="Next" onclick="Next()">
<SCRIPT LANGUAGE="JavaScript">
function Previous()
{
if(xmlLibrary.recordset.AbsolutePosition > 1)
xmlLibrary.recordset.movePrevious();
}
function Next()
{
if(xmlLibrary.recordset.AbsolutePosition <
xmlLibrary.recordset.RecordCount)
xmlLibrary.recordset.moveNext();
}
</SCRIPT>
</BODY>
</HTML>

2.5 Displaying XML Using XSL


XSL is the acronym for the Extensible Stylesheet Language which is an application
of XML. XSL is a powerful styling language that uses special stylesheets to create
templates to display the data contained in an XML page in a variety of ways. We
use XSL to transform an XML document into an HTML page that can be viewed on
Internet Explorer. We do this by creating a separate XSL document that is linked
to the XML document. XSL is composed of two parts: XSLT which stands for XSL
Transformation and is used to transform from an XML doucment to another format
which may be HTML, PDF or LaTEX. XSLFO which stands for XSL Formatting
which is the native XML equivalent of Cascading Style Sheets (CSS). XSLFO is
thus reponsible for rendering information in a visual way.
This technology can be used with IE 5 and IE 6. The Microsoft version and XSL
does not fully support all the recommendations set for this language by the World
Wide Web Consortium (W3C). However, XSL can be used on the server-side so that
the output is browser independent.

XSL is not a large language. It is composed of twenty tag-like elements and associated
attribute-like methods. Like XML, all XSL elements must have an opening
and closing tag. All XSL tags have the same namespace prefix, xsl:, to denote
that this is an XSL element. Notice the use of the colon. After the prefix, the suffix
designates the tag’s purpose.
In order to display our XML document, we only need three of the XSL elements.
xsl:template
The xsl:template element is used to define a template. It can also be used as a
container element to declare the start and stop of an XSL coding sequence. We use
it in this manner in our example. In order for this to work in IE 6, we must use the
following code exactly
<xsl:template xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
The next element we use is
xsl:for-each
This element is used to create a for ... each loop which allows looping through
all the values for an XML data field. We use the select attribute to specify the
name of the XML data element.
xsl:value-of
The xsl:value-of element is used to insert the value of the XML data field into
the template. We use the select attribute to specify the name of the XML data
field. The xsl:value-of element allows us to display the data value for an XML
tag.

An example is given in the following. The Library.xml file is given by


<?xml version="1.0" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="library.xsl"?>
<!-- File name: library.xml -->
<!-- address: file://c:\books\java\library.xml -->
<library>
<book>
<title> SymbolicC++ </title>
<subtitle> An Introduction to Computer Algebra </subtitle>
<author> Tan Kiat Shi, Willi Hans Steeb, Yorick Hardy </author>
<ISBN> 1852332603 </ISBN>
<publisher> Springer </publisher>
<city> London </city>
<year> 2000 </year>
</book>
<book>
<title> Classical and Quantum Computing </title>
<subtitle> with C++ and Java Simulations </subtitle>
<author> Yorick Hardy and Willi Hans Steeb </author>
<ISBN> 3764366109 </ISBN>
<publisher> Birkhauser Publishing </publisher>
<city> Basel </city>
<year> 20001 </year>
</book>
</library>
The file library.xsl is given by
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<HTML>
<BODY>
<xsl:for-each select="library/book">
<DIV>
TITLE: <xsl:value-of select="title"/>
<BR/>
AUTHOR: <xsl:value-of select="author"/>
<BR/>
YEAR: <xsl:value-of select="year"/>
<HR/>
</DIV>
</xsl:for-each>
</BODY>
</HTML>
</xsl:template>
</xsl:stylesheet>

To put an conditional if test against the content of the file, we simply add an
xsl:if element to our document. In the example we consider the table for a sporting
competition
name points
======================
Snowbird John 6234
Adler Jack 3234
Eagle Carl 134
======================
Each row of the table is identified as a
<result> ... </result>
block for the xml-file. We only want the display the table for the participants who
have more than 200 points.
The file if.xml is given by
<?xml version="1.0"?>
<!-- File name: If.xml -->
<!-- address: file://c:\books\java\if.xml -->
<?xml-stylesheet type="text/xsl" href="if.xsl"?>
<ranking>
<result>
<name> Snowbird John </name>
<points> 6234 </points>
</result>
<result>
<name> Adler Jack </name>
<points> 3234 </points>
</result>
<result>
<name> Eagle Carl </name>
<points> 134 </points>
</result>
</ranking>
42 CHAPTER 2. XML
The if.xsl-file is given by
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- address: file://c:\books\java\if.xsl -->
<xsl:template match="/">
<HTML>
<BODY>
<TABLE border="2">
<TR>
<TH> Name </TH>
<TH> Points </TH>
</TR>
<xsl:for-each select="ranking/result">
<xsl:if test="points &gt; 200">
<TR>
<TD><xsl:value-of select="name"/></TD>
<TD><xsl:value-of select="points"/></TD>
</TR>
</xsl:if>
</xsl:for-each>
</TABLE>
</BODY>
</HTML>
</xsl:template>
</xsl:stylesheet>

The following two programs show an application of xsl:sort. The attributes we


can use are
order = "ascending/descending"
lang = "..."
data-type = "text/number"
case-order = "upper-first/lower-first"
The file sort.xml is given by
<?xml version="1.0"?>
<!-- File name: Sort.xml -->
<!-- address: file://c:\books\java\sort.xml -->
<?xml-stylesheet type="text/xsl" href="sort.xsl"?>
<ranking>
<player>
<name> Snowbird </name>
<points> 723 </points>
</player>
<player>
<name> Adler </name>
<points> 323 </points>
</player>
<player>
<name> Eagle </name>
<points> 173 </points>
</player>
</ranking>
The file sort.xsl is given by
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<HTML>
<BODY>
<TABLE border="2">
<TR>
<TH> Name </TH>
<TH> Points </TH>
</TR>
<xsl:for-each select="ranking/player">
<xsl:sort select="points" order="descending" data-type="number"/>
<TR>
<TD><xsl:value-of select="name"/></TD>
<TD><xsl:value-of select="points"/></TD>
</TR>
</xsl:for-each>
</TABLE>
</BODY>
</HTML>
</xsl:template>
</xsl:stylesheet>
2.6 Using org.w3c.dom.*
The Document Object Model (DOM) is a platform- and language-neutral interface
that will allow programs and scripts to dynamically access and update the content,
structure and style of documents. The document can be further processed and the
results of that processing can be incorporated back into the presented page. DOM,
the offical W3C API for XML, builds an internal model for the XML document
which is a tree. The web site is
http://www.w3.org
In order to construct the tree it has to read the XML document sequentially, extracting
elements, attributes and name space definitions as well as processing instructions.
In the Level 1 DOM, each object, whatever it may be exactly, is a Node. For
example
<P> This is Chapter 1 </P>
has created two nodes: an element P and a text node with the content This is
Chapter 1. The text node is inside the element, so it is considered a child node of
the element. Conversely, the element is considered the parent node of the text node.
If we consider
<P> This is <B> Chapter 1 </B> </P>
the element node P has two children, one of which has a child of its own.
<P>
|
-----------------------
||
This is <B>
|
Chapter 1
Next we show how to display image metadata with ImageIO as XML-file using DOM.
Given a jpeg-file Image0.jpg. IIOMetadata contains meta information about the
image, so not the actual pixels, but the compression, keywords, comments, etc. If
we convert from one format to another, we do not want to loose this information.
A ImageTranscoder understands this meta data and maps it onto another format.
Internally, Metadata is stored as a bunch of IIOMetadataNodes. They implement
the org.w3c.dom interface. The format of this DOM tree is plug-in dependent:
the native format (as format features are different), but plug-ins may support the
plug-in neutral format.
The following example program displays, using the XSLT transformation package,
the plug-in neutral format.
// Main.java
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import javax.imageio.*;
import java.awt.image.*;
import java.util.*;
import java.io.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.*;
import javax.xml.parsers.*;
import org.w3c.dom.*; // for Node class
public class Main
{
public static void main(String []args) throws Exception
{
Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = (ImageReader) readers.next();
ImageInputStream iis =
ImageIO.createImageInputStream(new File("Image0.jpg"));
reader.setInput(iis,true);
BufferedImage bi = reader.read(0);
IIOMetadata metadata = reader.getImageMetadata(0);
Node node =
(Node) metadata.getAsTree(metadata.getNativeMetadataFormatName());
// use the XSLT transformation package
// to output the DOM tree we just created
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(new DOMSource(node),new StreamResult(System.out));
}
}

Chapter 3
JavaScript
3.1 Introduction
The HTML language used to create pages for the World Wide Web was originally
designed to produce plain and static documents, stuff like engineering notes and
long-winded arguments by scientist types. When the Web first started, the only
browsing software available for it was text-based.
JavaScript makes HTML come alive. JavaScript is a scripting language for HTML
and the Netscape Navigator browser, version 2.0 and later. JavaScript is a
crossplatform,
object-oriented language. Core JavaScript contains a core set of objects
as Array, Date, and Math, and a core set of language elements such as operators,
control structures, and statements. JavaScript “scripts” are small programs that interact
with Netscape and the HTML content of a page. We can create a JavaScript
program to add sound or simple animation, pre-validate a form before the user’s
response
is sent to our company’s server, search through a small database, set options
based on user preferences, and much more. JavaScript performs the same function
as a macro in a word processor or electronic spreadsheet program. A macro is a
small program designed solely to run inside a program, automating some task or
enhancing a feature of the program. The difference here is that instead of a word
processor or electronic spreadsheet application, JavaScript is designed for use with
Netscape and surfing on the World Wide Web.
JavaScript is used in Netscape 2.0 and later versions, as well as in Microsoft Internet
Explorer 3.0 and later versions. As the co-developer of JavaScript, Netscape has
wanted to make JavaScript an open’standard, meaning that other companies can
use and implement JavaScript in their own Internet products. When JavaScript
was first announced in December of 1995, over two dozen companies jumped on the
bandwagon, promising to support it in future products.

Thus JavaScript is an authoring language for the typical Web page designer. It
is a scripting language in which the program is embedded as part of the HTML
document retrieved by the browser.
A JavaScript program consists of one or more instructions (also referred to as code
or commands) included with the HTML markup tags that form our Web documents.
When Netscape encounters a JavaScript instruction, it stops to process it.
For example, the instruction might tell Netscape to format and display text and
graphics on the page. Unlike a program witten in Java, JavaScript programs are
not in separate files (though this is an option using Netscape 3.0 and later). Instead,
the JavaScript instructions are mixed together with familiar HTML markup tags
such as <H1>, <P>, and <IMG>.
Because JavaScript is embedded in HTML documents, we can use any text editor
or Web page editor to write our JavaScript programs. The only requirement is that
the editor must allow direct input.
Netscape needs to be told that we are giving it JavaScript instructions, and these
instructions are enclosed between
<SCRIPT> ... </SCRIPT>
tags. Within the script tag we can have only valid JavaScript instructions. We
cannot put HTML tags for Netscape to render inside the <SCRIPT> tags, and we
cannot put JavaScript instructions outside the <SCRIPT> tags.
JavaScript is designed on a simple object-based paradigm. An object is a construct
with properties that are JavaScript variables or other objects. An object also has
functions associated with it that are known as the object’s methods. In addition to
objects that are predefined in the Navigator client and the server, we can define or
own objects. A JavaScript object has properties associated with it. We access the
properties of an object with a simple notation
objectName.propertyName
Note that JavaScript is case-sensitive. Comments in JavaScript are the same as in
C, C++ and Java, namely
// ...
and
/* ... */
Core JavaScript can be extended for a variety of purposes by supplementing it with
additional objects; for example: Client-side JavaScript extends the core language
by supplying objects to control a browser and its Document Object Model. Serverside
JavaScript extends the core language by suppling objects relevant to running
JavaScript on a server.
3.2. DOCUMENT OBJECT 49
3.2 Document Object
The document object contains information about the current document, such as its
title, when it was last modified, and the color of the background.
The document methods interact with the document. The most commonly used
document method is
document.write("text");
and
document.writeln("text");
which writes text to the browers window. The document objects is itself a property
of the window object. JavaScript assumes that we mean the current window when
we use the syntax given above. Thus the write and writeln methods insert text
into the document. The two methods are identical, except that writeln appends a
new line character to the end of the string.
The command
document.bgColor = "red";
sets the background color to red. As an exmple of these two commands consider
<HTML>
<HEAD>
<TITLE> document.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
document.write("Hello Egoli");
document.write("\n");
str1 = "willi";
str2 = "hans";
document.write("<P> str1 = " + str1 + " str2 = " + str2);
document.bgColor = "red";
</SCRIPT>
</BODY>
</HTML>

The concatention operator + concatenates two strings values together.


The following program shows that the prompt provides a string even if we enter
digits. Then + will do concatenation. Thus to obtain numbers we use the Number
object.
<HTML>
<SCRIPT>
n = prompt("enter n: ","");
m = prompt("enter m: ","");
x = n + m;
document.write("x = " + x,"<BR>"); // concatenates strings n and m
u = Number(n);
v = Number(m);
r = u + v;
document.write("r = " + r,"<BR>"); // addition of numbers
</SCRIPT>
</HTML>

3.3 Window Object


The window object represents the contents of an entire browser window. The method
open() is a method to open a new window.
win = window.open("OpenMe.html");
fills it with the specified document. The user interface methods are special methods
of the window object. They all display a dialog box asking for user input. JavaScript
has three ready-made dialog boxes that we can use to interact with our visitors. All
three display a (fixed) title and a message, which we can set, and hold execution of
the script until the user responds. The dialog boxes are
alert(message) confirm(message) prompt(message,default)
The most important one is
alert("message");
We use this method whenever we wish to display a message. This message is diplayed
in a dialog box. The user reads the message and chooses OK to dismiss the dialog box.
The confirm(message) carries an OK and a Cancel button, and returns the value
true or false, depending upon which button was clicked. We apply it when we are
offering our visitor a simple Yes/No choice. We use confirm() in an if() test.
The dialog box prompt(message,default) carries a text box and OK and Cancel
buttons. It returns whatever text was entered. We use it to obtain information on
pages where we do not want to have a form.
<HTML>
<HEAD>
<TITLE> window.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
alert("System dialog boxes");
if(confirm("Do you want to do this?"))
alert("Let us begin")
else
alert("In any case we do it")
lnum = prompt("Enter your lucky number",""); // "" clears text box
</SCRIPT>
</BODY>
</HTML>

3.4 Data Types


Data types must not be declared we just define them. JavaScript recognizes the
following types of values:
numbers, such as 18 or 2.81
logical (boolean) values, either true or false
strings such as willi. The String literal is zero or more characters enclosed in
double " or single ' quotation marks.
null (null value). a special keyword denoting a null value. null is also a primitive
value. Since JavaScript is case sensitive, null is not the same as Null, NULL, or any
other variants. The null value behaves as 0 in numeric context and as false in
boolean context.
undefined, a top-level property whose value is undefined. undefined is also a primitive
value.
The assignment operator = assigns a value to its left operand based on the value of
its right operand. For example
i = 4;
x = 3.14159;
found = true;
nfound = false;
str = "xxxyyy";
c = 'X';
Variables can also be declared using the keyword var. For example
var username;
var max = 500;
The first line creates the variable username, but without giving it a value; the second
creates max and assigns 500 to it.
The rules for variable names are the same as those for object names. Names must
start with a letter or underscore and may contain any combinations of letters and
digits. Spaces cannot be used.
3.4. DATA TYPES 53
<HTML>
<HEAD>
<TITLE> DataTypes.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
i = 4;
x = 3.14159;
c = 'X';
found = true;
nfound = false;
str = "xy";
document.write("i = " + i,"<BR>");
document.write("x = " + x,"<BR>");
document.write("c = " + c,"<BR>");
document.write("found = " + found,"<BR>");
document.write("nfound = " + nfound,"<BR>");
document.write("str = " + str,"<BR>");
n = null;
document.write("n = " + n,"<BR>"); // => null
div = n/4;
document.write("div = " + div,"<BR>"); // => 0
r = "The answer is " + 60;
document.write("r = " + r,"<BR>");
s = 60 + " is the answer";
document.write("s = " + s,"<BR>");
myList = ["Berlin", , "London", "Singapore"];
document.write("myList[1] = " + myList[1],"<BR>"); // => undefined
</SCRIPT>
</BODY>
</HTML>

3.5 Special Characters


A string literal is zero or more characters enclosed in double " or single ' quotation
marks. In addition to ordinary characters, we can also include special characters in
strings. The special characters are
Character Meaning
========= =========
\b backspace
\f form feed
\n newline
\r carriage return
\t tab
\' apostrophe or single quote
\" double quote
\\ backslash character \
\XXX character with the Latin-1 encoding specified by up
three octal digits XXX between 0 and 377.
\251 is the octal sequence for the copyright symbol
\xXX character with the Latin-1 encoding specified by the
two hexadecimal digits XX between 00 and FF.
\xA9 is the hexadecimal sequence for the copyright
symbol.
======================================================
=========
The following program shows an application
<HTML>
<HEAD>
<TITLE> Special.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
str1 = "one line \n another line";
document.write("str1 = " + str1,"<BR>"); // one line another line
s = "one line <BR> another line";
document.write("s = " + s,"<BR>"); // s = one line
// another line
str2 = "a tab \t in a string";
document.write("str2 = " + str2,"<BR>");
str3 = "She reads \"The Nonlinear Workbook\" by W.-H. Steeb"
3.5. SPECIAL CHARACTERS 55
document.write("str3 = " + str3,"<BR>");
symbol1 = "\251"
document.write("symbol1 = " + symbol1,"<BR>"); // @
symbol2 = "\xA9"
document.write("symbol2 = " + symbol2,"<BR>"); // @
</SCRIPT>
</BODY>
</HTML>

3.6 Arithmetic Operations


The arithmetic operations are
+ addition
- subtraction
* multiplication
/ division
% modulus (remainder)
++ increment operator
-- decrement operator
As in C, C++ and Java the operators ++ and -- have a preincrement (predecrement)
and postincrement (postdecrement) version. We notice that division is floating
point division. Thus 1/4 returns 0.25. JavaScript also has the shorthand operators
x += y for x = x + y etc. The following program shows how the arithmetic
operators are used.
<HTML>
<HEAD>
<TITLE> JSArith.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
i = 7;
j = -3;
k = i + j;
document.write("<BR> k = " + k + "<BR>");
m = i - j;
document.write("<BR> m = " + m + "<BR>");
n = i*j;
document.write("<BR> n = " + n + "<BR>");
p = i/j;
document.write("<BR> p = " + p + "<BR>");
r = i%j;
document.write("<BR> r = " + r + "<BR>");
i++;
document.write("<BR> i = " + i + "<BR>");
j--;
document.write("<BR> j = " + j + "<BR>");
</SCRIPT>
</BODY>
</HTML>

3.7 Comparison Operators


A comparison operator compares its operands and returns a logical value based on
whether the comparision is true. The operands can be numerical or string values.
Strings are compared based on the standard lexicographical ordering (ASCII table).
The following table describes the comparision operators
Operator Name Description
======== ============
==========================================
== equal returns true if the operands are equal
!= not equal returns true if the operands are not equal
> greater than returns true if the left operand is
greater than the right operand
>= greater than returns true if the left operand is
or equal greater than or equal to the right operand
< less than returns true if the left operand is
less than the right operand
<= less than returns true if the left operand is
or equal less or equal to the right operand
======================================================
=============
<HTML>
<HEAD>
<TITLE> Comparison.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
result1 = (3 == 3);
document.write("result1 = " + result1,"<BR>"); // => true
result2 = (3 != 3);
document.write("result2 = " + result2,"<BR>"); // => false
result3 = (4 > 2);
document.write("result3 = " + result3,"<BR>"); // => true
</SCRIPT>
</BODY>
</HTML>

3.8 Bitwise Operators


Bitwise operators treat their operands as a set of 32 bits (zeros and ones). For
example the decimal number 14 has the binary representation
14 -> 00000000 00000000 00000000 000001110
The bitwise operators are the bitwise AND &, the bitwise OR |, the bitwise XOR ^,
and the bitwise NOT ~. Furthermore we have the left shift <<, the sign-propagating
right shift >> and the zero-fill right shift >>>.
<HTML>
<HEAD>
<TITLE> Bitwise.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
m = 9;
n = 16;
p1 = m & n; // AND
p2 = m | n; // OR
p3 = m ^ n; // XOR
p4 = ~m; // NOT
p5 = ++p4; // increment by 1
document.write("p1 =" + p1,"<BR>"); // => 0
document.write("p2 =" + p2,"<BR>"); // => 25
document.write("p3 =" + p3,"<BR>"); // => 25
document.write("p4 =" + p4,"<BR>"); // => -9
document.write("p5 =" + p5,"<BR>"); // => -9
q1 = 31 >> 2;
document.write("q1 =" + q1,"<BR>"); // => 7
q2 = 3 << 3;
document.write("q2 =" + q2,"<BR>"); // => 24
q3 = -9 >> 2;
document.write("q3 = " + q3,"<BR>"); // => -3
q4 = -9 >>> 2;
document.write("q4 = " + q4,"<BR>"); // => 1073741821
</SCRIPT>
</BODY>
</HTML>
The following program shows how the bitwise operation & and the shift operations
are applied for the Russian farmer multiplication.
3.8. BITWISE OPERATORS 59
<HTML>
<SCRIPT>
x = prompt("Enter m: ","");
y = prompt("Enter n: ","");
m = Number(x);
n = Number(y);
if(m == 0) document.write("0","<BR>");
if(n == 0) document.write("0","<BR>");
if(m == 1) document.write(n,"<BR>");
if(n == 1) document.write(m,"<BR>");
temp = 0;
while(m != 0)
{
document.write(m,"<BR>");
document.write(n,"<BR>");
if((m & 1) == 1)
temp = n + temp;
document.write("temp:" + temp,"<BR>");
m = m >> 1; n = n << 1;
}
document.write(temp);
</SCRIPT>
</HTML>

3.9 Program Flow


JavaScript supports a compact set of statements we can use to control the program
flow. They are
conditional statements: if ... else and switch
loop statements: for, while, do ... while, label, break, continue. Note that
label is not itself a looping statement, but is frequently used with these statements.
There is no goto in JavaScript.
The if ... else, switch, for, while, do ... while conditions have the form as
in Java.
The logical operators
&& logical AND
|| logical OR
! logical NOT
also have the same form as in Java, C and C++. Furthermore the relational operators
are
== equal to < less than <= less than or equal to
!= not equal to > greater than >= greater than equal to
An example is
if((i%3) == 0) { ... }
The for loop and while loop are the same as in Java. For example
...
for(n=1;n<10;n++)
{
x = i*n;
}
The break statement provides a way of escaping from for or while loops. For
example
for(count=0;count<5;count++)
{
answer = 4;
if(answer == (count*count))
break;
}
3.9. PROGRAM FLOW 61
The following program uses two for loops to generate a triangle of asterisks.
<HTML>
<COMMENT> asterisk.html </COMMENT>
<SCRIPT>
n = 9;
for(i=1;i<n;i++)
{
for(j=1;j<=i;j++)
{
document.write("*");
}
document.write("<BR>");
}
</SCRIPT>
</HTML>
A switch statement allows a program to evaluate an expression and attempt to
match the expression’s value to a case label. If a match is found, the program executes
the associated statement.
<HTML>
<COMMENT> MSwitch.html </COMMENT>
<SCRIPT>
MArray = [ 3, 4, 1, 1, 4, -3, 1, 6 ];
for(j=0;j<MArray.length;j++)
{
switch(MArray[j])
{
case 1: document.write("number is 1","<BR>")
break;
case 3: document.write("number is 3","<BR>")
break;
default: document.write("number is not 1 or 3","<BR>")
break;
}
}
</SCRIPT>
</HTML>
<HTML>
62 CHAPTER 3. JAVASCRIPT
<COMMENT> SSwitch.html </COMMENT>
<SCRIPT>
s = new String("bella");
for(j=0;j<s.length;j++)
{
c = s.charAt(j);
document.write("j = " + j, "<BR>");
switch(c)
{
case 'a': document.write("character is 'a'","<BR>")
break;
case 'b': document.write("character is 'b'","<BR>")
break;
default: document.write("character is not 'a' or 'b'","<BR>")
break;
}
}
</SCRIPT>
</HTML>
The continue statement inside a for loop or while loop skips over any remaining
lines and loops round again.
3.9. PROGRAM FLOW 63
The following HTML file gives an example how the for loop and the while loop is
used.
<HTML>
<HEAD>
<TITLE> JSLoop.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
document.write("Hello Egoli");
for(i=1;i<=10;i++)
{
if((i%2) == 0)
{
document.write("<P>Loop: " + i + "</P>");
}
}
alert("We are leaving the first Script block");
</SCRIPT>
<B> Now we use a script again </B>
<SCRIPT>
sum = 0;
count = 0;
while(count < 10)
{
sum += count;
count++;
}
document.write("<BR> sum = " + sum);
</SCRIPT>
<BR><BR>
<B> Again we enter script to set the background colour </B>
<SCRIPT>
document.bgColor = "red";
</SCRIPT>
</BODY>
</HTML>

JavaScript also has a for ... in statement. It uses it to manipulate objects. The
form is
for(varname in objname)
{ forbody }
The following program shows an example of the for ... in statement.
<HTML>
<TITLE> forin.html </TITLE>
<BODY>
<SCRIPT>
languages = ["C++", "Java", "C", "Lisp"];
var language = "C";
var label = 0;
for(var i in languages)
{
if(language == languages[i])
{
document.write("language in list on position: " + i,"<BR>");
label = 1;
}
}
document.write("label = " + label,"<BR>");
if(label == 0)
{ document.write("language not in list"); }
</SCRIPT>
</BODY>
</HTML>

The purpose of the with statement in JavaScript is to permit a number of object


references to be made to the same object (or instance) without having to repeat the
name of that object. A with statement looks as follows
with(object)
{
statements
}
The following with statement specifies that the Math object is the default object.
<HTML>
<HEAD>
<TITLE> with.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
var a = 3.0;
var b = 7.0;
var result1;
var result2;
with(Math)
{
result1 = PI*a*b;
result2 = sin(a)*sin(a) + cos(b)*cos(b);
}
document.write("result1 = " + result1,"<BR>");
document.write("result2 = " + result2,"<BR>");
</SCRIPT>
</BODY>
</HTML>

3.10 Recursion
Recursion plays a central role in computer science. A recursive function is one whose
definition includes a call to itself. More generally, a recursive method is a method
that calls itself either directly or indirectly through another method. A recursion
needs a stopping condition. JavaScript allows recursion.
The following program shows how to use recursion for the generatimg of the Fibonacci
numbers.
<HTML>
<COMMENT> recursion.html </COMMENT>
<SCRIPT>
x = prompt("Enter the position of the Fibonacci number","");
n = Number(x);
function fib(n)
{
if(n<=2) return 1;
else return (fib(n-1)+fib(n-2));
}
result = fib(n);
document.write("Fibonacci number is: " + result,"<BR>");
</SCRIPT>
</HTML>
3.11 Other JavaScript Constructs
The new operator creates a new copy of an object. We can use the new operator
to create an instance of a user-defined object type or one of the predefined object
types
Arrays, Boolean, Date, Functions, Image, Number, Object,
Option, RegExp, String
An example is
mystring = new String("xxyy");
now = new Date();
JavaScript also has the this pointer which refers to the current object. In general,
this refers to the calling object in a method. The syntax is
this
this.object
The object name helps to disambiguate what this means. The this keyword is
also often used to define a new property in a user-defined object. When combined
with the FORM property, this can refer to the current object’s parent form.
We use the var statement to explicitly declare a variable. We may also define a
value for the variable at the same time we declare it, but this is not necessary. The
var statement also sets the scope of a variable when a function is defined inside a
function. For example
var name1 = "value";
name1 = "value";
Used outside of a user-defined function, both of these do exactly the same. Both
create a global variable. A global variable can be accessed from any function in any
window or frame that is currently loaded. If we use var name1 inside a user-defined
function it is local in scope, we only can see it inside the function.
The void operator specifies an expression to be evaluated without returning a value.
The delete operator deletes an object, an object’s property, or an element at a
specified index in an array.

3.12 Functions
JavaScript allows the use of functions indicated by the keyword function. The var
statement inside a function makes the variable local, i.e. it goes out of scope when
we leave the function.
The following HTML file show how functions are used within JavaScript. The
program opens a window where we see
Type something here
a textbox and a button called ClickMe. We enter some text in the textbox, for
example Egoli-Gauteng. Then we click at the Button ClickMe. The method alert
opens a dialog box and displays
The value of the textbox is: Egoli-Gauteng
Then click OK to close the dialog box.
<HTML>
<COMMENT> MyForm.html </COMMENT>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
function testMe(form)
{
Ret = form.box.value;
alert("The value of the textbox is: " + Ret);
}
</SCRIPT>
<FORM>
Type something here <INPUT TYPE="text" NAME="box"><P>
<INPUT TYPE="button" NAME="button" VALUE="ClickMe"
onClick = "testMe(this.form)">
</FORM>
</BODY>
</HTML>

In the following example we show the use of two functions. The HTML commands
to display a table of the square roots of the integers from 1 to 20 are embedded in
the JavaScript code.
<HTML>
<COMMENT> Function.html </COMMENT>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function sqrttable(myWindow)
{
myWindow.document.write("<B> Square Root Table </B><BR>");
myWindow.document.write("<HR>");
myWindow.document.write("<TABLE BORDER=1 CELLSPACING=5>");
myWindow.document.write("<TR><TD>Number</TD><TD>Squareroot</TD></TR>");
for(var i=1;i<=20;i++)
{
myWindow.document.write("<TR><TD>" + i + "</TD><TD>" + Math.sqrt(i) +
"</TD></TR>");
}
myWindow.document.write("</TABLE>");
myWindow.document.write("<HR>");
}
function display()
{
var dynWindow = window.open("","Title","width=200,height=300,scrollbars",
+ "resizable");
sqrttable(dynWindow);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="Show it">
<input type=button value="show table" onClick="display()">
</FORM>
</BODY>
</HTML>

3.13 Creating New Objects


Using a constructor function we can create an object with the following two steps
1. Define the object type by writing a constructor function
2. Create an instance of the object with new
To define an object, create a function for the object type that specifies its name,
properties, and methods. The following HTML file gives an example.
<HTML>
<COMMENT> car.html </COMMENT>
<BODY>
<SCRIPT>
function car(make,model,year)
{
this.make = make
this.model = model
this.year = year
}
mycar = new car("BMW","Z3",2000)
yourcar = new car("Volkswagen","Beetle",1999)
hiscar = new car("Audi","A6",2000)
document.write("<P> mycar = " + mycar.model)
document.write("<P> yourcar = " + yourcar.year)
document.write("<P> hiscar = " + hiscar.make)
</SCRIPT>
</BODY>
</HTML>
3.14. PREDEFINED CORE OBJECTS 71
3.14 Predefined Core Objects
JavaScript provides the predefined core objects
Array, Boolean, String, Math, Number
In the following programs we show how the predefined objects are used.
An array is an ordered set of values that we refer to with a name and an index. The
Array object has methods for manipulating arrays in various ways, such as joining,
reversing, and sorting them. It has a property for determing the array length and
other properties.
An array can be created as follows:
arrayObjectName = new Array(element0,element1,...,elementN)
or
arrayObjectName = new Array(arrayLength)
Array literals are also Array objects. For example the following literal is an Array
object
cities = ["London", "Paris", "Berlin"]
The first program shows how the predefined core object Array is used.
72 CHAPTER 3. JAVASCRIPT
<HTML>
<HEAD>
<TITLE> Array.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
myArray = new Array("C++", "Lisp", "Java");
document.write(myArray.join(),"<BR>");
document.write(myArray.reverse(),"<BR>");
yourArray = new Array(3);
yourArray = myArray.sort();
document.write("yourArray = " + yourArray,"<BR>");
newArray = new Array("Assembler", "VHDL");
concatArray = new Array(5);
concatArray = myArray.concat(newArray);
document.write("concatArray = " + concatArray,"<BR><BR>");
x = new Array(2);
x[0] = 2;
x[1] = 5;
result = x[0]*x[1];
document.write(result,"<BR><BR>"); // => 10
document.write("length = " + x.length,"<BR><BR>"); // => 2
a = new Array(4)
for(i=0;i<4;i++)
{
a[i] = new Array(4)
for(j=0;j<4;j++)
{
a[i][j] = "["+i+","+j+"]"
}
}
for(i=0;i<4;i++)
{
str = "Row "+i+": "
for(j=0;j<4;j++)
{
3.14. PREDEFINED CORE OBJECTS 73
str += a[i][j];
}
document.write(str,"<P>")
}
</SCRIPT>
</BODY>
</HTML>
The Boolean object is a wrapper around the primitive Boolean data type.
<HTML>
<HEAD>
<TITLE> Boolean.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
r = Math.random();
if(r < 0.5)
{
b = new Boolean(true);
}
else
{
b = new Boolean(false);
}
document.write("b = " + b,"<BR>");
</SCRIPT>
</BODY>
</HTML>

The String object is a wrapper around the string primitive data type. We should
not confuse a string literal with the String object. For example
s1 = "egoli"; // creates a string literal value
s2 = new String("egoli"); // creates a String object
We can call any of the methods of the String object on a string literal value.
JavaScript automatically converts the string literal to a temporary String object,
calls the method, and then discards the temporary String object.
The following program shows an application of several methods of the String object.
<HTML>
<HEAD>
<TITLE> String.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
mystring = new String("Hello Egoli");
lgth = mystring.length;
document.write("lgth = " + lgth,"<BR><BR>"); // => 11
ch = mystring.charAt(3);
document.write("ch = " + ch,"<BR><BR>"); // => l
chcode = mystring.charCodeAt(3);
document.write("chcode = " + chcode,"<BR><BR>"); // => 108
sub = mystring.substring(2,6);
document.write("sub = " + sub,"<BR><BR>"); // => llo
lower = mystring.toLowerCase();
document.write("lower = " + lower,"<BR><BR>"); // => hello egoli
yourstring = new String("willi-hans");
upper = yourstring.toUpperCase();
document.write("upper = " + upper,"<BR><BR>"); // => WILLI-HANS
string1 = new String("carl-");
string2 = new String("otto");
string3 = string1.concat(string2);
document.write("string3 = " + string3,"<BR><BR>"); // => carl-otto

str = new String("12 34 45");


myarray = new Array(3);
myarray = str.split(" ");
document.write("myarray[0] = " + myarray[0],"<BR>"); // => 12
document.write("myarray[1] = " + myarray[1],"<BR>"); // => 34
document.write("myarray[2] = " + myarray[2],"<BR>"); // => 45
</SCRIPT>
</BODY>
</HTML>
The top-level predefined function eval evaluates a string of JavaScript code without
reference to a particular object. The syntax is
eval(expr)
where expr is a string to be evaluated.
<HTML>
<HEAD>
<TITLE> Eval.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
s1 = "3 + 3";
s2 = new String("3 + 3");
document.write("result1 = " + eval(s1),"<BR>"); // => 6
document.write("result2 = " + eval(s2),"<BR>"); // => 3 + 3
</SCRIPT>
</BODY>
</HTML>
76 CHAPTER 3. JAVASCRIPT
The predefined Math object has properties for mathematical constants and functions.
Standard mathematical functions are methods of Math. For example
abs, sin, cos, tan, acos, asin, atan, exp, log
ceil, floor, min, max, pow, round, sqrt
An application is as follows:
<HTML>
<HEAD>
<TITLE> Math.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
document.write(Math.sin(1.14159),"<BR>");
document.write(Math.sin(Math.PI),"<BR><BR>");
r = 2.0; theta = 1.0;
with(Math)
{
a = PI*r*r;
y = r*sin(theta)
x = r*cos(theta)
}
document.write("a = " + a,"<BR>");
document.write("y = " + y,"<BR>");
document.write("x = " + x,"<BR>");
z = Math.random();
document.write("z = " + z,"<BR>");
r1 = Math.max(3,4,2,7,1);
document.write("r1 = " + r1,"<BR>"); // 7
r2 = Math.min(3,1,10,20,2,3,9);
document.write("r2 = " + r2,"<BR>"); // 1
</SCRIPT>
</BODY>
</HTML>
The Number object has properties for numerical constants, such as maximum value,
not-a-number (NaN), and infinity. We cannot change the values of these constants.
<HTML>
<HEAD>
<TITLE> Number.html </TITLE>
</HEAD>
<BODY>
<SCRIPT>
biggestNum = Number.MAX_VALUE;
document.write("biggestNum =" + biggestNum,"<BR>");
smallestNum = Number.MIN_VALUE;
document.write("smallestNum = " + smallestNum,"<BR>");
diff = biggestNum - smallestNum;
document.write("diff = " + diff,"<BR>");
infiniteNum = Number.POSITIVE_INFINITY;
document.write("infiniteNum = " + infiniteNum,"<BR>");
negInfiniteNum = Number.NEGATIVE_INFINITY;
document.write("negInfiniteNum = " + negInfiniteNum,"<BR>");
notANum = Number.NaN;
document.write("notANum = " + notANum,"<BR>");
</SCRIPT>
</BODY>
</HTML>

3.15 Object object


JavaScript supports a generic Object() object, which we can use to make new
objects. The following two programs show how to create and use one-dimensional
arrays using the Object object. In the first program we enter the colour and click
the Find button. The hextriplet is displayed. In the second program we enter the
name of the customer and click the Find button. This provides us with the complete
information about the customer. The method
String toLowerCase()
converts a string to all lowercase.
<HTML>
<HEAD>
<TITLE> DataBase.html </TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
Colour = new Object()
Colour[0]=10
Colour[1]="aliceblue"
Colour[2]="antiquewhite"
Colour[3]="aqua"
Colour[4]="aquamarine"
Colour[5]="azure"
Colour[6]="beige"
Colour[7]="bisque"
Colour[8]="black"
Colour[9]="blanchedalmond"
Colour[10]="blue"
Data = new Object()
Data[1]="f0f8ff"
Data[2]="faebd7"
Data[3]="00ffff"
Data[4]="7fffd4"
Data[5]="f0ffff"
Data[6]="f5f5dc"
Data[7]="ffe4c4"
Data[8]="000000"
Data[9]="ffebcd"
Data[10]="0000ff"

function checkDatabase()
{
var Found = false;
var Item = document.testform.color.value.toLowerCase();
Count = 1;
while(Count <= Colour[0])
{
if(Item == Colour[Count])
{
Found = true;
alert("The hex triplet for '" + Item + "' is #" + Data[Count]);
break;
}
Count++;
} // end while
if(!Found)
alert("The color '" + Item +"' is not listed in the database");
}
</SCRIPT>
<FORM NAME="testform" onSubmit="checkDatabase()">
Specify a color name, then click the
"Find" button to see its hex triplet:
<BR>
<INPUT TYPE="text" NAME="color" VALUE="" onClick=0> <P>
<INPUT TYPE="button" NAME="button" VALUE="Find"
onClick="checkDatabase()">
</FORM>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE> DataBase2.html </TITLE>
</HEAD>
<SCRIPT LANGUAGE="JavaScript">
Names = new Object()
Names[0]=6
Names[1]="cooper"
Names[2]="smith"
Names[3]="jones"
Names[4]="michaels"
Names[5]="avery"
Names[6]="baldwin"
Data = new Object()
Data[1]="Olli|Cooper|44 Porto Street|666-000"
Data[2]="John|Smith|123 Main Street|555-1111"
Data[3]="Fred|Jones|PO Box 5|555-2222"
Data[4]="Gabby|Michaels|555 Maplewood|555-3333"
Data[5]="Alice|Avery|1006 Pike Place|555-4444"
Data[6]="Steven|Baldwin|5 Covey Ave|555=5555"
function checkDatabase()
{
var Found = false; // local variable
var Item = document.testform.customer.value.toLowerCase();
for(Count=1;Count<=Names[0];Count++)
{
if(Item == Names[Count])
{
Found = true;
var Ret = parser(Data[Count], "|");
var Temp = "";
for(i=1;i<=Ret[0];i++)
{
Temp += Ret[i] + "\n";
}
alert(Temp);
break;
}
}
if(!Found)
alert("Sorry, the name '" + Item +"' is not listed in the database.")
3.15. OBJECT OBJECT 81
} // end function checkDatabase()
function parser(InString,Sep)
{
NumSeps=1;
for(Count=1;Count<InString.length;Count++)
{
if(InString.charAt(Count)==Sep)
NumSeps++;
}
parse = new Object();
Start=0; Count=1; ParseMark=0;
LoopCtrl=1;
while(LoopCtrl==1)
{
ParseMark = InString.indexOf(Sep,ParseMark);
TestMark = ParseMark+0;
if((TestMark==0) || (TestMark==-1))
{
parse[Count]= InString.substring(Start,InString.length);
LoopCtrl=0;
break;
}
parse[Count] = InString.substring(Start,ParseMark);
Start=ParseMark+1;
ParseMark=Start;
Count++;
}
parse[0]=Count;
return (parse);
} // end function parser()
</SCRIPT>
<FORM NAME="testform" onSubmit="checkDatabase()">
Enter the customer's name, then click the "Find" button:
<BR>
<INPUT TYPE="text" NAME="customer" VALUE="" onClick=0> <P>
<INPUT TYPE="button" NAME="button" VALUE="Find"
onClick="checkDatabase()">
</FORM>
</BODY>
</HTML>

3.16 Date Object


The Date object is used to work with dates and times. We create an instance of the
Date object with the new keyword. To store the current date in a variable called
my_date:
my_date = new Date()
After creating an instance of the Date object, we can access all the methods of the
object from the my_date variable. We have to keep in mind that the method
getMonth()
returns the month of a Date object from 0-11, where 0=January, 1=February, etc.
The following program shows an example.
<HTML>
<HEAD> </HEAD>
<!-- File name: Today.html -->
<BODY>
<SCRIPT LANGUAGE="JavaScript">
document.write("<CENTER><H2> Today is </H2><BR>");
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth() + 1;
var yy = date.getYear();
if(dd < 10) dd = "0" + dd;
if(mm < 10) mm = "0" + mm;
if(yy < 10) yy = "0" + yy;
document.write("<B>" + dd + "." + mm + "." + yy + "</B>");
document.write("</CENTER>");
</SCRIPT>
</BODY>
</HTML>
3.16. DATE OBJECT 83
In the second program we test whether the present time is am or pm.
<HTML>
<HEAD>
<TITLE> clockset.html </TITLE>
</HEAD>
<SCRIPT LANGUAGE="JavaScript">
function setClock()
{
now = new Date();
var CurHour = now.getHours();
var CurMinute = now.getMinutes();
now = null;
if(CurHour >= 12)
{
CurHour = CurHour - 12;
Ampm = "pm";
}
else
Ampm = "am";
if(CurHour == 0)
CurHour = "12";
if(CurMinute < 10)
CurMinute = "0" + CurMinute
else
CurMinute = "" + CurMinute
CurHour = "" + CurHour;
Time = CurHour + ":" + CurMinute + Ampm
document.clocktext.clock.value = Time;
setTimeout("setClock()",1000*30)
}
</SCRIPT>
</HEAD>
<BODY onLoad = "setClock()">
<FORM NAME = "clocktext">
<INPUT TYPE="text" NAME="clock" VALUE="" SIZE=8>
</FORM>
</BODY>
</HTML>

3.17 Regular Expression


Regular expressions are patterns used to match character combinations in strings.
In JavaScript, regular expressions are also objects. These patterns are used with
the exec and test methods of RegExp, and the match, replace, search and split
methods of String. We can construct regular expression either using the constructor
function of the RegExp object, for example
re = new RegExp("abc+de")
or using an object initializer, for example
re = /abc+de/
Using the constructor function provides runtime compilation of the regular expression.
Regular expression have two optional flags that allow for global and case
insensitive searching. To indicate a global search we use the g flag. To indicate
a case insensitive search we use the i flag. These flags can be used separatly or
together in either order, and are included as part of the regular expression.
The methods that use regular expressions are:
exec A RegExp methods that executes a search for a match in a string.
It returns an array of information.
test A RegExp method that tests for a match in a string.
It returns true or false.
match A String method that executes a search for a match in a string.
It returns an array of information or null on a mismatch.
search A String method that tests for a match in a string.
It returns the index of the match, or -1 if the search fails.
replace A String method that executes a search for a match in a string,
and replaces the matched substring with the replacement
substring.
split A String method that uses a regular expression or a fixed
string to break a string into an array of substrings.
Pattern matching in JavaScript and Perl is closely related.

There are a large number of special characters in regular expressions. In the following
we list some of them.
The backslash \ indicates that the next character is special and not to be interpreted
literally. For example, /b/ matches the character b. However /\b/ means match a
word boundary.
The character ^ indicates matches at the beginning of input or line. For example,
/^X/ does not match the X in "in X" but does match it in "Xenia".
The character $ indicates matches at end of input or line. For example, t$ does not
match the t in "otto", but does match it in "art".
Using the asterisk * we can test whether the preceding characters matches 0 or more
times.
The + indicates matches of the preceding characters 1 or more times.
Using ? we can find the matches of the preceding characters 0 or 1 time. For example,
/el?le?/ matches the "el" in "angel" and "le" in "angle".
The command (x) matches "x" and remembers the match. Thus including parentheses
in a regular expression pattern causes the corresponding submatch to be
remembered. For example, /x(y)x/ matches the string "xyx" and remembers y.
The commmand x | y matches either x or y.
Let n be a positive integer. Then {n} matches exactly n occurrences of the preceding
character.
[xyz] is a character set. It matches any one of the enclosed characters. We can
specify a range of characters by using a hyphen. For example, [abcd] is the same
as [a-d]. The expression [^xyz] is a negated or complemented character set. It
matches anything that is not included in the brackets. Again we can specify a range
of characters by using a hyphen.
The command [\b] matches a backspace and \b matches a word boundary such
as space. The command \d matches a digit character. This is equivalent to [0-9].
With the command \D we match any non-digit character. This is equivalent to
[^0-9]. The command \f matches a form-feed, \n a line-feed, \r a carriage return,
\t a tab.
With \w we can match any alphanumeric character including underscore. It is
equivalent to [A-Za-z0-9_].

<HTML>
<COMMENT> RegExp.html </COMMENT>
<BODY>
<SCRIPT>
re0 = /xyx/
result0 = re0.exec("czxyyyxer")
document.writeln(result0)
// => null
re1 = /xyx/
result1 = re1.exec("czxyxer")
document.writeln(result1)
// => xyx
re2 = /^X/
result2 = re2.exec("Xylon")
document.writeln(result2)
// => X
re3 = /^X/
result3 = re3.exec("ylonX")
document.writeln(result3)
// => null
re4 = /t$/
result4 = re4.exec("art")
document.writeln(result4)
// => t
re5 = /t$/
result5 = re5.exec("otto")
document.writeln(result5)
// => null
re6 = /le?/
result6 = re6.exec("angle")
document.writeln(result6)
// => le
re7 = new RegExp("a+")
result7 = re7.exec("Cbaabbaxc")
document.writeln(result7)
// => aa

re8 = /xy+x/
result8 = re8.exec("czxyyyxer")
document.writeln(result8)
// => xyyyx
re9 = /x(y+)x/
result9 = re9.exec("czxyyyxer")
document.writeln(result9)
// => xyyyx, yyy
re10 = /xx aa$\n/
result10 = re10.test("yybb ++")
document.writeln(result10)
// => false
// \w matches any alphanumeric characters
// \s matches a single character other than white space
re11 = /(\w+)\s(\w+)/
str1 = "willi hans"
result11 = str1.replace(re11,"$2,$1")
document.writeln(result11)
// hans willi
re12 = new RegExp("[a-z]")
result12 = re12.exec("12345ac")
document.writeln(result12)
// => a
</SCRIPT>
</BODY>
</HTML>

3.18 Prompts
The prompt is a special method of the window object. It displays a dialog box with
a single-text box and Cancel and OK buttons
prompt(message,defaultText)
The word prompt tells JavaScript that a dialog box will appear on the screen. The
word message is the text that is displayed in the prompt box. Lastly, the word
defaultText is the text displayed in the text box.
<HTML>
<HEAD>
<COMMENT> prompt.html </COMMENT>
</HEAD>
<BODY bgcolor=yellow text=black>
<SCRIPT LANGUAGE="JavaScript">
var i;
var j;
var k;
i = 1;
j = 1;
document.write("<H4>");
var m = prompt("enter the number of Fibonacci numbers:",0);
document.write(i + "<BR>");
document.write(j + "<BR>");
k = i + j;
document.write(k + "<BR>");
for(var n=3;n<=m-1;n++)
{
i = j;
j = k;
k = i + j;
document.write(k + "<BR>");
}
</SCRIPT>
</BODY>
</HTML>

3.19 Events
JavaScript programs are typically event-driven. Events are actions that occur on
the Web page, usually of something the user does. Examples are: a button click is
an event, giving focus to a form element, resizing the page, submitting a form.
An event, then, is the action which triggers an event handler. The event handler
specifies which JavaScript code to execute. Often, event handlers are placed within
the HTML tag which creates the object on which the event acts. For example, a
hyperlink is subject to a mouseover event, meaning that its event handler will be
triggered when a mouse passes over the link. The JavaScript which is called by the
event handler may be any valid JavaScript code: a single statement or a series of
statements, although most often it is a function call.
The set of all events which may occur, and the particular page elements on which
they can occur, is part of the Document Object Model (DOM), and not of JavaScript
itself. Thus, Netscape and Microsoft do not share the exact same set of events, nor
are all page elements subject to the same events between browsers.
The table below displays some of the most commonly used events supported in both
DOM’s.
Event Occurs when ... Event Handler
========== =========================== =============
click User clicks on form or link onclick
change User changes value of text, onchange
textarea, or select element
focus User gives form element onfocus
input focus
blur User removes input focus onblur
from form element
mouseover User moves mouse pointer onmouseover
over a link or anchor
mouseout User moves mouse pointer onmouseout
off of link or anchor
select User selects form element's onselect
input field
submit User submits a form onsubmit
resize User resizes the browser onresize
window
load User loads the page in the onload
Navigator

unload User exits the page onunload


The following program shows an example.
<HTML>
<COMMENT> Event1.html </COMMENT>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
window.onresize = message;
function message()
{
alert("The window has been resized!");
}
</SCRIPT>
</HEAD>
<BODY>
Please resize the window.
</BODY>
</HTML>

In the following example we demonstrate the onBlur event and can see how it is
possible to force a user to enter valid information into a form. The user is forced to
enter a number from 0 to 9.
<HTML>
<COMMENT> onblur.html </COMMENT>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function isDigit(c)
{
return ((c >= "0") && (c <= "9"))
}
function checkValue(field)
{
if(!isDigit(field.value))
{
alert("You must enter a digit from 0 to 9.");
field.focus();
}
if((field.value.length < 0) || (parseInt(field.value) >= 10))
{
alert("You did not enter a digit from 0 to 9");
field.focus();
}
}
</SCRIPT>
<FORM>
Please enter a number from 0 to 9:
<INPUT TYPE=TEXT NAME="number" SIZE=3 onBlur="checkValue(this);">
<BR><BR>
Please enter your name:
<INPUT TYPE=TEXT NAME="name" SIZE=25>
</FORM>
</BODY>
</HTML>

The following example demonstrates the onChange event. We built a pulldown menu
that allows users to jump to different websites or URLs.
<HTML>
<COMMENT> onchange.html </COMMENT>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function jumpTo(URL_List)
{
var URL = URL_List.options[URL_List.selectedIndex].value;
window.location.href = URL;
}
</SCRIPT>
<FORM>
<SELECT NAME="site" onChange="jumpTo(this);">
<OPTION VALUE="http://www.fhso.ch/~steeb"> Applied University Solothurn
<OPTION VALUE="http://issc.rau.ac.za"> ISSC
</SELECT>
</FORM>
</BODY>
</HTML>

The following example demonstrates the onClick event.


<HTML>
<COMMENT> onclick.html </COMMENT>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function informuser()
{
alert("I told you not to press that button");
}
</SCRIPT>
<FORM>
<INPUT TYPE=button NAME="button" VALUE="Do not press this button"
onClick="informuser();">
</FORM>
</BODY>
</HTML>

The following example demonstrates the onFocus event.


<HTML>
<COMMENT> onfocus.html </COMMENT>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var alreadyWarned = false;
function displayHelp()
{
if(!alreadyWarned)
{
alert("Enter your phone number in (xx) xxx-xxxx format");
alreadyWarned = true;
}
}
</SCRIPT>
<FORM>
<INPUT TYPE=text NAME="phonenumber" SIZE=15
onFocus = "displayHelp();">
</FORM>
</BODY>
</HTML>

3.20 Java Applets and JavaScript


JavaScript can be used to control the behaviour of a Java applet without knowing
much about the design of the applet. All public variables, methods, and properties
are available for JavaScript access. Each applet in a document is reflected in
JavaScript as
document.appletName
where appletName is the value of the NAME attribute of the <APPLET> tag.
The following Java program Welcome.java and the HTML program Welcome.html
show an application. We define a
public void setString(String s)
method that accepts a string argument, assigns it to myString, and calls the
repaint() method. The file Welcome.java is given by
// Welcome.java
import java.applet.Applet;
import java.awt.Graphics;
public class Welcome extends Applet
{
String myString;
public void init()
{
myString = new String("Welcome to ISSC")
}
public void paint(Graphics g)
{
g.drawString(myString,25,25);
}
public void setString(String s)
{
myString = s;
repaint();
}
}

The HTML file is given by


<HTML>
<COMMENT> Welcome.html </COMMENT>
<BODY>
<APPLET CODE="Welcome.class" NAME="Welcome" WIDTH=275 HEIGHT=135>
</APPLET>
<SCRIPT>
function insert()
{
document.Welcome.setString(document.myform.str.value)
}
</SCRIPT>
<FORM NAME="myform">
<INPUT TYPE="button" VALUE="SET STRING" onClick="insert()">
<INPUT TYPE="text" SIZE="20" NAME="str">
</FORM>
</BODY>
</HTML>

3.21 JavaScript and XML


The Document Object Model (DOM) is the model that describes how all elements
in the HTML page, like input fields, images, paragraphcs etc., are related to the
topmost structure: the document itself. By calling the elements by its proper DOM
name, we can influence it. The Level 1 DOM Recommendation has been developed
by the W3C to provide any programming language with access to each part of an
XML document. Thus we can use JavaScript to parse an XML document. Notice
that DOM is based on a tree structure. Our XML file describes a polynomial. Our
polynomial consists of two terms, namely
p(x; y) = 2x3y2 ¡ 4y5 :
<?xml version="1.0"?>
<!-- poly.xml -->
<polynomial>
<term>
<factor> 2 </factor>
<variable>
<name> x </name>
<exponent> 3 </exponent>
</variable>
<variable>
<name> y </name>
<exponent> 2 </exponent>
</variable>
</term>
<term>
<factor> -4 </factor>
<variable>
<name> x </name>
<exponent> 0 </exponent>
</variable>
<variable>
<name> y </name>
<exponent> 5 </exponent>
</variable>
</term>
</polynomial>

Knowing the exact structure of the DOM tree, we can walk through it in search of
the element we want to find using the commands
parentNode, childNodes[0], childNodes[1], ... , firstChild, lastChild
The following HTML-file with the embedded JavaScript code finds elements in the
tree structure of the polynomial.
<!-- polynomials -->
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="ONLOAD">
Document = polynom.XMLDocument;
factor1.innerText=
Document.documentElement.firstChild.firstChild.text;
name1.innerText=
Document.documentElement.firstChild.childNodes[1].firstChild.text;
factor2.innerText=
Document.documentElement.lastChild.firstChild.text;
</SCRIPT>
</HEAD>
<BODY>
<xml id="polynom" src="file://c:\books\java\poly.xml"></xml>
Factor 1: <span id="factor1"></span>
<BR>
Name 1: <span id="name1"></span>
<BR>
Factor 2: <span id="factor2"></span>
</BODY>
</HTML>
The output is:
Factor 1: 2
Name 1: x
Factor 2: -4

3.22 Loading a js-file


Given a js file, for example the file asterik.js
3.22. LOADING A JS-FILE 99
n = 9;
for(i=1;i<n;i++)
{
for(j=1;j<=i;j++)
{
document.write("*");
}
document.write("<BR>");
}
The file is loaded in a HTML file as follows
<HTML>
<SCRIPT type="text/javascript">
function staticLoad(url)
{
document.write('<script src="',url,
'"type="text/JavaScript"><\/script>');
}
staticLoad("asterisk.js");
</SCRIPT>
</HTML>
In the following two programs display.html and display.js we display the time
with the time interval of 1000ms (1 second).
<HTML>
<!-- display.js -->
<SCRIPT src="display.js">
</SCRIPT>
<BODY onload="show_time(); window.setInterval(show_time,1000);">
</BODY>
</HTML>
The display.js file is
function show_time()
{
document.open();
document.write(
"<HTML> \n" +
" \n" +
"<SCRIPT src=\"display.js\"> \n" +
"<\/SCRIPT> \n" +
" \n" +
"<BODY onload=\"window.setInterval(show_time,1000);\"> \n" +
" \n" +
"<B> Date: <\/B><BR>" + Date() + "<BR><BR> \n" +
" \n" +
"<FORM> \n" +
"<\/FORM> \n" +
" \n" +
"<\/BODY> \n" +
"<\/HTML>");
document.close(); // force render
}
Chapter 4
Resources and Web Sites
There are a large number of web sites which provide information, news and tutorials
of Java, HTML and JavaScript. Furthermore there are web sites to download new
versions of Java, HTML and JavaScript.
The main web sites of SUN Microsystems for Java are
http://java.sun.com/
http://java.sun.com/jdc/
http://developer.java.sun.com/
Another useful web site for Java, HTML and JavaScript is “The Web Developer’s
Virtual Library”
http://wdvl.com/WDVL/About.html
The WDVL has more than 2000 pages and some 6000 links.
The web site
http://www.niu.edu/acad/english/htmlref.html
provides an HTML reference guide. The web site
http://developer.netscape.com/docs/
provides links to technical manuals and articles for Java, JavaScript and HTML.
The offical word on the latest standard in HTML can be found on the web site
http://www.w3.org/pub/WWW/MarkUp/MarkUp.html
101
102 CHAPTER 4. RESOURCES AND WEB SITES
Information about XML can be found on the web sites
http://www.w3.org/XML/
http://www.w3schools.com/
Bibliography
[1] Horton Ivor, Beginning Java 2, WROX Press, Birmingham, UK, 1999
[2] Jaworski Jamie, Java 1.2 Unleashed, SAMS NET, Macmillan Computer Publishing,
USA, 1998
[3] Johnson Marc, JavaScript Manual of Style, Macmillan Computer Publishing,
USA, 1996
[4] McComb Gordon, JavaScript Sourcebook, Wiley Computer Publishing, New
York, 1996
[5] Willi-Hans Steeb, The Nonlinear Workbook: Chaos, Fractals, Cellular Automata,
Neural Networks, Genetic Algorithms, Fuzzy Logic with C++, Java,
SymbolicC++ and Reduce Programs, World Scientific, Singapore, 1999
[6] Tan Kiat Shi, Willi-Hans Steeb and Yorick Hardy, SymbolicC++: An Introduction
to Computer Algebra Using Object-Oriented Programming, 2nd edition
Springer-Verlag, London, 2000

You might also like