Documente Academic
Documente Profesional
Documente Cultură
Web
Designing ACeL
This hands-on workshop introduces you to the basic
principles of Web site design and authoring using HTML. AMITY
You will then use FrontPage to create your web page or site UNIVERSITY
and publish it to the World Wide Web for viewing.
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.
Table of Contents
Syllabus .......................................................................................................................................... 2
Module I : Introduction to HTML .............................................................................................. 6
Basic Web Design ....................................................................................................................... 6
Developing a Web Site ................................................................................................................ 6
Designing Navigation Bars.......................................................................................................... 8
Page Design ................................................................................................................................. 9
Design Concepts ........................................................................................................................ 11
Introduction to HTML ............................................................................................................... 12
Introduction to FrontPage .......................................................................................................... 17
Page Properties ...................................................................................................................... 19
Working with Text ................................................................................................................ 21
Formatting Text ..................................................................................................................... 22
Inserting a Picture .................................................................................................................. 24
Hyperlinks ............................................................................................................................. 27
Saving Your Web Page ......................................................................................................... 30
Tables .................................................................................................................................... 31
Creating a Website .................................................................................................................... 38
HTML TAG LIST ..................................................................................................................... 57
MODULE II : Advance HTML & CSS .................................................................................. 72
HTML Versions ........................................................................................................................ 72
HTML Support .......................................................................................................................... 72
Getting ready to create a website............................................................................................... 73
HTML Structure ........................................................................................................................ 75
HTML Header ........................................................................................................................... 76
Elements in the Header.......................................................................................................... 78
HTML Body .............................................................................................................................. 82
HTML Frames ........................................................................................................................... 84
HTML Element Categories ....................................................................................................... 89
HTML Elements ........................................................................................................................ 93
HTML Headers and Paragraphs ................................................................................................ 96
HTML Lists ............................................................................................................................. 100
Ordered Lists ....................................................................................................................... 100
Unordered Lists ................................................................................................................... 101
Definition Lists .................................................................................................................... 103
HTML Tables .......................................................................................................................... 103
HTML Attributes ..................................................................................................................... 110
HTML Formatting ................................................................................................................... 112
HTML Line Formatting........................................................................................................... 114
HTML Text Formatting........................................................................................................... 116
HTML SPAN and DIV Elements ............................................................................................ 118
HTML Characters.................................................................................................................... 120
Style Sheets ............................................................................................................................. 121
CSS Properties......................................................................................................................... 125
HTML Graphics ...................................................................................................................... 132
HTML Sound .......................................................................................................................... 136
HTML Links .............................................................................................................................. 136
HTML Forms .......................................................................................................................... 140
HTML Script Embedding ........................................................................................................ 145
Using Applets .......................................................................................................................... 150
XHTML ................................................................................................................................... 152
HTML Tags ............................................................................................................................. 154
HTML Terms .......................................................................................................................... 157
Recommended Reading ........................................................................................................... 159
Module III : XML & Java Script ............................................................................................ 160
Chapter : 1 ............................................................................................................................... 160
1 Introduction ...................................................................................................................... 160
Chapter 2 ................................................................................................................................. 160
XML .................................................................................................................................... 160
Chapter 3 ................................................................................................................................. 187
JavaScript ............................................................................................................................ 187
Chapter 4 ................................................................................................................................. 248
Bibliography ............................................................................................................................ 250
Module I : Introduction to HTML
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 The Five Golden Rules
Web files and folders should not have any spaces and be in lowercase. Use the
o
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.
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.
Site ID.
Global navigation bar.
You are here indicator.
Local navigation bar.
Breadcrumb trail
Small text version of navigation bars (optional)
Source: Dont 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:
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
Has to convey site identity and mission: what it is and what its
for.
Has to provide an overview of what the site has to offer, and how
its organized.
Should provide a way to search the site.
Has to appeal to diverse interests.
Source: Dont 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 sites target audience?
o Do the graphics mesh with the sites intended purpose?
o Do the tone and style of the language complement the sites 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. Dont 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.
<HTML>
<HEAD>
</HEAD>
<BODY>
</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.
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. l
</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:
Introduction to FrontPage
What is FrontPage?
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 cant see
anything at the moment because we havent 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.
Click back on the Page view to begin building your web page.
Page Views
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
Background
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 dont, 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. L
To insert a line break (<BR>) instead of a paragraph break, use the Shift-Enter
combination. l
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.
Dont 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.
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
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
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.
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 cant 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.
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.
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.
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:
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 pages 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
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:
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
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.
Its wise to save your web page periodically so that you dont 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.)
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.
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.
E.g.
E.g.
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.
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.
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.
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 2002s 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.
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
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), theyre important.
Saving Your Web Site
If you havent already, youll 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.
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
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.
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, well 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.
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. Dont 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.
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
Your initial view of your Home Page (index.htm) should look like the image below.
browsers such as Netscape and AOL to ensure compatibility.
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.
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.
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.
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 Names Home Page where First Names 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
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.
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 hasnt 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
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.
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.
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.
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.
Trinitys 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.
Dont 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
Once the publish
dialog box.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.
BASIC TAGS
<html>...</html>
<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>
<body bgcolor="?">
<body background="filename.xxx">
<body text="color">
<body link="color">
<body alink="color">
<body vlink="color">
<p>...</p>
<p align=?>
<br>
<blockquote>...</blockquote>
LISTS
<dl>...</dl>
<dt>
<dd>
<ol>...</ol>
<li>...</li>
<div align=?>
A generic tag used to format large blocks of HTML, also used for stylesheets
TEXT ATTRIBUTES
<pre>...</pre>
<hl>...</hl> to <h6>...</h6>
<b>...</b>
<i>...</i>
<tt>...</tt>
<cite>...</cite>
<em>...</em>
<strong>...</strong>
Emphasizes a word (with italic or bold)
<sub>...</sub>
<sup>...</sup>
FONT ATTRIBUTES
<font>...</font>
<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>
<font color="color">...</font>
Sets the font color using hexadecimal code or color <font color=blue>
IMAGES
<img>
IMAGE FORMULA
<IMG SRC=filename.xxx>
LINKS
URL FORMULA
<A HREF=URL>LinkText</A>
<a>...</a>
<a href="URL#name">...</a>
<a name="name">...</a>
<a href="mailto:email@something.com">...</a>
TABLES
<table>...</table>
Generates a table
<table border="pixels">
<table cellspacing="pixels">
<table cellpadding="pixels">
<td>...</td>
Defines a table data cell
<td colspan="columns">
<td rowspan="rows">
<td nowrap>
<th>...</th>
<tr>...</tr>
Sets the vertical alignment of a row or cell to the top, middle, or bottom
FRAMES
<frameset>...</frameset>
<frameset rows="value,value">
<noframes>...</noframes>
<frame src="?">
<frame name="name">
<frame marginwidth="#">
<frame marginheight="#">
<frame scrolling="value">
<frame noresize>
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=?>
<hr width=?>
<hr noshade>
FORMS
<form>...</form>
<form action="url">
Designates the path of the script to process input from the form
<form method="get|post">
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
<select name="name">...</select>
<input type="checkbox">
<input type="hidden">
<input type="image">
<input type="password">
<input type="radio">
<input type="text">
<input type="submit">
<input type="reset">
&
&
Ampersand
™
Trademark
®
Registered trademark
©
Copyright
"
"
“
Left quote
”
Right quote
⁄
Forward slash
<
<
>
>
»
«
—
Em-dash
£
°
30
Degree
¼
Quarter
½
Half
¾
Three quarters
·
Middle dot
¡
♠
?
♣
♥
♦
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.
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
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.
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>
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
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.
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.
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.
An example:
<link href="style.css" rel="stylesheet" type="text/css">
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> 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">
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
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.
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.
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.
<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%.
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:
Categories
HTML Guide Contents Page
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.
List-item Elements
Name Description Comment
DIR Directory List Depreciated
DL Definition List -
LI List Item -
OL Ordered (numbered) List -
UL Unordered List -
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.
Inline HTML Elements
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:
http://www.comptechdoc.org/guides/htmlguide/htmlelement.html (2 of 3)7/21/2003
7:44:47 AM HTML Elements
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 <span> 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.
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:
2 In the last paragraph, the following line: Many systems are set up to capture the
<CTRL><ALT><DEL> 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.
Ordered Lists
<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.
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
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
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 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
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.
<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
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
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.
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><b> tag </b>.<br>This is an example of the
<big><big> tag</big>.<br>This is an example of the <em><em>
tag</em><br>This is an example of the <i><i> tag</i>.<br>This is an example
of the <small><small> tag</small>.<br>This is an example of the
<strike><strike> tag</strike>.<br>This is an example of the
<strong><strong> tag<strong>.<br>This is an example of the
<sup><sup> tag<sup>.<br>This is an example of the <sub><sub>
tag<sub>.<br>This is an example of the <tt><tt> tag<tt>.<br>This is an
example of the <u><u> tag</u><br>This is an example of the
<var><var> tag</var><br>
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.
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 <span> 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.
Although these special characters may displayed without the semicolon at the end, it is
the proper standard to use the semicolon.
Style Sheets
The section "CSS Properties" contains a more complete list of parameters and the
elements they work with.
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.
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
border- Set the top border width See border All {border- No
top style, and color. width, style, top:
and color medium
solid
green}
border- Set the top border width thin, medium, All {border- No
top- thick, or top-width:
width length value thin}
border- Sets Border width. thin, medium, All {border- No
width thick, or width: 8}
length value
clear Determines where none, left, All {clear: left} No
floating elements are right, both
allowed.
float Specifies how text is none, left, All {float: left} No
wrapped and where it is right
aligned.
height Height of element auto or a Block elements and {height: No
height value IMG, INPUT, 200}
TEXTAREA,
SELECT, and
OBJECT
Classification Properties
Name Description Possible Values Element Example inherited
Types
display Sets the type of block, inline, list- All {display: list- No
element. item, none item}
list-style Sets list style type and/orSee list-style-type and list- List- {list-style: circle} Yes
position. style-position item
list-style- Sets image to be used as url List- {list-style-image: Yes
image the list item marker. item url(this.gif)}
list-style- Sets list style type. circle, disc, decimal, lower- List- {list-style-type: Yes
type alpha, lower-roman, none, item square}
square, upper-alpha, upper-
roman
list-style- Sets where the marker is inside, outside List- {list-style: circle} Yes
position place relative to the text item
and its wrapping position.
whitespace Sets treatment of spaces normal, pre, nowrap Block {whitespace: Yes
inside the element. pre}
Font Properties
Name Description Possible Values Element Example inherited
Types
font Used to define See font-family, font-size, font- All {font: 20pt} Yes
font properties style, font-variant, and font-
weight.
font- Used to define font style normal, italic, oblique All {font-style: Yes
style to use italic}
font- Used to determine normal, small-caps All {font-variant: Yes
variant whether to use normal or small-caps}
small caps
font- Sets font weight. normal, bold, bolder, lighter, All {font-weight: Yes
weight 100, 200, 300, 400, 500, 600, 600}
700, 800, 900
Text Properties
Name Description Possible Values Element Example inherited
Types
letter- Sets the space normal or length All {letter- Yes
spacing between value spacing:
characters. 0.2em}
line-height Sets the height of normal, a number, a All {line-height: Yes
lines. percent of the 2}
element font size,
text-align Sets the alignment left, right, center, Block {text-align: Yes
of text. justify center}
text- Sets the special none, overline, All {text- No
decoration decoration underline, line- decoration:
attributes of text. through, blink blink}
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"
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.
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.
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>
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.
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.
<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
First Name: Last Name: Address1: Address2: City: State: Zip: Area Code/Phone:
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.
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>
First Name: Last Name: Address1: Address2: City: State: Zip: Area Code/Phone:
Using Applets
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.
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.
HTML Tags
<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.
<PRE> </PRE> Preformatted text. Text presented as typed with tabs, spaces and
other whitespace.
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 III : 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, youll 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, youll 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
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 hinese 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.
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.
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
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
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
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
< >
These entity references must be used for literal left and right angle brackets which are used in
XML as element tag delimiters.
' "
These entity references must be used for single and double quotes which are used in XML as
element tag delimiters.
&
& 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.
<library>
<book>
<author> Tan Kiat Shi, Willi Hans Steeb, Yorick Hardy </author>
</book>
<book>
</book>
</library>
If we consider the XML file from an SQL table point of view then each
The following example shows how to use an attribute. The attribute is sex.
<people>
<person sex="male">
</person>
<person sex="female">
</person>
</people>
<people>
<person>
</person>
<person>
</person>
</people>
The polynomial
<?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.
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
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.
nonNegativeInteger nonPositiveInteger
positiveInteger recurringInstant
timeInstant
The attribute tag is used to associate a previously data typed attribute to a tag.
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
======= ===============================
==========================================
The element tag is used to associate a previously data typed tag to an element.
The type attribute provides the type of the custom XML element.
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:
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 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"?>
<?xml version="1.0"?>
<familytree>
</person>
<person id="p2" sex = "m">
</person>
</person>
</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.
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>
of XML. XSL is a powerful styling language that uses special stylesheets to create
use XSL to transform an XML document into an HTML page that can be viewed on
to the XML document. XSL is composed of two parts: XSLT which stands for XSL
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
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
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
In order to display our XML document, we only need three of the XSL elements.
xsl:template
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
<xsl:template xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
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
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.
<library>
<book>
<author> Tan Kiat Shi, Willi Hans Steeb, Yorick Hardy </author>
</book>
<book>
</book>
</library>
<?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>
<BR/>
<BR/>
<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
======================
======================
block for the xml-file. We only want the display the table for the participants who
<?xml version="1.0"?>
<ranking>
<result>
</result>
<result>
</result>
<result>
</result>
</ranking>
42 CHAPTER 2. XML
<?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>
</TR>
<xsl:for-each select="ranking/result">
<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>
order = "ascending/descending"
lang = "..."
data-type = "text/number"
case-order = "upper-first/lower-first"
<ranking>
<player>
</player>
<player>
</player>
<player>
</player>
</ranking>
<?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>
</TR>
<xsl:for-each select="ranking/player">
<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>
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
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 users
response is sent to our companys 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 openstandard,
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.
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
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.
objectName.propertyName
// ...
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.
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 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>
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)
We use this method whenever we wish to display a message. This message is displayed 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>
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.
value.
The assignment operator = assigns a value to its left operand based on the value of
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;
The first line creates the variable username, but without giving it a value; the second
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
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT>
i = 4;
x = 3.14159;
c = 'X';
found = true;
nfound = false;
str = "xy";
n = null;
div = n/4;
</SCRIPT>
</BODY>
</HTML>
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
+ 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>
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).
> 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>
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
<HTML>
<HEAD>
</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
q1 = 31 >> 2;
q2 = 3 << 3;
q3 = -9 >> 2;
q4 = -9 >>> 2;
document.write("q4 = " + q4,"<BR>"); // => 1073741821
</SCRIPT>
</BODY>
</HTML>
The following program shows how the bitwise operation & and the shift operations
<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>
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.
The if ... else, switch, for, while, do ... while conditions have the form as in Java.
|| logical OR
! logical NOT
also have the same form as in Java, C and C++. Furthermore the relational operators are
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;
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
expressions 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 }
<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>
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
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 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 objects 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
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 objects 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
<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>
Using a constructor function we can create an object with the following two steps
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
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.
or
Array literals are also Array objects. For example the following literal is an Array
object
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
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
The top-level predefined function eval evaluates a string of JavaScript code without reference to
a particular object. The syntax is eval(expr)
<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
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>
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.")
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:
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.
<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>
<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>
re = new RegExp("abc+de")
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.
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.
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.
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.
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 DOMs.
Event Occurs when ... Event Handler
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>
<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>
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 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
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.
<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>
Chapter 4
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.
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 Developers
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 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
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
USA, 1996
York, 1996
[5] Willi-Hans Steeb, The Nonlinear Workbook: Chaos, Fractals, Cellular Automata,
[6] Tan Kiat Shi, Willi-Hans Steeb and Yorick Hardy, SymbolicC++: An Introduction