web-design-note-good-quality-notes
web-design-note-good-quality-notes
web-design-note-good-quality-notes
NOTES
USES OF INTERNET
1) For Business/ To make money: The Internet offers a wide range of business
opportunities and facilities. One is able to trade online thus putting away all
the tariffs and barriers experienced. I.e. The Internet is used to advertise and
sell product and services.
2) To Communicate: The Internet has enabled users to get faster and more
reliable communication. Communication ranges from electronic mail to
Internet access. Through chatting and emails the Internet can be used to meet
people. www.yahoo.com
3) To have Fun: The Internet provides access to many games that one can
download to play online. (Entertainment in form of music, movies etc)
4) Research: Anyone can be able to find articles or information readily available
on the Internet. It is an open library with access to some university online
libraries.www.google.com
5) News: Ranging from headlines around the world to sports it is readily
available. E.g www.nation.co.ke, www.cnn.com
6) Education: the Internet is a great learning tool. Many tutorials are available in
various subjects thus allowing users to learn more.
7) To find software: The Internet contains a wealth of useful downloadable
shareware (software you can use for free on a trial basis) e.g shareware.com
8) To shop: The Internet offers a wide range of goods that can be bought online
e.g. cars, books e.t.c. However, security online is still questionable. E.g
www.amazon.com
INTRANET
- Organizations can use Internet networking standards and web technology to create private
networks called intranets.
- An Intranet is an internal organizational network that can provide access to data across the
enterprise.
- It uses the existing company network infrastructure along with Internet connectivity
standards and software developed for the World Wide Web.
- Intranets can create networked applications that can run on many different kinds of
computers throughout the organization.
√ The principal difference between the Internet and an Intranet is that whereas the Internet
is open to anyone, the Intranet is private and is protected from public visits by firewalls.
√ A firewall is a hardware or software placed between an organization’s internal network
and an external network to prevent outsiders from invading private networks.
EXTRANET
- Private intranet that is accessible to select outsiders.
- They are extended to authorized users outside the company eg authorized buyers could link
to a portion of the company’s intranet to obtain information about the cost and features of its
products.
- The company can use firewalls to make sure that only authorized people can access the site.
- Extranets are especially useful for linking organizations with customers or business partners.
They often are used for providing product availability, pricing and shipment data and
electronic data interchange (EDI) or for collaborating with other companies on joint
development or training efforts.
(1) WWW
What is the World Wide Web?
The official definition of the WWW is "wide-area hypermedia information retrieval initiative
aiming to give universal access to a large universe of documents."
wide-area: The World Wide Web spans the whole globe.
hypermedia: It contains various types of media (text, pictures, sound, movies ...)
and hyperlinks that connect pages to one another.
information retrieval: Viewing a WWW document (commonly called a Web
page) is very easy thanks to the help of Web browsers. They allow you to retrieve
pages just by clicking links, or entering addresses.
universal access: It doesn't matter what type of computer you have, or what type
of computer the page you want is stored on - your Web browser allows you to
connect seamlessly to many different systems.
large universe of documents: Anyone can publish a Web page - and nearly
anyone has! No matter what obscure information you want to find, there is bound
to be someone out there who has written a Web page about it.
What's the relationship between the WWW and the Internet?
The World Wide Web is just one of the many services that the Internet provides. Some other
services provided by the Internet are email, FTP, gopher, telnet and usenet.
Almost every protocol type available on the Internet is accessible on the web including the
following components: Email, FTP, Telnet, User news, HTTP
Features of WWW
- It has its own protocol i.e., HTTP
- It creates a convenient and user-friendly environment
- It is the fastest components of Internet since it gathers together all the protocols into a single
system.
- It relies on the hypertext as means of Information retrieval.
- It has the ability to work with multimedia and advanced programming languages i.e. text,
graphics, video and audio.
- It is a delivery medium, content provider and subject matter.
- It connects users to almost any part of the Internet.
- It is used to explore intellectual, verbal knowledge and effective learning.
- It contains complex virtual web of connections and consist of files.
It provides real-time collaboration, interactive pages and automatic push of information to
client computers.
(2) FTP
- The Internet allows you to copy files between your computer and other computers on the
Internet by using file transfer protocol (ftp). You connect your computer to an ftp server, an
Internet host computer that stores files for transfer. You may be required to log in to retrieve a
file, which varies from software, and text files to graphic files.
(4) E-mail
- This is online communication between computer users. It is quick, convenient, efficient and
cheap way to communicate with both individuals and groups.
- It’s the most popular internet service.
(5) TELNET
It’s a service that enables remote log in. Users are permitted to log in onto a host and perform
tasks as if they are working on the remote computer itself.
(8) IRC
This is an Internet service that allows a number of users to connect to the same network node
and communicate in real time.
CHAPTER 2
WORLD-WIDE WEB MODEL
WEB DESIGN
This is a user centered multi disciplinary design pursuit pertaining to planning and
production of web sites. It includes influences from visuals arts technology, information structure
and networked delivery.
Factors that influence the significant impact of the web design on web marketing efforts
(i) How long it takes to load a web page
(ii) How often visitors visit the site, register or buy products
(iii) How long users use the site
(iv) How users find the site
(v) How likely users revisit the site
A web site is considered excellent if it is useful, usable, correct and pleasing. The
components of web development have to be compatible e.g. HTML, XML, JavaScript, Java,
flash browser, compatibility and server capacity.
4. Conformity of conversion and innovation
This includes how fast the site loads and how attractive the site is.
WEB SITES
- This is a group of web pages that are related and logically connected.
- Web sites can be viewed using software called a web browser eg Internet Explorer, Netscape
navigator
- A web site may contain a single web page or many interconnected web pages.
1. Web page
- This is a single web document that is everything you can see on your PC's browser window
at one time. Web pages are multiple documents.
- A web page can perform the following:
- Present information in an interesting way.
- Provide course material for students
- Share information globally
- Direct potential employees to information
2. Entry Page
- This is the first page a visitor views when entering a web site. It is not necessarily the home
page.
3. Home Page
- This is the introductory, starting, first, or welcome page for a web page.
- It is where other pages branch off.
- It is the main page of a web site.
- It acts as the introductory page by providing visitors with an overview of the web site and
links to the rest of the site.
4. Exit page
- This is the last page a visitor views before leaving the web site.
5. Hypertext
- This is text that contains links to other texts or documents.
- It refers to any word or phrase in an electronic document that can be used as a pointer to a
related text page.
6. Hypermedia
- This is a system that have links between text or media that takes users to another web page.
- It contains various type of media hyperlinked to connect a page to other page.
7. Link
- This is a connection made on a piece of text or media that takes users to another web page.
- It is a part of web that can be clicked to get to somewhere else.
8. Hyperlink
- This is a connection or links from one document to another or to any resource or within a
document.
- It is the most basic navigational element in a web browser.
9. Broken Link
It is a link that references a page that no longer exists.
10. Content
These are all the words, images and link which a user can read and interact with in a web page.
11. In - Line
- This is a resource of some type, which is placed directly into a document.
- It is always used in an image i.e. inline image.
13.Web browsers
The piece of software that runs on your computer and allows you to view Web pages. The most
common browsers are Netscape and Internet Explorer.
Types of Servers
The Internet is made up of millions of machines, each with a unique IP address. Many of these
machines are server machines, meaning that they provide services to other machines on the
Internet. You have heard of many of these servers: e-mail servers, Web servers, FTP servers,
Gopher servers and Telnet servers, to name a few. All of these are provided by server machines.
WEB SERVERS
At its core, a web server serves static content to a web browser by loading a file from a disk and
serving it across the network to a user’s web browser. This entire exchange is mediated by the
browser and server talking to each other using HyperText Transfer Protocol (HTTP)
DNS SERVERS
Since most people have trouble remembering the strings of numbers that make up IP addresses,
and because IP addresses sometimes need to change, all servers on the Internet also have human-
readable names, called domain names. For example, www.howstuffworks.com is a permanent,
human-readable name. It is easier for most of us to remember www.howstuffworks.com than it is
to remember 209.116.69.66.
The name www.howstuffworks.com actually has three parts:
1. The host name ("www")
7
PROXY SERVERS
Proxy servers sit between a client program (typically a web browser) and an external server
(typically another server on the web) to filter requests, improve performance, and share
connections.
INTERNET ADDRESSING
IP ADDRESS
An IP address is a unique numerical address assigned to every machine on the Internet.
The IP address is a 32 bit binary number normally represented as 4 decimal values i.e. octets.
Each octet represents 8 bits in range from 0 to 255 separated by decimal points. This method of
notation is called the dotted decimal notation e.g. 216.27.61.137
To guarantee world-wide unique addresses, IP addresses are licensed from Network
Information Center (NIC).
An IP address and its subnet mask perform the following functions:
- Enable the system to process the receipt and transmission of packets.
- They specify the device’s local addresses.
- They specify a range of addresses that share the cable with the device.
TRACERT
This command is used to determine the path of a packet.
IPCONFIG
This command is used to determine the IP address of your computer.
DOMAIN NAMES
This is a unique name that identifies an Internet site.
It is an alpha-numeric representation of the IP address. The characters are separated by dots and
correspond to an IP address e.g. www.nation.co.ke
IP addresses are not user friendly and could cause typing errors; the domain name system (DNS)
was created so people would not have to remember several confusing numbers. Domain names
enable short, alphabetical names to be assigned to IP addresses.
They are easier to remember and to work with than an IP address and are informative and
convenient to people.
FQDN
- A Fully Qualified Domain Name is a domain name that includes all higher level domains
relevant to the entity named.
- It is usually selected to give a clear indication of the site’s organization or sponsoring agent.
DOMAIN NAME SERVICE (DNS)
- This is a hierarchical, distributed method of organizing the name space of the Internet. It
translates domain names to IP addresses and vice versa.
- It provides a centralized, distributed database which keeps track of computers names and
their corresponding IP addresses.
- DNS servers are computers connected to the Internet host part of the DNS database and
allow others to access it.
- DNS servers contains a subset of the entire databases. DNS uses a client/server model where
the DNS servers contain information about a portion of the DNS database and makes
information available to clients.
ROUTING
- A router is a machine that routes packets and keep information used to get data to its
destination in routing tables.
- Each router knows about its sub-networks and which IP addresses they use.
- Routers form a tree-like structure on the Internet with Network Service Provider (NSP)
backbone at the roots.
- When a packet (piece of data) arrives at a router, the router examines the IP address of its
destination then checks its routing table. If the network containing the IP address is found the
packet is sent to that network, if not, then the router sends the packet on a default route up the
backbone to next router until it finds its destination. This process is called package routing.
TYPES OF DOCUMENTS
(1) Static document
- Documents are stored as a file on a server
- The same content is delivered every time that URL is accessed.
- Advantages: They are simple, reliable, fast and the documents can be cached locally at a
client.
- Disadvantages: Inflexible as content can only be changed by updating the file.
Information can become boring easily.
(2) Dynamic documents
- The documents are created by a program like CGI -script.
- Advantages: Information is timely and always reflect the latest information.
- Disadvantages: They are not reliable.
Require high cost of executing and maintenance.
Slow to access
Client: most users of the web simply want to access content. they need an app that can
receive incoming content and display it. this kind of app is called a client. (eg. strictly
speaking, an email program is considered a client.) many kinds of possible web clients
10
(real player, winamp), but most popular is a web browser (displays html, plus many other
common media formats). client cache: the location data is temporarily stored while it is
displayed in your browser.
Server: so where does a web page come from? servers, the host computers that act as
storage and distribution centres for web content waiting to be delivered to web clients. a
web server is a 24-hour communication application that works something like an
automated telephone switchboard. it listens for calls ("requests") placed by people using
web browsers asking for web pages. once a request is made by a browser, the server
checks to see if it can find the requested page. if it can find the page, the server sends it
back to the browser and the browser displays it. if the server can't find the page, or there
is some other problem, it sends back an error response in the form of a numeric code.
some responses are: "404--the web server can't find the page you asked for", "403--you're
not allowed to access the page you asked for without authorization".
servers:
o Are actual computers physically hooked up to the internet via ethernet, cable,
telephone line, etc.
o Run software that listens for requests for web content and returns messages and
data.
o Can perform tasks (run programs/scripts, query databases) before responding to
clients.
o Can cease functioning without affecting the stability of the rest of the
web/internet.
Protocol: the language used by the client and server to negotiate the transfer of data. web:
http (hyper-text transfer protocol), file transfer: ftp (file transfer protocol), transmission
control protocol/internet protocol (tcp/ip...tcp disassembles data into packets, ip handles
addressing and routing of the packets).
11
CHAPTER 3
OVERVIEW OF HTML
HTML CODING
- HTML stands for HyperText Markup Language.
- Hyper means active.
- It represents textual and image content.
- It is platform independent. This means that the text and the content are encoded in a way that
they can be displayed on a wide range of computers.
- Pages are made of text, images and URL links.
- HTML is structured i.e. it has a beginning, body and end.
- HTML is composed of tags which are always enclosed in angle brackets <>
- Tags in HTML are not case sensitive.
- In HTML there are two types of tags, container tags, and empty tags.
- Container tags occur in pairs. An example of a container tag is the <title></title> tag.
Whatever is contained within this tag is assigned to the title. Notice that the closing tag has a
slash in it.
- Empty tags require no closing tag. An example of an empty tag is the break tag <br>. This
forces the cursor to a new line.
- Tags should always be balanced hence containers should be nested within each other.
Advantages of HTML
1. It can be written in any editor.
2. It is universal and simple to learn and implement.
3. It gives an opportunity to further explore and add more features.
<HTML>
<HEAD>
</HEAD>
12
<BODY>
<P>Hello world!</P>
</BODY>
</HTML>
- COMMENT TAG
The first line of the code usually starts with !. It is usually for commenting and it is an empty
tag. Comment tags do not show up in the browser window. One can tell your web browser
what version of HTML being used. This needs to be written exactly as is. This, unlike the rest
of the HTML language is case sensitive. You can write all the other tags in upper or lower
case.
- <HTML> </HTML>
This is now the beginning of the document. It tells the browser that the file contains HTML
coded information. The file extension .html indicates that the file is a HTML document.
- <HEAD> </HEAD>
This identifies the first part of the HTML - coded document that contains the title. The title is
shown as part of the browser’s window.
- <TITLE> </TITLE>
The title element contains the document title and identifies its content in a global context.
The title is typically displayed in the title bar at the top of the browser window, but not inside
the window itself. The title is also what is used to identify the page for search engines and
also what is displayed on a bookmark list. Titles should be descriptive, unique and relatively
short.
- <BODY> </BODY>
The body tag defines the look of the page as a whole – specifically global settings for the
color of the text, the color of the background and the color of the links.
This is the second and the largest part of the HTML document.
The Body section of HTML contains other tags, which display text, images, links and
multimedia.
Body Tag Attributes
BGCOLOR
Defines the background color of the page. The color setting can be expressed in one or
two ways, either by name e.g. “ blue” or as a six digit hexadecimal number e.g. Blue –
0000ff, Green – 00ff00, Red – ff0000, White – ffffff, Black – 000000 e.t.c
BACKGROUND
Defines a background image. The images get tiled in the browser.
TEXT
Defines the color of the text of the page. NB/ Make sure your background
contrasts with the text color.
LINK
Defines the color of hyperlinks which have yet to be selected.
ALINK
Defines the color of hyperlinks as they are being clicked.
VLINK
13
e.g.
<HTML>
<HEAD>
<TITLE>Welcome to my page </TITLE>
</HEAD>
</BODY>
</HTML>
OTHER TAGS
HEADINGS
Html has six levels of headings numbered H1 to H6 with H1 being the largest. Headings are
typically displayed in larger and/or bolder fonts than normal body text.
<HTML>
<HEAD>
<TITLE>Welcome to my page </TITLE>
</HEAD>
</BODY>
</HTML>
PARAGRAPH
The amount of spaces and carriage returns are automatically compressed into a single space
when the HTML document is displayed in a browser.
Hence, the paragraph tag ,<P> </P> is used.
Attributes of Paragraph tag
<P ALIGN= CENTER></P>
<P ALIGN= RIGHT></P>
<P ALIGN=LEFT></P> is the default alignment i.e. if the align attribute is not included, the
paragraph will be left aligned.
14
LINE BREAK
When your HTML document is viewed, normally the text will do a word-wrap at the end of a
line. Using the <BR> tag forces a line break with no extra space between lines. This <BR> tag
has no closing tag.
HORIZONTAL RULE
The <HR> tag produces a horizontal line the width of the browser window. A horizontal rule is
useful to separate major sections of your document.
Attributes
WIDTH
The width of the rule can be expressed in two way: as a number or a as a percentage.
e.g <HR WIDTH=500> or <HR WIDTH = 75%>
SIZE
Allows the designer to specify how high, in pixels, the line will be.
NOSHADE
By default horizontal rules come with a 3D look. By using NOSHADE the line is displayed
without the drop shadow that would normally accompany the basic line.
e.g.
15
CHAPTER 4
HTML TEXT
Logical styles
These styles tag text according to its meaning.
These tags do not directly specify the type of highlighting they will employ.
- The advantage of this approach is that it reduces repetition of modification of text e.g. when you want
to change the appearance of level one heading from 24-point times centered to 30 Helvetica right
aligned, all one has to do is change the definition of level one in the web browser.
- Another advantage of logical styles is that they enforce consistency.
Physical styles
They offer consistency in that something you tag a certain way will always be displayed that way
for readers of your document.
Blockquote Forces a paragraph break above and below the text. Used to include
<blockquote>…… lengthy quotations in separate block on the screen. Most browsers
</blockquote> generally change the margins for the quotation to separate it from the
surrounding text.
Preformatted text Used to generate text exactly as typed in including spaces, new lines and
<PRE>….</PRE> tabs. Useful for program listings.
e.g.
<pre>
mangoes sh 5
Oranges sh 10
</pre>
Note: Most websites stick to fonts like Times Roman and Arial, because most computers have these fonts
installed. If you were to use an elaborate font and your viewers didn't have that font, it will revert to Sans-
Serif or Helvetica, as default.
SPECIAL CHARACTERS
The ASCII characters <,> and & have special meanings in HTML therefore, they cannot be used in text.
The angle brackets are used to indicate the beginning and end of tags while the ampersand sign is used to
indicate the beginning of an escape sequence.
NB/ Unlike the rest of HTML, the escape sequences are case sensitive.
MARQUEE ELEMENT
This is a tag that creates a scrolling text.
i.e. <marquee>……….</marquee>
It can not be nested and it must have an ending tag.
Attributes
Marquee Align= top/middle/bottom
This align the marquee with the top, middle or bottom of neighboring text line.
18
CHAPTER 5
HTML LISTS
Lists are often used to present information in an easy to read format. It can also be used to indent
information. Lists can be numbered, unnumbered or definition lists. Lists tags can be nested.
There are three types of lists:
- Unordered/ Unumbered Lists (Bullets)
- Ordered/ Numbered Lists (Numbers)
- Definition Lists (no numbers or bullets)
Unordered Lists
These are bulleted lists i.e. a list of items is preceded by bullets or markers. It is a single item list.
The list begins and ends with this tag.
To make a bulleted list:
- Start with an opening list<UL> (for unnumbered list) tag
- Enter the <LI> (list item) tag followed by the individual item; no closing</LI> tag is needed.
- End the entire list with a closing list </UL> tag.
The <LI> items can contain multiple paragraphs. Indicate the paragraphs with the <P> paragraph
tags.
e.g.
<UL>
<LI>Monday
<LI>Tuesday
<LI>Wednesday
</UL>
Attributes
Type: This is used to set different kind of bullet character. The options are:
- disc <UL type = square>
- circle
- square
Ordered Lists
A numbered list is identical to the unnumbered list only you use <OL> to number the list
<OL>
<LI>Monday
<LI>Tuesday
<LI>Wednesday
</OL>
Attributes
Type: This is used to set different kind of numbered lists.
E.g.
Plain number - <OL type =1>
Capital Letter - <OL type = A>
Small Letter - <OL type = a>
Capital Roman numbers - <OL type = I>
Small Roman numbers - <OL type = I>
Value: This is used to change the number within a list and is used as part of LI command.
19
<OL>
<LI value ="7">Item 7
<LI>Item 2
</OL>
Definition Lists
It consists of alternating a definition term<DT> and a definition <DD>. Web browsers generally
format the definition on a new line and indent it.
The <DT> and <DD> entries can contain multiple paragraphs.
e.g.
<DL>
<DT> Alligator
<DD>A large reptile with very sharp teeth.
<DT>Alliance
<DD>A union, relationship
</DL>
The COMPACT attribute can be used routinely in case your definition terms are very short.
e.g.
<DL COMPACT>
<DT>ctrl s
<DD>Short cut for saving in Windows
</DL>
Nested Lists
Lists can be nested. You can also have a number of paragraphs, each containing a nested list, in a
single item.
e.g.
<UL>
<LI> A few provinces of Kenya:
<UL>
<LI>Nairobi
<LI>Coast
<LI>Western
20
CHAPTER 6
HTML LINKS
The chief power of HTML comes from its ability to link text and/or an image to another
document or section of a document. A browser highlights the identified text or image with color
and/or underlines to indicate that it is hypertext link.
Links are used to:
- Jump from section to section within the same web page.(Internal)
- Link to different page within your web site. (Local)
- Link to another web page in another web site. (Global)
- Link to a graphical image
- Link to documents in other directories.
Relative pathnames
You can link to documents in other directories by specifying the relative path from the current
document to the linked document. Relative links are useful because:
1. It is easier to move a group of documents to another location (because the relative path names
will still be valid.
2. It is more efficient connecting to the server
3. There is less to type
URLs
This is the address or location of the link.
The World Wide Web uses Uniform Resource Locators (URLs) to specify the location of files on
other servers. A URL includes the type of resource being accessed (e.g. web, gopher, ftp), the
address of the server and the location of the file. The syntax is:
Scheme://host.domain [:port]/path/filename
Attributes
Href
- Stands for hypertext reference.
- This is the location of the file or section of page that is referenced.
Color
The general color of the text links is specified in the <body> tag
i.e. <body link="ff00ff" vlink=#808080" alink="#ff0000"
where link is the color of the link that has not been visited, vlink is the color of the link that has
been visited and alink is the color displayed when the mouse hovers over the text.
- One can also define colors for individual links on the page. There are two methods:
(a) Placing font tags between <a href> and </a> e.g.
Click <a href = "http://www.w3.com.org/addressing"><font
color="ffOOCC">here</font></a> to go to w3.
This works for most browsers except IE 3.0
(b) Using a style setting in the <a> tag e.g.
click<a href="http://www.mail.yahoo.com" style=color:rgb(0,255,0)"> here </a> to go to
w3.
This works for all browsers.
Target
The target is used if you want the link to open in another window or frame than where the link
itself is placed.
The format is <a href="url" target =" ">
The predetermined targets are:
- Blank : loads the page into a new browser window
- Self : loads the page into the current widow
- Parent : loads the page into the frame that is superior to the frame the hyperlink is in.
- Top : Cancels all frames and loads in full browser window
E.g.
<a href =http://www.jkuat.ac.ke target="blank"> here</a>
Name attribute
- This is used to set up named anchors.
- You can invisibly mark certain points of a document as places that can be jumped directly
instead of loading the document.
- The value of the Href attribute value of name attribute must be enclose with quotation marks.
- The anchor should have either name or Href attribute but not both.
- The anchor can not be nested.
Anchors can be used to move a reader to a particular section in a document. To create the links,
you require two items:
(a) HREF attribute
(b) NAME attribute
e.g.
<a href ="#linkname"> word</a>
linkname is the name of the section that you are linking to
The # symbol instructs the browser to look through the HTML document for a named anchor.
A named anchor is a hidden reference marker for a particular section of the same page. It is also
used to mark a section of another page.
e.g.
<body>
<a name ="top"></a>
.
.
<a href ="top">TOP</a>
</body>
or
<a href ="#linkname"> word</a>
.
.
<A name ="linkname">about some text here</a>
In documentB.html:
Mailto
- Used to hyperlink email addresses, but this scheme is unique in that it uses only a colon (:)
instead of :// between the scheme and the address.
23
- You can make it easy for a reader to send electronic mail to a specific person or mail alias by
including the mailto attribute in a hyperlink. The format is:
<A HREF ="mailto:emailinfo@host">Name</a>
e.g.
<A HREF = " mailto:danil2000@yahoo.com"> Send me mail</a>
- Mailto allows users to send emails by clicking on the hyperlink and a mail windo appears.
- One can also set the subject,cc and bcc to be part of the the mailto link:
e.g. <a href ="mailto:danil2000@yahoo.com?subject= topic">Greetings</a>
<a href "mailto:danil2000@yahoo.com?cc=person@hotmail.com>Greetings</a>
NB/ It is important to note that UNIX is case-sensitive operating system where filenames
are concerned.
24
CHAPTER 7
HTML IMAGES
Images are also called pictures, graphics, icons, cliparts.
Most web browsers support two inline image formats ie GIF and JPEG
Attributes
Size
- This scales the image and sets the appropriate space (in pixels) as it downloads the image.
< IMG SRC =”filem\name.gif” HEIGHT=100 WIDTH = 100>
25
- They both take numeric values which specify the amount of horizontal and vertical space
surrounding any image they are applied to. This value is specified in pixels.
<IMG SRC = “filename.gif” VSPACE=”10” HSPACE =”20”>
Alignment
- By default an image is left aligned.
- This attributes controls text around the graphic. The align attribute can take the following
values: CENTER, RIGHT, LEFT, TOP, and BOTTOM.
<IMG SRC =”filename.gif” ALIGN=RIGHT>
Border
- This is used to place or eliminate a border round the image.
- Border widths are measured in pixels.
<IMG SRC =”filename.gif” BORDER=”0”>
Alt attribute
- This is used to define an alternate text for the image.
- It improves the display and usefulness for people using text only browsers or when image
autoload is off.
- It is used to give the user more information about the image.
<IMG SRC=”filename.gif” alt =”picture of a lion”>
Background Graphics
- Newer versions of web browsers can load an image and use it as a backgroundwhen
displaying a page.
- Background images can be a texture or an image of a logo.
- Using a feature called tiling, a browser takes the image and repeats it across and down to fill
your browser window.
<BODY BACKGROUND = “filename.gif”>
Images as Hyperlinks
- Inline images can be used as hyperlinks just like plain text. Ie. They can be used as
connectors to other web pages
IMAGE MAPS
- This is an active click able image that sends visitors to different web pages depending on
different parts of the image clicked. These are called hotspots.
- Using an image one can tell the browser that particular sections of the graphic, when clicked,
will trigger a jump to a particular page.
- The image is divided into regions or areas with each area linked to a different URL.
- An image map has three components:
o An image
26
Merit
- It is supported by all browsers.
Demerits
- It takes a lot of time to load.
- It requires more system and programs e.g. CGI on your web server.
- Status bar shows only coordinates flying by along with the name of the image mp file include
URL.
o Client-side image mapping:
A client side image map is made up of two elements: the graphical map and the
code which tells the browser how to operate it.
The code itself requires two elements, the <IMG> tag which will display the map
and the <MAP> tag which provides instructions on what it will do.
With a client-side map, all of the data required to operate the selection procedure
is included with the HTML page, cutting out the need for streams of
communications with the server.
Client-side maps data is stored in HTML files and embedded directly into a page
containing other HTML elements and are interpreted by the web browser
program.
It works independently of your web server hence interpreted by the visitors’ web
browser.
27
The web data are embedded in the host page and when the client clicks on the
image, the browser processes without interaction with the server.
The <IMG> tag takes all the attributes including two extra ones:
ISMAP which tells the browser this is an image map
and USEMAP which contains an anchor link to the map definition data.
USEMAP assigns a name to the image which must be unique. The value of
the name is case sensitive.
e.g.
<IMG SRC ="mymap.gif" WIDTH =100 HEIGHT =100 ISMAP USEMAP
="#mapdata">
The map data sits inside the <MAP> container and looks like:
Demerits
Older browsers do not support it.
RECT
Two pairs of coordinates are needed to specify a rectangle. The first pair specifies
the top left corner of the rectangle while the second pair specifies the bottom right
corner of the rectangle.
e.g.
<AREA SHAPE ="RECT" COORDS="100,100,200,200"
Href=http://www.apage.co.uk">
CIRCLE
This is defined by its center and its distance from the center to any point on the
circle.
28
POLYGON
This is a figure that has got any number of sides. Polygon is built by a list of
adjacent vertices.
E.g.
<AREA SHAPE ="POLY" COORDS =16,13,35,62,72,27,16,13>
COORDS
Specifies sets of X and Y coordinates within the map image that will act as
hotspots. When the mouse moves over a hotspot the browser detects that a link
has been activated. If a mouse button is pressed the browser will act in the same
way as if a hyperlink has been selected.
HREF
Contains the URL the browser will jump to when the hotspot is clicked by the
page visitor.
29
CHAPTER 8
HTML BACKGROUNDS
Modifying the background involves including attributes in the <BODY> tag:
BGCOLOR
It adds solid background color.
<BODY BGCOLOR= red>
TEXT
Is used to add color of normal body text.
LINK
Adds the color for hypertext links items.
VLINK - This attribute adds color for the recently visited link.(Visited link)
ALINK - This attribute adds color of the link that is currently being selected. (Active link)
BACKGROUND
This attribute overrides the BGCOLOR attribute since wallpaper goes on top of the background
color.
Before including the background image you must consider the following point:
File size
Effect of texture
Readability of the text
BACKGROUND SOUND
Sound for the web comes in two main formats, digital audio or WAV and synthesized music of
MIDI format. Both are compatible with all browsers.
WAV is a very versatile Microsoft Windows format, which allows anything from music samples
to voice to be digitally recorded for later playback, either from a sound player or over the web.
The MIDI format cannot handle digital data and instead draws on collections of preset musical
sounds which are usually stored on a chip on your PC sound card.
To add sound:
<a href ="mysound.wav"> Click here for my sound</a>
When the user clicks the hyperlink, the browser will automatically launch a suitable player if one
exists. If not, the browser will ask you if you wish to save the file to disk.
NB/ Care should be taken as these files are of a reasonable size.
BGSOUND TAG
It’s an easy way of adding a background sound:
<BGSOUND SRC="mysound.wav" LOOP =50>
30
Attributes
SRC
The SRC attribute allows the designer to specify which sound file is to be played, and where to
find it.
LOOP
This attribute takes one of two values. INFINITE which means the sound will continue to play
forever and X, where X is any value which determines how many times the sound will play
before ending.
NB/ Netscape does not support the <BGSOUND> tag.
SRC
The SRC attribute allows the designer to specify which sound file should be played.
WIDTH
Allows the width of the sound playing control to be specified. Most sound controls have a small
number of buttons including play, rewind and stop associated with them and by specifying the
width and height it is possible to fix the size of the control and buttons.
HEIGHT
Specifies the height of the sound playing control.
HIDDEN
Takes the values "YES" and "NO". Hides the sound playing control from view- useful in
conjunction with AUTOPLAY.
AUTOPLAY
Forces the file specified in SRC to play as soon as it is loaded.
LOOP
Takes the values TRUE or FALSE. Using TRUE forces the browser to endlessly repeat the sound
file.
VOLUME
Entering a percentage value between 0 and 100 forces the sound tool to alter the playback
volume of the sound to the specified level.
Placing it in a page:
31
This would play back the the file mysound.wav, placing the sound player in an area 150 by 250
pixels. The controls for the player would be displayed and the sound will loop. As AUTOPLAY
is not set the page visitor would have to use the player controls to start the sound.
<EMBED SRC = "moresound.wav" HIDDEN ="TRUE" LOOP = "FALSE" VOLUME ="50%"
AUTOPLAY = "YES">
The above example will hide the sound player, automatically starting the sound as soon as it is
loaded. The sound itself will play once(LOOP is set to FALSE) at half of the maximum possible
volume .
NB/ You may use multiple embed tags within one page, but it is recommended to never set more
than one on autoplay.
32
CHAPTER 9
HTML TABLES
Tables establish a way of presenting data in a highly controlled tabulated form giving greater
control over positioning of elements.
Tables allow information to be in rows and columns.
Apart for allowing text to be arranged in columns tables can be used:
1. To divide the page into various sections
2. To create menus
3. To add interactive form fields
4. To create fast loading headers of page
5. For easy alignment of images
The <TABLE> tag is used to signify the start of a table definition.
CAPTION tag
This gives the caption for the title of the table. The default position of the title is centered at the
top of the table.
It is only permitted after the TABLE tag.
A good caption should provide a short heading for the table.
It has the following align attribute values: ALIGN=BOTTOM, TOP, LEFT, RIGHT.
NOTE
The content of a table is not shown until the entire table is loaded.
The table must be declared using the table tag
The second method, whilst not as exact, uses a percentage of the available space which allows
the table to expand or contract along with the browser if it is resized at any point.
e.g.
<TABLE WIDTH="90%"> forces the table to take 90% of the available horizontal space.
HEIGHT
It is declared just like the width attribute, however, not all browsers accept this attribute.
BORDER
This attribute sets the thickness of the borders surrounding the table.
e.g.
<TABLE BORDER =2>
If no border is desired a value of 0 BORDER=0 is given.
Every table is a collection of rows and cells. Each row contains a number of cells, each of which
contains the table information.
33
Rows must be set up before cells can be added in. In order, to create a table row the <TR> and
</TR> container is used. Each row can contain a number of cells .
The color of the border can be set by declaring:
<TABLE BORDER COLOR = red>
Table rows
The <TR> tag has the following attributes:
ALIGN
Specifies the horizontal alignment of cell data for a row. ALIGN can be either LEFT, RIGHT, or
CENTER.
VALIGN
Specifies the vertical alignment of cell data for a row. It takes one of the values TOP, MIDDLE,
or BOTTOM.
BGCOLOR
A recent addition to the table attributes, BGCOLOR takes the same values as the BGCOLOR
attribute of the BODY tag.
NB/ This tag is not supported by all browsers.
Table Cells
For every ROW in a table there must be a number of cells which contain the data to be displayed.
There are two elements for table cells ie <TH> and <TD>
<TD> tag that defines a table data cell. By default the text in this cell is aligned left and centered
vertically. It specifies the start and end tag of a cell which may hold data.
<TH> tag that defines a table header cell. By default the text in this cell is bold and centered.
Every <TH> and <TD> tags have the following attributes:
CELLSPACING
This attribute sets the size of the "invisible" margin between individual cells in a table as well as
the size of the gap between the cells and the border of the table overall.
e.g.
<TABLE BORDER = 1 BORDERCOLOR=#ff0000 CELLSPACING=20>
<TR><TD>Data1<TD>Data2<TD>Data 3
<TR><TD>Data 4<TD>Data 5<TD>Data 6
</TABLE>
CELLPADDING
Allows the setting of the gap between the left hand edge of table cells and the start of the cell
contents.
Cellpadding can be used to create areas of space within cells so that the cell contents don't appear
to be pushed up close to the edge of that cell.
e.g.
<TABLE CELLSPACING = 20 or = 50%>
<TR><TD>D1<TD>D2<TD>D3
34
</TR><TD>D4<TD>D5<TD>D6
</Table>
ALIGN
This allows the horizontal position of the table overall to be set.
Giving values of RIGHT or LEFT allows the table to be pushed against the respective page edge,
using CENTER will align the table so it sits neatly in the middle of the page.
VALIGN
This allows the designer to specify where the cell contents will physically appear.
BGCOLOR
Allows the background color of individual cells to be specified.
WIDTH
This attribute allows the width of individual table cell to be specified either as an explicit value
or as percentage of the total table width.
NB/ Care should be taken when specifying cell widths as the browser will only allow one width
to be used per column.
If multiple widths are specified the browser will resize all cells in that column to the width of the
widest.
HEIGHT
Takes values explicitly or percentages.
NB/ It is not supported by all browsers.
NOWRAP
Tells the browser that any text in any cell which uses the NOWRAP attribute must appear as a
single line, rather than over a number of lines.
NOWRAP can be useful if a specific sentence is required to fill just one line.
It turns off word wrapping.
e.g
<TABLE>
<CAPTION ALIGN =Bottom> Table Head Summary </CAPTION>
<TR>
<TD>Row 1 Col 1</TD>
<TD>Row 1 Col 2</TD>
</TR>
<TR>
<TD> Row 2 Col 1 </TD>
<TD> Row 2 Col 2 </TD>
</TR>
</TABLE>
35
- The values of COLSPAN and ROWSPAN can be anything from 2 to the maximum number
of cells in the width and height.
- Values greater than the total number of cells have no effect though care should be taken as
this may cause problems later on when the table is extended.
- Spanned cells always extend to the right of their own position (in the case of row span) and
into the space below their own position (if it’s a colspan) It is not possible to tell a cell to
span into space above or to the left of its own position.
COLSPAN = number
This is an attribute that specifies the number of columns spanned by the current cell. The value 0
means that cells span all columns from the current column to the last column of the column
group. Cells may span several columns.
e.g
<TABLE BORDER =1>
<TR>
<TD>1
<TD>2
<TD>3
</TR>
<TR>
<TD>4
<TD>6
<TD Colspan="2">8
</TR>
<TR>
<TD>9
<TD>10
</TR>
</TABLE>
ROWSPAN = number
This attribute specifies the number of rows spanned by the current cell including the current row.
e.g.
<TABLE BORDER =1>
<TR>
<TD>A
<TD rowspan = 2>B
<TD>C
<TR>
<TD>D
<TD>E
<TR>
36
<TD>F
<TD>G
</TABLE>
e.g
<TABLE>
<CAPTION ALIGN =Bottom> Table Head Summary </CAPTION>
<TR>
<TD ROWSPAN=2>Row 1 Col 1</TD>
<TD COLSPAN=2>Row 1 Col 2</TD>
</TR>
<TR>
<TD> Row 2 Col 1 </TD>
<TD> Row 2 Col 2 </TD>
</TR>
</TABLE>
e.g.
<TABLE BORDER=1>
<TR><TD>Row 1 Cell 1</TD><TD>Row1 Cell 2</TD>
<TD>Row 1 Cell 3</TD>
</TR>
<TR><TD ROWSPAN = 2>Row 2 Cell 1</TD>
<TD COLSPAN =2>Row 2 Cell 2</TD>
</TR>
<TR><TD>Row 3 Cell 2</TD><TD>Row 3 Cell 3</TD>
</TR>
</TABLE>
THEAD
This contains the header information about the columns.
This element defines a group of header rows in a table. It follows caption, colspangroup elements
and precedes the optional TFOOT element and TBODY.
TFOOT
This contains the footer information about the columns. This element defines a group of footer
rows in a table. It follows the THEAD and precedes TBODY. It provides a summary row or
footnotes that apply to the entire table or portions of it.
TBODY
This defines a group of data rows in a table. A table must have one or more TBODY element. It
contains row groups
37
e.g.
<TABLE>
<THEAD>
<TR>
<TH>ABBR </TH>
<TH>Long Form </TH>
</TR>
</THEAD>
<TFOOT>
<TR>
<TD>Footer
</TR>
</TFOOT>
<TBODY>
<TR>
</TBODY>
</TABLE>
COL ELEMENT
This allows the designer to create structural divisions within a table.
It allows designers to share attributes among several columns without implying any structural
grouping.
38
CHAPTER 10
HTML FRAMES
Frames allow author's to present or render documents in multiple views within sub windows of
the main window. This help in keeping certain information stationary e.g. static banner, a small
navigation bar.
Frames make it difficult to print paper copies of the web and not all web browsers support
frames.
A web page consists of a master HTML document that define FRAMESETS or the arrangement
of the framed areas on the page.
Frame is a way to divide the browser screen to allow easier navigation under some
circumstances.
The tags used to create a frame document are:
<FRAMESET></FRAMESET>
<FRAME>
<NOFRAME>
General Format:
<HTML>
<HEAD>
<FRAMESET>
</HTML>
<FRAMESET>………..</FRAMESET>
This specifies the layout of the main user window in terms of rectangular subspaces. It is used to
declare multiple frames.
This is a container element for dividing a window into rectangular subspaces called frames.
It takes the place of the body element and immediately follows the head.
It can be nested and contain one or more frames element.
NOFRAME element provide an alternate content for browsers that do not support frames.
Attributes
ROWS AND COLS
These define the dimensions of each frame in the set. I.e. row gives the height of each row and
cols give the width of each column. Each attribute takes a comma separated by a list of lengths.
e.g.
<FRAMESET ROWS="30%, 25%, 45%" cols = "33%", 33%,34%">
If rows and columns are omitted the implied values for the attribute is 100%.
This element accepts ONLOAD and ONUNLOAD attributes to specify client-side scripting
actions to perform when frames have all been loaded or removed.
<FRAME>
This element defines the contents and appearance of a single frame i.e. the rectangular subspace
within a frameset documents. Each frame element must be contained within a frameset element
that defines the dimensions of the frame.
39
Attributes of Frame
SRC Attribute
This provides the uniform resource identification of the frames content i.e. the source document
which is a typical HTML document. It specifies the location of the initial contents to be
contained in the frame.
e.g.
<HTML>
<HEAD><TITLE>A two row framed page</TITLE>
</HEAD>
<FRAMESET ROWS ="15%","85%" >
<FRAME SRC ="Frame-source1.html">
<FRAME SRC ="Frame-source2.html">
</FRAMESET>
</HTML>
Name Attribute
Name = data
This assigns a name to the current frame and may be used as the target of the subsequent links
i.e. A, Link, Base element
The name attribute vale must begin with a character in the range A-Z or a-z
The name should be human-readable and based on the content of the frame.
e.g.
<FRAMESET COL = "40%", *">
<FRAME NAME = "Menu" SRC = "List.html" Title = "Menu">
<FRAME NAME = "Content" SRC = "add.html" Title = "Content">
</FRAMESET>
FRAMEBORDER ATTRIBUTE
This specifies whether or not the frame has a visible border.
e.g. FRAMEBORDER =1 tells the browser to draw a border between the frame and all adjoining
frames. It is the default value.
FRAMEBORDER=0 tells the browser not to draw a border between this frame and every
adjoining frame though borders from other frames will override this.
MARGINWIDTH
This specifies the amount of space to the left between the frame's contents in the left and right
margins. The value must be greater than zero in pixels.
MARGINHEIGHT
This specifies the amount of space to be left between the frames content in its top and bottom
margins.
NORESIZE
This is a boolean attribute that tells the browser that the frame cannot be resized.
SCROLLING
This specifies whether the scrollbar should be provided for the frame. It takes the values of
AUTO, YES or NO.
The default value of AUTO generates scrollbars only when necessary.
40
LONGDESC
This specifies a link to a long description of the frame. It displays an alternate content for non-
visual browsers. This description should supplement the short description provided using title
attribute.
It is useful for non-visual browsers.
e.g.
<HTML>
<HEAD><TITLE>Some example of frames</TITLE>
<FRAMESET COLS ="33%", "33%", "33%">
<FRAMESET ROWS ="*, 200">
<FRAME SRC ="Source1.html" Scrolling ="yes">
<FRAME SRC ="Source2.html" NORESIZE MARGINWIDTH ="10">
</FRAMESET>
<FRAME SRC ="Source3.html" FRAMEBORDER ="0">
<FRAME SRC ="Source4.html" FRAMEBORDER ="0">
</FRAMESET>
</HTML>
TARGET ATTRIBUTE
This specifies the name of a frame where a document is to be opened. By assigning a name to a
frame via a name attribute, the author can refer to it as the target of links defined by other
elements.
This attribute may be set for elements that creates links (a, link) image maps (area) and forms
(form)
e.g.
<HTML>
<HEAD>
</HEAD>
<FRAMESET ROWS ="50%, 50%">
<FRAME NAME ="Dynamic" SRC = "dy.html">
<FRAME NAME ="Fixed" SRC = "fixed.html">
</FRAMESET>
</HTML>
E.G.
<HTML>
<HEAD>
</HEAD>
<BODY>
<P>Now you may have to advance to<A HREF ="doc.html TARGET ="Dynamic">Slide</A>
<NOFRAMES> ELEMENT
41
This contains text that should only be rendered when frames are not displaced or the browsers
are configured not to display frames.
It is typically used in a frameset document to provide an alternate content for browsers that has
to support the frames.
NOFRAMES element must not contain the BODY elemt.
A meaningful NOFRAMES element should always be provided in a frameset document and
should at least contain links to the main frame.
e.g.
<HTML>
<HEAD>
<TITLE>This is an example</TITLE>
</HEAD>
<FAMESET COLS="50%, 50%>
<FRAME SRC ="main.html">
<NOFRAMES>
<P>Here is the <A HREF ="main.html">NONFRAME</A?
</NOFRAMES>
</FRAMESET>
</HTML>
NB
It allows the explanation of the document's purpose in cases when it is used with browsers that
do not support frames.
<|FRAME> ELEMENT
This defines an inline frame for the inclusion of external objects including other HTML
documents.
It can act as a target for other links. It allows the designer to insert a frame within a block of text.
Inserting an inline frame is like inserting an object via the object element.
Object is more widely supported than inline frame.
The content of the Inline frame element should only be displayed by browsers that do not support
frames or are configured not to display the frames.
Inline frames may not be resized. It can support the following attributes as the element.
- Frame border
- Marginwidth
- Marginheight
- Scrolling
- SRC
- Name
- Longdescr
e.g.
<FRAME SRC ="Source.html" WIDTH="400" HEIGHT ="500" SCROLLING ="auto"
FRAMEBORDER ="1">
<A HREF ="source.html"> Related document </A>
</FRAME>
Note
- The NOFRAME element and LONGDES attributes displays an alternate content.
- Frameset definition never changes but the contents of one of its frames can.
- Frameset definition never changes but the contents of one of its frames can.
- Frameset may make navigation forward and backward through for user browsers.
- Frameset cols ="50,**">
This means column of 50 pixels and * means the remain space left over.
- Authors should not use an image or similar objects as content of a frame for better
accessibility and better indexing with search engines.
43
CHAPTER 11
HTML FORMS
An HTML form is a section of a document containing normal content, markup, special element
called controls and labels on those controls (checkboxes, menus, radio buttons e.t.c)
Forms are used to:
- Add another level of interactivity to your web page.
- Allow communication between your viewers and your website.
- Gather information (take input from users)
- Offer different means of navigation.
FORM ELEMENT
<FORM>…….</FORM> defines an interactive form which is a web page form.
It contains the following form control element which are in the container for the form.
1. <INPUT>
2. <SELECT>………</SELECT>
3. <OPTION>
4. <TEXTAREA>……….</TEXTAREA>
5. <BUTTON>
6. <LABEL>
7. <OPTGROUP>
8. <LEGEND>
9. <FIELDSET>
Form element act as a container for controls:
It specifies:
- The layout of the form
- The program that will handle the completed and submitted form
- The receiving program must be able to place name/value pairs in order to make use of them.
(action)
- The method by which user data will be sent to the server (method)
- The character encoding that will be accepted by the server in order to handle this form.
44
This specifies which HTTP method will be used to submit the form data set. The values are
"GET" and "POST".
Format is:
<FORMAT METHOD ="GET">OR<FORM METHOD ="POST">
GET
Data from the form is posted by appendices the data to the end of script URL and send the form
input in an URL to the processing agent server the amount of data that it can handle is limited by
URL and what browser can process. It should be used when the form causes no side effects i.e.
idempotent e.g database
It restricts form data set values to ASCII characters.
It allows form submission to be containers completely in a URL.
POST
****Data from the form is sent as a separate packet to the HTTP server, the form is sent in the
body of the submission *******
It does not entail the character encoding and length restrictions imposed by GET.
The form data set is specified to cover the entire character set and is included in the body of the
form.
2. ACTION=" "
This specifies the URL of the script that the form should be sent to.
The value of action attribute is the URL of the destination. It usually points to a CGI script or
Java script that handles the form submission.
The value is the place where the form is to be sent to.
The URL identified does not have to be CGI script.
It may point to mailto: URL
e.g
<form action ="mailto:daniel2003@yahoo.com" METHOD ="POST">
Note:
It is server side form handler and specifies the form processing agent.
3. ENCTYPE=" "
This specifies the content type used in submitting the form to the server when the value of
method is post.
The default value is "application/x-www-form-url.encoded" the value "multipart/form -data"
should be used in combination with input ELEMENT type="file".
e.g.
<form action =mailto:dan2003@yahoo.com METHOD="POST" ENCTYPE ="TEXT/PLAIN">
FORM CONTENTS
</FORM>
<FORM ACTION =http://amarco.co.ke/mg/aserver METHOD ="POST">
FORM CONTENT
</FORM>
45
6. TARGET =
This is used with frames to specify in which frame the form response should be rendered. If no
frame with such a name exist, response is rendered in a new window.
Th values are case sensitive e.g.
- TOP renders the response in the full unframed window.
- SELF renders the response in current frame
- BALNK renders the response in a new window
- PARENT renders the response in the immediate frameset parent.
The following attributes specify client side scripting actions for various events.
7. NAME
It names the element so that it may be referred to from style sheets or scripts.
8. ONSUBMIT
To specify when the form is submitted the action to be taken by the script.
9. ONRESET
To specify the action to be taken by script when the form is reset.
INPUT ELEMENT
This is one of the useful tags used in form's container which is an empty element.
It generates button, input fields and checkboxes.
It inputs areas in a form and defines a form control for the used to enter input.
2. VALUE
This specifies or sets the initial value of the area. It is optional except when type attribute has the
value radio or checkbox.
3. SIZE=" "
This sets the horizontal space of the area i.e. the initial width of the control.
4. MAXLENGTH
46
This sets the maximum size of the characters allowed in the area.
5. CHECKED
This boolean attribute specifies that the button is on. I.e. it initially sets either a radio button or
checkbox areas as checked.
6. SRC=" "
This specifies the source the source of an image to be used to decorate the graphical submit
button.
7. ALT=
This specifies the alternative text for an image.
8. ALIGN=
This specifies the alignment of the graphical submit button to top, middle and bottom.
9. READONLY
This sets the value of the area to read-only.
10. DISABLED
This disables the use of an area.
12. TABINDEX
This sets the order in which the area should receive focus i.e. position in tabbing order.
13. ONCLICK
Used to define the action taken when button is activated.
e.g. <INPUT TYPE=button VALUE ="Hide non-strict attributes" ID = toggler ONCLICK
="TOGGLER()">
14. ONFOCUS
When the element receives focus.
15. ONBLUR
When the element loses focus.
16. ONSELECT
When text in an input of type text or password is selected.
17. ONCHANGE
When the element loses focus and its value has changed since it received focus.
47
TYPE=
This specifies the type of control to create the default value for this attribute is "text".
It defines the type of form control. It has the following value: text, password, checkbox, radio,
submit, reset, file, hidden, image and button.
e.g.
<INPUT TYPE = "image src = "dol.gif">
<INPUT TYPE = text NAME = Username SIZE="8" MAXLENGTH ="8">
TYPE = text
This creates a single line text input control area. E.g. <INPUT TYPE = text NAME="text1"
SIZE="30" VALUE ="H11">
TYPE = Password
Create a single line to input text but rendered as a series of asterisks. This contrtol type is used
for sensitive inputs.
e.g. <INPUT TYPE = password name ="pass" SIZE="30" VALUE ="Pass">
TYPE = Checkbox
This produces a checkbox if checked. It will come up checked selected initially. For multiple
checkboxes the name changes but value the same.
e.g.
<INPUT TYPE ="Checkbox" Name ="Rock" Value = "Yes" Checked>Hotdogs<BR>
<INPUT TYPE ="Checkbox" Value ="Yes" Name ="ED> Chips <BR>
Note
That every checkbox have a unique name and check boxes allows users to choose one or more
options.
TYPE = Radio
This produces a radio button which always exist in a group. All members of this group have
same name but different values hence allows users to choose only one of the several options i.e.
only one button can be checked initially or latter.
e.g.
<INPUT TYPE ="radio" NAME = food VALUE =Dan>HOT<BR>
<INPUT TYPE ="radio" NAME = food VALUE =Yes Checked>COLD<BR>
<INPUT TYPE ="radio" NAME = food VALUE =Lock>WARM<BR>
TYPE = Submit
This produces a submit button which when pressed sends the content of the form to the servers.
For multiple submit buttons each should have a different name. It sends all the selection, values
and entered text to defined action destination.
e.g.
<INPUT TYPE="Submit" VALUE ="Send" Name ="Okoth>
<INPUT TYPE ="Submit" VALUE ="Send" Name ="Dan">
TYPE = Reset
This produces a reset button which will restore the form to its original state if pressed. The value
of VALUE attributes is used as text on the button.
e.g.
48
TYPE = file
This creates a field through which users can upload files from their local computers or network.
It is typically presented as an input box with a button to start browsing the local hard disk and
you can specify one or more file names to upload.
A form that include a file input must specify method =post and enctype = "multipart"
form="data" in form tag.
e.g.
<FROM ACTION =http://serve.com/cgi/handle enctype = "multipart/ form - data" method
="post">
<P>Name<INPUT TYPE =text name ="Sender">
File sending?<INPUT TYPE ="file" NAME="files">
</P>
</FORM>
TYPE = Hidden
It allows author's to include form data without having it rendered to the user. It is useful if the
document is generated by a script and author need to store state information.
User input can be carried from form to form by hidden inputs.
It sends the form data without appearing in the layout of the web page.
e.g.
<INPUT TYPE ="hidden" NAME ="Instructor" VALUE =Mulei@yahoo.com>
TYPE =Image
This creates a graphical submit button and provide alt attribute to act as an alternative text to
image you can also create an image map.
e.g.
<INPUT TYPE =Image SRC = source.gif ALT ="Submit">
Example
<INPUT TYPE ="Text" NAME ="Text" SIZE ="120">
<INPUT TYPE ="password" NAME ="pass" SIZE ="30">
<INPUT TYPE ="checkbox" NAME ="box" VALUE ="box" Checked>
<INPUT TYPE ="Radio" NAME ="food" VALUE ="Yes">
<INPUT TYPE ="Submit" VALUE ="SEND">
<INPUT TYPE ="Reset" VALUE ="RE">
<INPUT TYPE ="Textarea" COLS =30 ROWS = 40>
Quiz
What is the structure of a web form.
Describe the content of a web from data submission.
What is the difference between radio button and checkboxes, submit and reset forms buttons.
49
TEXTAREA ELEMENT
This is a container element which defines a text input window, <textarea> is used for large
textual areas.
It allows users to enter multiple lines of text or information.
When the form is submitted the current value of any textarea within the form is sent to the
server as name/ value pair.
The name attribute provides the name used and cols and rows attributes specify the number of
visible rows and columns in visual browser.
Readonly attribute prevent the user from editing the content of the textarea.
Tabindex attribute specifies a number between 0 and 3276 to indicate te tabbing order of the
element.
Accessing attribute specified a single unicode character as a shortcut key for giving focus to the
textarea.
WRAP attribute
This is automatically wrap the text according the values.
Wrap = Virtual
Means that the text in box wraps but it is sent as one long continuous string.
Wrap = Physical
Means that the text in the box wraps and is sent that way too.
Wrap = Off
Means that the text in the box does not wrap but it is sent exactly the way it was typed in.
e.g.
<TEXTAREA NAME="Comments" ROWS ="10" Cols ="45" WRAP ="Virtual">
</Textarea>
</Select>
STRUCTURAL DEFINITION
Heading <H?></H?> (the spec. defines 6 levels)
<H? ALIGN=LEFT|CENTER|
Align Heading RIGHT></H?>
Division <DIV></DIV>
Align Division <DIV ALIGN=LEFT|RIGHT|CENTER|JUSTIFY></DIV>
4.0 Defined Content <SPAN></SPAN>
<BLOCKQUOTE></BLOCKQUO
Block Quote TE> (usually indented)
4.0 Quote <Q></Q> (for short quotations)
4.0 Citation <Q CITE="URL"></Q>
Emphasis <EM></EM> (usually displayed as italic)
Strong
<STRONG></STRONG> (usually displayed as bold)
Emphasis
Citation <CITE></CITE> (usually italics)
Code <CODE></CODE> (for source code listings)
Sample Output <SAMP></SAMP>
Keyboard Input <KBD></KBD>
Variable <VAR></VAR>
Definition <DFN></DFN> (not widely implemented)
Author's
<ADDRESS></ADDRESS>
Address
Large Font Size <BIG></BIG>
Small Font Size <SMALL></SMALL>
(marks additions in a new
4.0 Insert <INS></INS>
version)
4.0 Time of Change <INS DATETIME=":::"></INS>
4.0 Comments <INS CITE="URL"></INS>
(marks deletions in a new
4.0 Delete <DEL></DEL>
version)
4.0 Time of Change <DEL DATETIME=":::"></DEL>
4.0 Comments <DEL CITE="URL"></DEL>
4.0 Acronym <ACRONYM></ACRONYM>
4.0 Abbreviation <ABBR></ABBR>
PRESENTATION FORMATTING
Bold <B></B>
Italic <I></I>
4.0* Underline <U></U> (not widely implemented)
Strikeout <STRIKE></STRIKE> (not widely implemented)
51
52
CHAPTER 12
The Common Gateway Interface (CGI) defining how a program interacts with a Hyper
Text Transfer Protocol (HTTP) server.
The Common Gateway Interface (CGI) provides the middleware between WWW servers and
external databases and information sources. CGI applications perform specific information
processing, retrieval, and formatting tasks on behalf of WWW servers.
A Web search engine is a good example of an interactive web page. The client enters one or
more keywords, and the Web index returns a list of Web pages that satisfy the search criteria
entered. The Web page returned by the Web index is also dynamic, because the content of that
page depends on what the client types in as search words - it's not a predefined static document.
To create an interactive Web page, HTML elements are used to display a form that accepts a
client's input and passes this to special computer programs on the Web server. This computer
programs process a client's input and return requested information, usually in the form of a web
page constructed on the fly by the computer program. These programs are known as gateways
53
because they typically act as a conduit between the Web server and an external source of
information, such as a database. Gateway programs exchange information with the Web server
using a standard known as The Common Gateway Interface. This is the reason CGI
programming is used to describe the task of writing computer programs that handle
clientrequests for information.
The term gateway describes the relationship between the WWW server and external applications
that handle data access and manipulation chores on its behalf. A gateway interface handles
information requests in an orderly fashion, and then returns an appropriate response. For
example, an HTML document generated on the fly, which contains the results of a query, applied
against an external database.
In other words, CGI allows a WWW server to provide information to WWW clients that would
otherwise not be available to those clients. This could, for example, allow a WWW client to
issue a query to an Oracle database and receive an appropriate response in the form of a custom
built Web document.
Some common uses of CGI include
Gathering user feedback about a product line through an HTML form.
Querying an Oracle database and rendering the result as an HTML document.
A Web browser running on a client machine exchanges information with a Web server using the
HyperText Transfer Protocol or HTTP. The Web server and the CGI program normally run on
the same system, on which the web server resides. Depending on the type of request from the
browser, the web server either provides a document from its own document directory or executes
a CGI program.
The sequence of events for creating a dynamic HTML document on the fly through CGI
scripting is as follows:
A client makes an HTTP request by means of a URL. This URL could be typed into the
'Location' window of a browser, be a hyperlink or be specified in the 'Action' attribute of
an HTML <form> tag.
From the URL, the' Web server determines that it should activate the gateway program
listed
in the URL and send any parameters passed via the URL to that program.
The gateway program processes the information and returns HTML text to the Web
server.
The server, in turn, adds a MIME header and returns the HTML text to the Web browser.
The Web browser displays the document received from the Web server.
54
The CGI script is executed when an anchor tag <A ... > or an image tag <IMG ...> refers to the
CGI script file rather than a normal file.
The determination of whether this is a CGI script file or just an HTML file is made on the
physical placement of the file on the server. Remember, the script file is placed on the same
machine on which the web server runs and not on your local machine.
It is of course possible to run a local web server on the machine on which you run the web
browser. However, for other people to access the files delivered by your web server you will
need a permanent connection to the internet.
Usually this placement is in the remote web server’s cgi-bin directory. However the exact
location of this directory on the server machine is determined by the web administrator for that
machine. This placement and control of the cgi-bin directory is determined by the web
administrator to prevent security problems, that could occur if arbitrary programs where allowed
to be executed by anybody accessing the machine.
55
Some web administrators may not allow you to create CGI scripts on their machine.
An anchor tag to execute the CGI script dynamic_page on the server www.mc.com is:
When the web server process a request to fetch a file, if the requested file is in the servers
nominated cgi-bin directory then as long as this file is marked as being executable the script
will be run on the server. If the file is not executable then an error will be reported.
The script eventually returns an HTML page or image to be displayed as the result of its
execution. When a CGI script file executes it may access environment variables to discover
additional information about the process that it is to perform. The first line of the returned data
must be:
GET
The Web browser submits the form's data as a part of a U RL
POST:
The Web browser sends the form's data separately from the URL as a stream of bits.
The Web server must be configured to recognize an HTTP request for a CGI program, In short,
configuring the web server involves informing it of the directory where the CGI programs reside.
The URL specifying a CGI program looks like any other URL, but the Web server can examine
the directory name and determine whether the URL is a normal document or a CGI program.
The Web server expects the CGI program's name to appear immediately following the CGI
directory (e.g. /cgi-bin/).
A URL can also include additional path information, which can be used by the CGI program.
This path information needs to be included in the URL immediately following the CGI program
name.
standard output), which is why it was a natural choice for some of the first CGI sample programs
provided by NCSA. As it can accomplish the same task as a C or C++ program with far fewer
lines of code, it has become the most widely used option for custom CGI scripts.
Besides this Perl is a scripting language, which means it does not have to be compiled. Instead,
an interpreter executes the Perl script, this makes it easy to write and test Perl scripts, because
they do not have to go through the typical edit-compile-link cycles.
58
CHAPTER 13
JAVA SCRIPT
INTRODUCTION TO JAVASCRIPT
JavaScript is a compact, object-based scripting language for developing client and server Internet
applications. Netscape Navigator 2.0 interprets JavaScript statements embedded directly in an HTML
page, enables you to create server-based applications similar to common gateway interface (CGI)
programs.
In a client application for Navigator, JavaScript statements embedded in an HTML page can recognise
and respond to user events such as mouse clicks, form input, and page navigation.
For example, you can write a JavaScript function to verify that users enter valid information into a form
requesting a telephone number. Without any network transmission, an HTML page with embedded
JavaScript can interpret the entered text and alert the user with a message dialog if the input is invalid. Or
you can use JavaScript to perform an action (such as play an audio file, execute an applet, or
communicate with a plug-in) in response to the user opening or exiting a page.
The JavaScript language resembles Java, but without Java's static typing and strong type checking.
JavaScript supports most of Java's expression syntax and basic control flow constructs. In contrast to
Java's compile-time system of classes built by declarations, JavaScript supports a run-time system based
on a small number of data types representing numeric, Boolean, and string values. JavaScript has a simple
instance-based object model that still provides significant capabilities.
JavaScript also supports functions, again without any special declarative requirements. Functions can be
properties of objects, executing as loosely typed methods.
JavaScript complements Java by exposing useful properties of Java applets to script authors. JavaScript
statements can get and set exposed properties to query the state or alter the performance of an applet or
plug-in.
By comparison, JavaScript is used to produce scripts designed to react to user and environment events as
well as in future being the glue to hook Java applets more seamlessly into WEB pages. The following are
some example:
An interactive colour picker for WEB developers to test different background and text colours in
their documents.
Calculators: Examples on the WEB include a unit conversion calculator and loan interest calculator.
Dynamic output based on the current environment and the user’s previous surfing history.
Forms verification: JavaScript can be used to ensure that from data is entered properly before
sending it to the server, rather then relying than relying on the server to verify from content after is
submitted.
59
Building URLs: JavaScript is used to build custom URLs based on the user choices in forms.
JavaScript can be used to replace many CGI scripts for clients-side processing, easing bandwidth
demands, and decreasing server load for busy WEB severs.
JavaScript Java
Interpreted (not compiled) by client. Compiled on server before execution on client.
Object-based. Code uses built-in, extensible Object-oriented. Applets consist of object classes
objects, but no classes or inheritance. with inheritance.
Code integrated with, and embedded in, Applets distinct from HTML (accessed from HTML
HTML. pages).
Variable data types not declared (loose Variable data types must be declared (strong typing).
typing).
Dynamic binding. Object references checked Static binding. Object references must exist at
at run-time. compile-time.
Secure. Cannot write to hard disk. Secure. Cannot write to hard disk.
Because JavaScript doses not require time-consuming compilation, scripts can be developed in relatively
short period of time. This is enhanced by the fact that most of the interface features, such as dialog boxes,
forms, and other GUI elements, are handled by the browser and HTML code. JavaScript programmers
don’t have to worry about creating or handling these elements of their application.
While JavaScript may share many similarities with Java. By learning just a few command and simple
rules of syntax, along with understanding the way objects are used in JavaScript, it is possible to begin
creating fairly sophisticated programs.
Because the World Wide Web, by its very nature, is platform-independent, JavaScript programs created
for Netscape Navigator are not tied to any specific hardware platform or operating system. The same
program code can be used on any platform for which Navigator 2.0 is available.
60
JavaScript programs tend to be fairly compact and are quite small, compared to the binary applets
produced by Java. This minimises storage requirements on the server and download times for the user. In
addition, because JavaScript programs usually are included in the same file as the HTML code for a page,
they require fewer separate network accesses.
As would be expected, JavaScript also has its own unique weaknesses. These include a limited set of
built-in methods, the inability to protect source code from prying eyes, and the fact that JavaScript still
doesn’t have a mature development and debugging environment.
Early version of the Navigator 2.0 beta included a version of JavaScript that was rather limited. In the
final release of Navigator 2, the number of built-in methods had significantly increased, but still didn’t
include a complete set of methods to work with documents and the client windows. With the release of
Navigator 3, things have taken a further step forward with the addition of numerous methods, properties,
and event handlers.
Because the source code of JavaScript presently must be included as part of the HTML source code for a
document, there is no way to protect the code from being copied and reused by people who view your
WEB pages.
This raises concerns in the software industry about protection of intellectual property. The consensus is
that JavaScript scripts are basically freeware at this point of time.
Most well-developed programming environment include a suite of tools that make development easier
and simplify and speed up the debugging process.
Currently, there are some HTML editors that provide JavaScript support. In addition, there are some on-
line tools for debugging and testing JavaScript script. However, there are really no integrated
development environments such as those available for Java, C, or C++. Live wire from Netscape provides
some development features but is not a complete development environment for client side JavaScript.
A script author is not required to extend, instantiated, or know about classes. Instead, the author acquires
finished components exposing high-level properties such as "visible" and "colour", then gets and sets the
properties to cause desired effects.
As an example, suppose you want to design an HTML page that contains some catalogue text, a picture of
a shirt available in several colours, a form for ordering the shirt, and a colour selector tool that's visually
61
integrated with the form. You could write a Java applet that draws the whole page, but you'd face
complicated source encoding and forgo the simplicity of HTML page authoring.
A better route would use Java's strengths by implementing only the shirt viewer and colour picker as
applets, and using HTML for the framework and order form. A script that runs when a colour is picked
could set the shirt applet's colour property to the picked colour. With the availability of general-purpose
components like a colour picker or image viewer, a page author would not be required to learn or write
Java. Components used by the script would be reusable by other scripts on pages throughout the
catalogue.
In order to take full advantage of this book, you will need several tools. A copy of the latest version of
Netscape Navigator or Microsoft Internet Explorer is essential to develop and test program code. In
addition, a good editing program that you will feel comfortable using will make program development
process easier.
In addition to a copy of Navigator or Internet Explorer, a strong editor or development tool will make the
task of entering, developing, and debugging JavaScript much easier.
If you have been doing a lot of HTML authoring or programming, you probably have you own tools that
should also well suited to JavaScript development. As long as you editor produces plain ASCII text file,
you should be fine.
In considering editors, it would be worth looking at tools that can help you in identifying the current line
number for debugging scripts.
Although Navigator or Internet Explorer started out as a basic WEB Browser, it has grown increasingly
popular. Unlike earlier Browsers and today’s basic web applications, both WEB Browsers now provide
authors with numerous tools to step beyond the traditional constraints of HTML. Instead of simply
combing text, pictures, sound and video, WEB designer now have finer control over document layout
fonts, colour, they are able to extent the functionality of the Browser using plug-ins and Java, and they
can produce interactive applications using JavaScript.
All JavaScript scripts need to be included as integral part of an HTML document. To have this, Netscape
has implemented an extension to standard HTML: the <SCRIPT> tag.
To include the script tag in an HTML document is very simple. Every scripting statement must be
contained inside a SCRIPT container tag. Just like HTML, when you are opening <BODY> tag, it starts
62
the body of your HTML document and a closing </BODY> tag ends it. In JavaScript, all that you have to
do is open the script tag by <SCRIPT> and close it by have this tag at the end of you script </SCRIPT>.
<SCRIPT>
Scripting statements
</SCRIPT>
The first and easiest, way is to include the actual source code in the HTML file, by using the following
syntax:
<SCRIPT LANGUAGE="JavaScriptVersion">
JavaScript statements...
</SCRIPT>
JavaScriptVersion specifies one of the following to indicate which version of JavaScript your code is
written for:
Statements within a <SCRIPT> tag are ignored if the user's browser does not have the level of JavaScript
support specified in the LANGUAGE attribute; for example:
Navigator 2.0 executes code within the <SCRIPT LANGUAGE="JavaScript"> tag; it ignores code within the
<SCRIPT LANGUAGE="JavaScript1.1"> tag and <SCRIPT LANGUAGE="JavaScript1.2"> tag.
Navigator 3.0 executes JavaScript code within either the <SCRIPT LANGUAGE="JavaScript"> or <SCRIPT
LANGUAGE="JavaScript1.1"> tags but ignores code within the <SCRIPT LANGUAGE="JavaScript1.2">
tag.
Navigator 4.0 executes JavaScript code within either the <SCRIPT LANGUAGE="JavaScript"> or <SCRIPT
LANGUAGE="JavaScript1.1"> tags and <SCRIPT LANGUAGE="JavaScript1.2"> tag.
example
63
This example shows how to define functions twice, once for JavaScript 1.0, and once using JavaScript 1.1
features.
<SCRIPT LANGUAGE="JavaScript">
// Define 1.0-compatible functions such as doClick() here
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript1.1">
// Redefine those functions using 1.1 features
// Also define 1.1-only functions
</SCRIPT>
<FORM ...>
<INPUT TYPE="button" onClick="doClick(this)" ...>
. . . </FORM>
One major problem, that we are going to face with this <SCRIPT> tag is browses that do not support
JavaScript will attempt to display the content of the script. To avoid this problem, Netscape recommends
the following approach using HTML comments:
<HTML>
<HEAD>
<SCRIPT LANGUAGE = “JavaScript”>
<!-- HIDE THE SCRIPT FORM OTHER BROWSERS
JavaScript Program
Look out: Unlike HTML, comments are created with these tags <! - - Comments Here - - >, JavaScript
comments start with a double-slash (//) anywhere on the line and continue to the end of that line.
Starting with Netscape Navigator3, they introduced the <NOSCRIPT> tag, which enable you to display
alternative text for non-JavaScript browsers. Texts that are between the <NOSCRIPT> tag will be display
by non-JavaScript browsers, but for Netscape Navigator v3.0 and above will ignore those texts.
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
<!-- HIDE THE SCRIPT FORM OTHER BROWSERS
//JavaScript Program
// STOP HIDING FORM OTHER BROWSERS -->
</SCRIPT>
</HEAD>
64
<NOSCRIPT>
<CENTRE>
JavaScript Script Appears Here<BR>
<H3>Best View in one of the following Browsers</H3>
Download Netscape Navigator v3.0 and above or<BR>
Internet Explorer v3.0 and above to use it. <BR>
</CENTRE>
<NOSCRIPT>
</HTML>
2.3 Where to Put Your JavaScript Code
An HTML file is able to have more than one <SCRIPT> tag. JavaScript script and programs can be
included anywhere in the header or the body of an HTML file. However, major sites like Netscape’s Web
site, and many others have their SCRIPT container in the header of the HTML file, which is the preferred
format.
that how JavaScript has a single line comment similar to those used in C++ or C programming Language
syntax. Everything after the double-slash until the end of that line is a comment. JavaScript also support C
style of multiple line comments, which starts with /* and end with */.
<HTML>
<HEAD>
<TITLE> JavaScript Exercise 1 </TITLE>
</HEAD>
<BODY>
Welcome to Informatics Computer School.<BR>
<SCRIPT LANGUAGE = "JavaScript">
<!-- HIDE THE SCRIPT FORM OTHER BROWSERS
65
The basic command unit is a one-line command or expression following by a optional semicolon ; for
example:
This command line invokes the write() method, which is part of the document object. The semicolon
indicates the end of the command.
A single JavaScript command can be written in multiple lines, as well as multiple command can also
written in a single line, as long as there is a semicolon to mark the end of each command. For example:
Multiple commands can be combined into a single command blocks by using curly brace ( { and } ).
Command blocks are used to group sets of JavaScript statements or commands into a single unit, which
can be used for various purpose, like defining function.
{
document.write(“JavaScript testing zone”);
document.write(“Cool, I am learning JavaScript and it
works!!!”);
}
{
document.write(“JavaScript Command Blocks”);
{
document.write(“JavaScript testing zone”);
document.write(“Cool, I am learning JavaScript and it
works!!!”);
}
66
}
when you are embedding command blocks like the above, it is important that you remember that all open
curly braces must be closed and that the first closing braces will close the last open braces. The opening
and closing of braces are mark by |:
{
| document.write(“JavaScript Command Blocks”);
| {
| | document.write(“JavaScript testing zone”);
| | document.write(“Cool, I am learning JavaScript and it
works!!!”);
| }
|
}
Look out: when embedding command blocks inside each other, it is common practice to indent each
successive command block so that it’s is easier to identify where the block start and end when reading
program code. Spaces and tabs do not have any effect on JavaScript programs.
In JavaScript, output can be directed to several places including the current document window and pop-up
dialog box.
In JavaScript, programmers can output text to the your browser in sequence with the HTML file. In the
next section you will learn how to output text to the browser window.
object.name.property.name
Data that these methods needs to perform this job is provided as an argument in the parentheses, for
example:
Look out:
1. Arguments are data provided to a function or a method for use in calculations and processing. They
passed information to the function or method by listing them in the parentheses following the
function or method name. Multiple arguments can be passed at once by having commas to separating
them.
67
2. In the example, it also show you that the output text are surrounded by double quotes and both of the
method are invoked in the same manner. Open and close quotes must be the same type, you cannot
open with a double and close with a single quote.
document.write(“<B>This is how you can use HTML tags in JavaScript these text are bold</B>”);
Analysis
The Script in the listing 2.2 demonstrates that HTML tags can also be use as part of JavaScript script.
68
document.writeln("<CENTER><H1>Welcome to</H1>");
document.writeln("<H2>Informatics Computer School</H2><HR>");
document.writeln("JavaScript is fun!!!!!!!!!!!");
document.write("I am learning JavaScript, ");
document.write("and this is the third exercises.</CENTER>");
// STOP HIDING FORM OTHER BROWSERS -->
</SCRIPT>
</HEAD>
</HTML>
Output
This example produces an output like those in Fig 2.4
Fig 2.4: Different output using the writeln() and write() method
Analysis
In JavaScript, strings of text, such as those used to produce output with the write() and writeln() methods,
can include special keystrokes to represent characters that cannot be typed, such as new line, tabs, and
carriage returns. The special characters are reviewed in following:
Characters Description
69
\n new line
\t tab
\r carriage return
\f form feed
\b backspace
In another words, to have a new line after a sentence instead of using HTML ”<BR>” tags, you can use
the ”\n” special characters to have a new line. For example to have a new after the line “JavaScript is
fun”, you will have to:
document.write(“JavaScript if fun!!!\n”);
All special characters have to start with a backslash “\”. The backslash is called the escaping characters.
Escaping characters are used in most programming languages to represents characters that cannot be
typed. Like having a new line after a sentence.
Look out: In order to use the special characters you have to use an HTML tags, the <PRE></PRE> tags.
You must enclose the entire special characters in the <PRE> tags container.
70
</BODY>
</HTML>
Output
Fig 2.5: Special Characters that affect the output of JavaScript script
Analysis
In exercise 2.4, we have learned how to use special characters in JavaScript, and learned how to insert a
image in JavaScript. It’s just like normal HTML but it has to be enclose in the document.write() method.
As a WEB site developer, you will realise that HTML has some limitation. One of the main restrictions of
HTML is you will only have single client window for display result. Even with the frames, WEB
designers are still limited, HTML files can only be display in complete browsers windows and unable to
be more interactive like having dialog box. In JavaScript, you are able to direct messages to the user and
get users input as well. In the next section you will see how you can output message via dialog box.
71
<HEAD>
<TITLE> JavaScript Exercise 5 </TITLE>
</HEAD>
<BODY>
<PRE>
<SCRIPT LANGUAGE = "JavaScript">
<!-- HIDE THE SCRIPT FORM OTHER BROWSERS
Generally, the alert() method is used for warn the users or to alert them to something. Examples are as
follow:
Nevertheless, the alert() method can also be used for friendly messages.
72
The alert() method still does not allow you to interact with the user. The addition of the OK button only
allow you to have some control over the timing of an event, but still cannot be used to generate any
dynamic output or customise output based on the user input.
The simplest way to interact with the user is using the prompt() method. Like the alert(), prompt() method
will also create a dialog box with the message you wanted, and it also provides a single line entry field.
The user may fill in the fields and click OK. An example of prompt() method is as follow:
Have you notice the difference the prompt() with the way you used the alert() method: you are providing
two strings to the method in the parentheses. The prompt() method requires two pieces of information:
first is text displayed and second is the default data in the entry field.
Look out: The information provided in parentheses to a method or a function are know as arguments. In
JavaScript, when a method requires more than one arguments, they are separated by commas.
Output
The script will display the GIF in the Navigator window, follow by the sentence, “Welcome to
Informatics Computer School,”. Then, a prompt dialog wills asks for the user’s name and once it is
entered, the sentence is completed and display with you name at the end.
73
Analysis
In exercise 2.6, we have learned how to used the prompt() method to construct a personalised welcome
greeting. However, you should that the process was somewhat cumbersome, required four
document.write() commands to display just a picture and a line of words. This can be done easier by
combining multiple strings of text into single string of text using what is know as concatenation.
Look out: Concatenation will be discussed more in depth in the Chapter. Using concatenation means
multiple strings are combined into a single string and are treated as a single string by JavaScript. To use
concatenation in this script you will have to use a single document.write() command and a simple plus
sign (+). For example:
74
JavaScript use four data types – numbers, strings, Boolean values, and a null value – to represent all
information the language can handle. Compare to most other programming languages, this is a small
number of data types, but it is sufficient to handle most of the data used in most programs except those
very complex programs.
Numbers, any number between 2.22E-308 … 1.79E+308, such as 15, 3.142, or 54e7.
This relatively small set of types of values, or data types, enables you to perform useful functions with
your applications. There is no explicit distinction between integer and real-valued numbers. Nor is there
75
an explicit date data type in Navigator. However, you can use the Date object and its methods to handle
dates.
Objects and functions are the other fundamental elements in the language. You can think of objects as
named containers for values, and functions as procedures that your application can perform.
3.1.1 Numbers
The JavaScript number type encompasses what would be several types in languages such as Java. Using
only the numbers data types, it is possible to declare both integers and floating point values.
3.1.1.1 Integers
Integers are numbers without any portion following the decimal point like whole numbers. Integers can
be positive or negative numbers. The maximum integers size dependent on the platform running the
JavaScript applications.
In JavaScript, integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8).
A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on
an integer literal indicates it is in octal; a leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers
can include digits (0-9) and the letters a-f and A-F. Octal integers can include only the digits 0-7.
Some examples of integer literal are, for example, bb, 143, 33, 0xFFF, and -345.
In JavaScript, a floating-point literal can have the following parts: a decimal integer, a decimal point ("."),
a fraction or decimal number, an exponent, and a type suffix. The exponent part is an "e" or "E" followed
by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one
digit, plus either a decimal point or "e" (or "E").
Some examples of floating-point literals are 1.470, -134.33e69, 0.1e12, and 2E3
Lookout: In JavaScript, when handling of floating point units will introduce inaccuracy in some
calculations. You kept this in mind for your programs.
76
Look out: Unlike C, C++, Java and many others, in JavaScript Boolean values can only be represented
with true and false. Values of 1and 0 are not recognises as Boolean values.
'JavaScript is fun'
"13433"
" "
In addition to ordinary characters, you can also include special characters in strings, as shown in the last
chapter.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var quote = "We are leaning \"JavaScript\" at Informatics Computer School."
document.write(quote)
</SCRIPT>
</HEAD>
</HTML>
77
To include a literal backslash inside a string, you must escape the backslash character. For example, to
assign the file path c:\temp to a string, use the following:
JavaScript is a loosely typed language i. e. you do not have to specify the data type of a variable when
you declare it, and data types are converted automatically as needed during script execution. So, for
example, you could define a variable as follows:
var answer = 33
And later, you could assign the same variable a string value, for example,
Because JavaScript is loosely typed, this assignment does not cause an error message.
In expressions involving numeric and string values, JavaScript converts the numeric values to strings. For
example, consider the following statements:
The first statement returns the string "The answer to the question is 33." The second statement returns the
string "33 is the answer the question."
For more information on these functions, see Chapter 4 & 5, "Built-in objects and functions."
JavaScript provides several special functions for manipulating string and numeric values:
eval attempts to evaluate a string representing any JavaScript literals or variables, converting it to a
number.
3.3 Variables
You use variables as symbolic names for values in your application. You give variables names by which
you refer to them and which must conform to certain rules.
78
A JavaScript identifier, or name, must start with a letter or underscore ("_"); subsequent characters can
also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z"
(uppercase) and the characters "a" through "z" (lowercase).
4. "Funan_Centre",
5. "info99",
6. and "_world".
In order, to use a variable, you must declare a variable. Declaring a variable tells JavaScript that a variable
of the given name exists so that the JavaScript interpreter can understand reference to that variable name
throughout the rest of the script. A variable can be declared in two ways:
NB
When you set a variable identifier by assignment outside of a function, it is called a global variable,
because it is available everywhere in the current document.
When you declare a variable within a function, it is called a local variable, because it is available only
within the function. Using var is optional, but you need to use it if you want to declare a local variable
inside a function that has already been declared as a global variable.
You can access global variables declared in one window or frame from another window or frame by
specifying the window or frame name. For example, if a variable called phoneNumber is declared in a
FRAMESET document, you can refer to this variable from a child frame as parent.phoneNumber.
<HTML>
<HEAD>
<TITLE> Incorporating Variables in a Script </TITLE>
<SCRIPT LANGUAGE="JavaScript">
var name = prompt ("Enter your Name:”, “name");
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
document.write(“<H1>Greetings,” + name + “. Welcome to Informatics Computer School.</H1>”)
</SCRIPT>
79
</BODY>
</HTML>
3.4 Expressions
An expression is any valid set of literals, variables, operators, and expressions that evaluates to a single
value. The value may be a number, a string, or a logical value. Conceptually, there are two types of
expressions: those that assign a value to a variable, and those that simply have a value. For example, the
expression
x = 31
is an expression that assigns x the value 31. This expression itself evaluates to 31. Such expressions use
assignment operators. On the other hand, the expression
30 + 1
simply evaluates to 31; it does not perform an assignment. The operators used in such expressions are
referred to simply as operators.
The special keyword null denotes a null value. In contrast, variables that have not been assigned a value
are undefined, and cannot be used without a run-time error.
80
The syntax is
If condition is true, the expression has the value of val1, Otherwise it has the value of val2. You can use a
conditional expression anywhere you would use a standard expression.
For example,
An assignment operator assigns a value to its left operand based on the value of its right operand. The
basic assignment operator is equal (=), which assigns the value of its right operand to its left operand.
That is, x = y assigns the value of y to x.
3.7 Operators
JavaScript has arithmetic, string, and logical operators. There are both binary and unary operators. A
binary operator requires two operands, one before the operator and one after the operator:
For example, 3 + 3 or x * y
A unary operator requires a single operand, either before or after the operator:
Arithmetic operators take numerical values (either literals or variables) as their operands and return a
single numerical value.
81
The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).
These operators work in the standard way.
var1 % var2
The modulus operator returns the first operand modulo the second operand, that is, var1 modulo var2, in
the statement above, where var1 and var2 are variables. The modulo function is the remainder of
integrally dividing var1 by var2. For example, 13 % 3 returns 1.
var++ or ++var
This operator increments (adds one to) its operand and returns a value. If used postfix, with operator after
operand (for example x++), then it returns the value before incrementing. If used prefix with operator
before operand (for example, ++x), then it returns the value after incrementing.
y = x++
y = ++x
var-- or --var
This operator decrements (subtracts one from) its operand and returns a value. If used postfix (for
example x--) then it returns the value before decrementing. If used prefix (for example, --x), then it
returns the value after decrementing.
y = x--
decrements x to 2 and sets y to 3.
82
y = --x
decrements x to 2 and sets y to 2.
Using the if statement, you are going to extend the “Testing User’s Response” exercise. You are going to
enable the user to indicate if he or she wants a second chance to answer the question correctly.
What you want to do is ask the question and check the result. If the result is wrong, you will ask the user
if he or she wishes to try again. If the user does, you ask one more time.
In order to make this easier, you will use the confirm() method, which is similar to the alert() and
prompt() methods that you already know how to use. The confirm() method takes a single string as an
argument. It display the string in a dialog box with OK and CANCEL buttons and returns a value of true
if the user select OK or false if CANCEL is selected.
<HTML>
<HEAD>
<TITLE> Using if for repetition </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
// DEFINE VARIABLES FOR REST OF SCRIPT
var question="What is 20+20?";
var answer=40;
var right='<IMG SRC="right.gif">';
var wrong='<IMG SRC="wrong.gif">';
// ASK THE QUESTION
var response = prompt(question,"0");
// CHECK THE ANSWER THE FIRST TIME
if (response != answer) {
// THE ANSWER WAS WRONG: OFFER A SECOND CHANCE
if (confirm("Wrong! Press OK for a second chance."))
response = prompt(question,"0");
}
// CHECK THE ANSWER
var output = (response == answer) ? right : wrong;
// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
// OUTPUT RESULT
document.write(output);
// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>
</BODY>
</HTML>
83
The result would look like Fig 3.6 prompting for user to input the answer. If the user enter, the right
answer Fig 3.7 will be show. If the user enter the wrong answer Fig 3.8 will show and prompt the user for
a second chance. If the user click on OK he or she will be given the second and the if the user enter the
wrong answer Fig 3.9 will be display or if the right answer is input, Fig 3.7 will be displayed.
Fig 3.7: Will be display if user enter the right answer for the question
Fig 3.8: Will be display if user enter the wrong answer for the question
84
Fig 3.9: Will be display if user enter the wrong answer for the question
In order to add the second chance, you have to add only two if statements. In order to grasp how this
works, lets look at the program line by line staring with the first prompt() method.
In this line, you declare the variable response, ask the user to answer the question and assign the user’s
answer to the variable response.
if (response != answer)
In this line, we compare the user’s respond to the variable answer that we assign our correct answer to. If
the answer is incorrect, then the next line is executed. If the answer is correct, the program will skip down
to output the result.
If the user has made an incorrect response, then you check whether the user wants a second chance with
confirm() method, which returns a Boolean values, which is evaluated by the if statement.
response = prompt(question,"0");
If the user selects OK in the confirm dialogs box, the confirm() method returns true, and this line
executes. With this command, the user is again asked the question, and the second respond is stored in the
respond variable, replace is stored in the response variable, replacing the previous answer.
85
Syntax
function name([param] [, param] [..., param]) {
statements }
Examples
This function returns the total dollar amount of sales, when given the number of units sold of products x,
y, and z.
It is important to realize that defining a function does not execute the commands that make up function. It
is only when the function is called by name somewhere else in the script that the function is executed.
In the above function, you can see that total_sales accepts three argument called; units_x,
units_y, units_z, Within the function, references to name refer to the value passed to the function.
4.3 RETURN
As mentioned in the previous section, functions can return result. Results are return using the return
statements. The return statement can be used to return any valid expression that evaluates to single value.
Syntax
return expression
Examples
The following function returns the square of its argument, x, where x is a number.
function square( x ) {
return x * x }
4.4 Putting Function to Work
To demonstrate the use of functions, you are going to rewrite the simple test question example you used
in “3.17 Testing User’s Response”. In order to do this, you are going to create a function that receives a
question as an argument, poses the question, check the answer, and returns an output string based on
accuracy of the user’s response as shown in the following example.
86
<HTML>
<HEAD>
<TITLE>Putting Function to work</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
//DEFINE FUNCTION testQuestion()
function testQuestion(question) {
//DEFINE LOCAL VARIABLES FOR THE FUNCTION
var answer=eval(question);
var output="What is " + question + "?";
var correct='<IMG SRC="correct.gif">';
var incorrect='<IMG SRC="incorrec.gif">';
</HEAD<
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
</BODY>
</HTML>
87
Now you have seen an example of how functions work, let’s take a look at an application of functions call
recursion. For instance, the following is an example of a recursive function that calculates a factorial:
<HEAD>
<TITLE> recursive function </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
//DEFINE FUNCTION testQuestion()
function testQuestion(question) {
//DEFINE LOCAL VARIABLES FOR THE FUNCTION
var answer=eval(question);
var output="What is " + question + "?";
var right='<IMG SRC="right.gif">';
var wrong='<IMG SRC="wrong.gif">';
88
var response=prompt(output,"0");
</HEAD<
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
</BODY>
</HTML>
Before creating a new object, it is necessary to define that object by outlining its properties. This is done
by using a function that defines the name and properties of the function. This type of function is know as
89
a constructor function. If you want to object type for student in class, you could create an object named
student with properties for name, age, and grade. This could be done with the function:
4.6.2
This
Syntax
this[.propertyName]
Examples
JavaScript has a special keyword, this, that you can use to refer to the current object. For example,
suppose you have a function called Check that validates an object’s value property, given the object, and
the max and min values:
Then, you could call Check in each form element’s onChange event handler, using this to pass it the form
element, as in the following example:
<INPUT TYPE = “text” NAME = “age” SIZE = 3 onChange= “Check(this, 18, 99)”>
4.7 New
To define an object type, create a function for the object type that specifies its name, properties, and
methods. An object can have a property that is itself another object. See the examples below.
You can always add a property to a previously defined object. For example, the statement car1.color =
"black" adds a property color to car1, and assigns it a value of "black". However, this does not affect any
90
other objects. To add the new property to all objects of the same type, you must add the property to the
definition of the car object type.
Syntax
objectName = new objectType ( param1 [,param2] ...[,paramN] )
objectType is the object type. It must be a function that defines an object type.
param1...paramN are the property values for the object. These properties are parameters defined for the
objectType function.
Examples
Example 1: object type and object instance.Suppose you want to create an object type for cars. You want
this type of object to be called car, and you want it to have properties for make, model, year, and color. To
do this, you would write the following function:
This statement creates mycar and assigns it the specified values for its properties. Then the value of
mycar.make is the string "Ford", mycar.year is the integer 1998, and so on.
You can create any number of car objects by calls to new. For example,
Then you can rewrite the definition of car to include an owner property that takes a person object, as
follows:
Instead of passing a literal string or integer value when creating the new objects, the above statements
pass the objects Rich and Boy as the parameters for the owners. To find out the name of the owner of
car2, you can access the following property:
car2.owner.name
function displayProfile(){
document.write("Name : " + this.name + "<BR>");
document.write("Age : " + this.age + "<BR>");
document.write("Mother's Name : " + this.mother +
"<BR>");
92
student1.mother = "Susan";
student1.displayProfile();
student2.displayProfile();
</Script>
</HTML>
you could then create two instance of the grade object for the two students:
93
Using these objects, you could then create the student objects like this:
function displayProfile(){
document.write("Name : " + this.name + "<BR>");
document.write("Age : " + this.age + "<BR>");
document.write("Mother's Name : " + this.mother +
"<BR>");
document.write("Maths Grade : " + this.grade.math +
"<BR>");
document.write("English Grade : " + this.grade.english +
"<BR>");
document.write("Science Grade : " + this.grade.science +
"<BR>");
document.write("<BR>");
}
Having define the method, you now need to change the object definition to include the method:
then, you could output Bob’s student profile by using the command:
student1.displayProfile();
94
String Object
Math Object
Date Object
Build-in Functions
These objects and their properties and methods are built into the language. You can use these objects in
both client applications with Netscape Navigator and server applications with LiveWire.
creates a string object called mystring. The literal "Hello, World!" is also a string object.
For example, given the above object, mystring.toUpperCase() returns "HELLO, WORLD!", and so
does "hello, world!".toUpperCase(). The following execise show how the string object is used.
<HTML>
<HEAD>
<TITLE>String Object Example</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
var sample = "Informatics";
document.write("<BR>");
document.write(sample.italics());
document.write("<BR>");
document.write(sample. toUpperCase());
document.write("<BR>");
document.write(sample.link(“http://www.ics-sin.com.sg”));
document.write("<BR>");
document.write(sample.fontsize(7));
document.write("<BR>");
document.write(sample.bold().strike());
document.write("<BR>");
document.write(sample.fontcolor("iceblue").big().sup());
95
Math.PI
Similarly, standard mathematical functions are methods of Math. These include trigonometric,
logarithmic, exponential, and other functions. For example, if you want to use the trigonometric
function sine, you would write
Math.sin(1.56)
It is often convenient to use the with statement when a section of code uses several math constants
and methods, so you don't have to type "Math" repeatedly. For example,
with (Math) {
a = PI * r*r;
y = r*sin(theta)
x = r*cos(theta)
}
JavaScript does not have a date data type. However, the date object and its methods enable you to work
with dates and times in your applications. The date object has a large number of methods for setting,
getting, and manipulating dates. It does not have any properties.
96
The parameters for the Date constructor can be any of the following:
Nothing: creates today's date and time. For example, today = new Date()
A string representing a date in the following form: "Month day, year hours:minutes:seconds". For
example, Xmas95= new Date("December 25, 1995 13:30:00") If you omit hours, minutes,
or seconds, the value will be set to zero.
A set of integer values for year, month, and day. For example, Xmas95 = new Date(95,11,25)
A set of values for year, month, day, hour, minute, and seconds For example, Xmas95 = new
Date(95,11,25,9,30,0)
The Date object has a large number of methods for handling dates and times. The methods fall into these
broad categories:
"set" methods, for setting date and time values in date objects
"get" methods, for getting date and time values from date objects
The "get" and "set" methods enable you to get and set seconds, minutes, hours, day of the month, day of
the week, months, and years separately. There is a getDay method that returns the day of the week, but no
corresponding setDay method, because the day of the week is set automatically. These methods use
integers to represent these values as follows:
hours: 0 to 23
The getTime and setTime methods are useful for comparing dates. The getTime method returns the
number of milliseconds since the epoch for a date object.
For example, the following code displays the number of shopping days left until Christmas:
<HTML>
97
<HEAD>
<TITLE>Date Object Example</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
today = new Date()
nextXmas = new Date("December 25, 1990")
nextXmas.setYear(today.getYear())
msPerDay = 24 * 60 * 60 * 1000 ; // Number of milliseconds per day
daysLeft = (nextXmas.getTime() - today.getTime()) / msPerDay;
daysLeft = Math.round(daysLeft);
document.write("Number of Shopping Days until Christmas: " + daysLeft);
// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>
</HEAD>
</HTML>
This example creates a date object named today that contains today's date. It then creates a date object
named nextXmas, and sets the year to the current year. Then, using the number of milliseconds per day, it
computes the number of days between today and nextXmas, using getTime, and rounding to a whole
number of days.
The parse method is useful for assigning values from date strings to existing date objects. For example,
the following code uses parse and setTime to assign a date to the IPOdate object.
Example 1. The following example displays an alert message 5 seconds (5,000 milliseconds) after the
user clicks a button. If the user clicks the second button before the alert message is displayed, the timeout
is cancelled and the alert does not display.
<SCRIPT LANGUAGE="JavaScript">
98
function displayAlert() {
alert("5 seconds have elapsed since the button was
clicked.")
}
</SCRIPT>
<BODY>
<FORM>
Click the button on the left for a reminder in 5 seconds;
click the button on the right to cancel the reminder before
it is displayed.
<P>
<INPUT TYPE="button" VALUE="5-second reminder"
NAME="remind_button"
onClick="timerID=setTimeout('displayAlert()',5000)">
<INPUT TYPE="button" VALUE="Clear the 5-second reminder"
NAME="remind_disable_button"
onClick="clearTimeout(timerID)">
</FORM>
</BODY>
Example 2. The following example displays the current time in a text object. The showtime() function,
which is called recursively, uses the setTimeout method update the time every second.
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
var timerID = null
var timerRunning = false
function stopclock(){
if(timerRunning)
clearTimeout(timerID)
timerRunning = false
}
function startclock(){
// Make sure the clock is stopped
stopclock()
showtime()
99
}
function showtime(){
var now = new Date()
var hours = now.getHours()
var minutes = now.getMinutes()
var seconds = now.getSeconds()
var timeValue = "" + ((hours > 12) ? hours - 12 : hours)
timeValue += ((minutes < 10) ? ":0" : ":") + minutes
timeValue += ((seconds < 10) ? ":0" : ":") + seconds
timeValue += (hours >= 12) ? " P.M." : " A.M."
document.clock.face.value = timeValue
timerID = setTimeout("showtime()",1000)
timerRunning = true
}
//-->
</SCRIPT>
</HEAD>
<BODY onLoad="startclock()">
<FORM NAME="clock" onSubmit="0">
<INPUT TYPE="text" NAME="face" SIZE=12 VALUE ="">
</FORM>
</BODY>
eval
parseInt
parseFloat
100
The built-in function eval takes a string as its argument. The string can be any string representing a
JavaScript expression, statement, or sequence of statements. The expression can include variables and
properties of existing objects.
If the argument represents an expression, eval evaluates the expression. If the argument represents one or
more JavaScript statements, eval performs the statements.
This function is useful for evaluating a string representing an arithmetic expression. For example, input
from a form element is always a string, but you often want to convert it to a numerical value.
The following example takes input in a text field, applies the eval function and displays the result in
another text field. If you type a numerical expression in the first field, and click on the button, the
expression will be evaluted. For example, enter "(666 * 777) / 3", and click on the button to see the result.
<SCRIPT>
function compute(obj) {
obj.result.value = eval(obj.expr.value)
}
</SCRIPT>
<FORM NAME="evalform">
Enter an expression: <INPUT TYPE=text NAME="expr" SIZE=20 >
<BR>
Result: <INPUT TYPE=text NAME="result" SIZE=20 >
<BR>
<INPUT TYPE="button" VALUE="Click Me" onClick="compute(this.form)">
</FORM>
The eval function is not limited to evaluating numerical expressions, however. Its argument can include
object references or even JavaScript statements. For example, you could define a function called setValue
that would take two arguments: and object and a value, as follows:
setValue(text1, 42)
These two built-in functions return a numeric value when given a string as an argument.
ParseFloat parses its argument, a string, and attempts to return a floating point number. If it encounters a
character other than a sign ( + or -), numeral (0-9), a decimal point, or an exponent, then it returns the
value up to that point and ignores that character and all succeeding characters. If the first character cannot
be converted to a number, it returns NaN.
The parseInt function parses its first argument, a string, and attempts to return an integer of the specified
radix (base). For example, a radix of 10 indicates to convert to a decimal number, 8 octal, 16
hexadecimal, and so on. For radixes above 10, the letters of the alphabet indicate numerals greater than 9.
For example, for hexadecimal numbers (base 16), A through F are used.
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all
succeeding characters and returns the integer value parsed up to that point. If the first character cannot be
converted to a number in the specified radix, it returns NaN. ParseInt truncates numbers to integer values.
9. Using the date object example. It show that the number of days left to this year Xmas. Can you
enhance the example to display day left to year 2000?
10. What would the output of the following code segment look like assuming there were no HTML tags
elsewhere in the file affecting the output?
102
A blur event occurs when a select, text, or textarea field on a form loses focus. The onBlur event handler
executes JavaScript code when a blur event occurs.
Event Handler of
Examples
In the following example, userName is a required text field. When a user attempts to leave the field, the
onBlur event handler calls the required() function to confirm that userName has a legal value.
Syntax
<INPUT TYPE="text" VALUE="" NAME="userName" onBlur="required(this.value)">
A change event occurs when a select, text, or textarea field loses focus and its value has been modified.
The onChange event handler executes JavaScript code when a change event occurs.
Use the onChange event handler to validate data after it is modified by a user.
Event Handler of
Examples
In the following example, userName is a text field. When a user attempts to leave the field, the onBlur
event handler calls the checkValue() function to confirm that userName has a legal value.
onChange syntax.
Event Handler of
Examples
103
For example, suppose you have created a JavaScript function called compute(). You can execute the
compute() function when the user clicks a button by calling the function in the onClick event handler, as
follows:
onClick syntax.
In the above example, the keyword this refers to the current object; in this case, the Calculate button. The
construct this.form refers to the form containing the button.
example,
Suppose you have created a JavaScript function called pickRandomURL() that lets you select a URL at
random. You can use the onClick event handler of a link to specify a value for the HREF attribute of the
<A> tag dynamically, as shown in the following example: Error! Hyperlink reference not valid.
In the above example, the onMouseOver event handler specifies a custom message for the
Navigator status bar when the user places the mouse pointer over the Go! anchor. As this
example shows, you must return true to set the window.status property in the onMouseOver
event handler.
Event Handler of
Examples
The following example uses an onFocus handler in the valueField textarea object to call the valueCheck()
function.
onClick syntax.
Use the onLoad event handler within either the <BODY> or the <FRAMESET> tag, for example, <BODY
onLoad="...">.
104
In a <FRAMESET> and <FRAME> relationship, an onLoad event within a frame (placed in the
<BODY> tag) occurs before an onLoad event within the <FRAMESET> (placed in the <FRAMESET>
tag).
Event Handler of
window
Examples
In the following example, the onLoad event handler displays a greeting message after a web page is
loaded.
You must return true within the event handler if you want to set the status or defaultStatus properties with
the onMouseOver event handler.
Event Handler of
link
Examples
By default, the HREF value of an anchor displays in the status bar at the bottom of the Navigator when a
user places the mouse pointer over the anchor. In the following example, the onMouseOver event handler
provides the custom message "Click this if you dare."Click me.
See onClick for an example of using onMouseOver when the <A> tag's HREF attribute is set
dynamically.
A select event occurs when a user selects some of the text within a text or textarea field. The onSelect
event handler executes JavaScript code when a select event occurs.
Event Handler of
text, textarea
Examples
The following example uses an onSelect handler in the valueField text object to call the selectState()
function.
onSelect syntax.
105
You can use the onSubmit event handler to prevent a form from being submitted; to do so, put a return
statement that returns false in the event handler. Any other returned value lets the form submit. If you
omit the return statement, the form is submitted.
Event Handler of
form
Examples
In the following example, the onSubmit event handler calls the formData() function to evaluate the data
being submitted. If the data is valid, the form is submitted; otherwise, the form is not submitted.
onSubmit syntax.
form.onSubmit="return formData(this)"
Use the onUnload event handler within either the <BODY> or the <FRAMESET> tag, for example,
<BODY onUnload="...">.
In a <FRAMESET> and <FRAME> relationship, an onUnload event within a frame (placed in the
<BODY> tag) occurs before an onUnload event within the <FRAMESET> (placed in the <FRAMESET>
tag).
Event Handler of
window
Examples
In the following example, the onUnload event handler calls the cleanUp() function to perform some shut
down processing when the user exits a web page:
<BODY onUnload="cleanUp()">
106
function hello() {
name = prompt('Enter Your Name:','Name');
alert('Greetings ' + name + ', welcome to my page!');
}
function goodbye() {
alert('Goodbye ' + name + ', sorry to see you go!');
}
107
<HTML>
<HEAD>
<TITLE> more on onLoad and onUnload </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
function urlList(a,b,c,d,e) {
// DEFINE FIVE-ELEMENT OBJECT
this[0] = a;
this[1] = b;
this[2] = c;
this[3] = d;
this[4] = e;
}
function selectPage(list) {
// SELECT RANDOM PAGE
var today = new Date();
var page = today.getSeconds() % 5;
// OPEN PAGE
window.open(list[page],"Random_Page");
}
// DEFINE SELECTION LIST
choices = new urlList("http://www.yahoo.com",
"http://www.cnn.com",
"http://www.dataphile.com.hk",
"http://home.netscape.com",
"http://www.landegg.org/landegg");
108
<H1>
<HR>
Please Wait ... Selecting Page.
<HR>
</H1>
</BODY>
</HTML>
<HEAD>
<TITLE> blur event </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
function calculate(form) {
form.results.value = eval(form.entry.value);
function getExpression(form) {
form.entry.blur();
form.entry.value = prompt("Please enter a JavaScript
mathematical expression","");
calculate(form);
109
</HEAD>
<BODY>
<FORM METHOD=POST>
Enter a JavaScript mathematical expression:
<INPUT TYPE=text NAME="entry" VALUE=""
onFocus="getExpression(this.form);">
<BR>
The result of this expression is:
<INPUT TYPE=text NAME="results" VALUE=""
onFocus="this.blur();">
</FORM>
</BODY>
</HTML>
<SCRIPT Language='JavaScript'>
function winopen () {
msg=open("","NewWindow","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,cop
yhistory=yes,width=400,height=400");
msg.location = "YOUR LINK LOCATION"
}
</SCRIPT>
This is the text that gets highlighted. put the following in the body.
If the user enters a value in the second or third field, the script should calculate the appropriate
value in the fields.
111
7.0 INTRODUCTION
The form object is one of the most heavily used objects in JavaScript written for Navigator. As a
programmer, by using the form object.
Lets users input text and make choices from form objects such as checkboxes, radio buttons, and selection
lists. You can also use a form to post data to a server.
Syntax
To define a form, use standard HTML syntax with the addition of the onSubmit event handler:
<FORM
NAME="formName"
TARGET="windowName"
ACTION="serverURL"
METHOD=GET | POST
ENCTYPE="encodingType"
[onSubmit="handlerText"]>
</FORM>
TARGET="windowName" specifies the window that form responses go to. When you submit a form with a
TARGET attribute, server responses are displayed in the specified window instead of the window that contains the
form. windowName can be an existing window; it can be a frame name specified in a <FRAMESET> tag; or it
can be one of the literal frame names _top, _parent, _self, or _blank; it cannot be a JavaScript expression (for
example, it cannot be parent.frameName or windowName.frameName). Some values for this attribute may
require specific values for other attributes. You can access this value using the target property.
ACTION="serverURL" specifies the URL of the server to which form field input information is sent. This
attribute can specify a CGI or LiveWire application on the server; it can also be a mailto: URL if the form is to be
mailed. Some values for this attribute may require specific values for other attributes. You can access this value
using the action property.
METHOD=GET | POST specifies how information is sent to the server specified by ACTION. GET (the default)
appends the input information to the URL which on most receiving systems becomes the value of the environment
variable QUERY_STRING. POST sends the input information in a data body which is available on stdin with the
data length set in the environment variable
CONTENT_LENGTH. Some values for this attribute may require specific values for other attributes. You can
access this value using the method property.
11. formName.propertyName
12. formName.methodName(parameters)
13. forms[index].propertyName
14. forms[index].methodName(parameters)
Description
Each form in a document is a distinct object.
You can reference a form's elements in your code by using the element's name (from the NAME attribute)
or the elements array. The elements array contains an entry for each element (such as a checkbox, radio,
or text object) in a form.
15. document.forms[index]
16. document.forms.length
To obtain the number of forms in a document, use the length property: document.forms.length.
You can also refer to a form's elements by using the forms array. For example, you would refer to a text
object named quantity in the second form as document.forms[1].quantity.
document.forms[1].quantity.value.
Elements in the forms array are read-only. For example, the statement
The value of each element in the forms array is <object nameAttribute>, where nameAttribute is the
NAME attribute of the form.
113
Properties
The form object has the following properties: action reflects the ACTION attribute elements is an array reflecting all
the elements in a form encoding reflects the ENCTYPE attribute length reflects the number of elements on a form
method reflects the METHOD attribute target reflects the TARGET attribute.
The forms array has the following properties: length reflects the number of forms in a document
Methods
submit
Event handlers
onSubmit
Property of
document
Examples
Example 1: named form. The following example creates a form called form1 that contains text fields for
first name and last name. The form also contains two buttons that change the names to all upper case or
all lower case. The function setCase shows how to refer to the form by its name.
Example 2: onSubmit event handler. The following example shows an onSubmit event handler that
determines whether to submit a form. The form contains one text object where the user enters three
characters. The onSubmit event handler calls a function, checkData, that returns true if the number of
characters is three; otherwise, it returns false. Notice that the form's onSubmit event handler, not the
submit button's onClick event handler, calls the checkData function. Also, the onSubmit event handler
contains a return statement that returns the value obtained with the function call.
var dataOK=false
return true}
else {
alert("Enter exactly three characters. " + document.form1.threeChar.value + " is not valid.")
return false
}
}
Example 3: submit method. The following example is similar to the previous one, except it submits the
form using the submit method instead of a submit object. The form's onSubmit event handler does not
prevent the form from being submitted. The form uses a button's onClick event handler to call the
checkData function. If the value is valid, the checkData function submits the form by calling the form's
submit method.
var dataOK=false
<FORM>
<p>
1:
<INPUT TYPE="radio" NAME="radio" value="YOUR MESSAGE GOES HERE"
onClick="alert(value)">
2:
<INPUT TYPE="radio" NAME="radio" value="YOUR MESSAGE GOES HERE"
onClick="alert(value)">
3:
<INPUT TYPE="radio" NAME="radio" value="YOUR MESSAGE GOES HERE"
onClick="alert(value)">
115
</form>
<A HREF="LINK GOES HERE" onClick="alert('YOUR MESSAGE GOES HERE')">YOUR LINK DESCRIPTION
116
GOES HERE</A>
Here how it works. Just put this part in your HEAD tag and then change YOUR CONFIRM MESSAGE
and YOUR LINK GOES HERE.
<script>
function rusure(){
question = confirm("YOUR CONFIRM MESSAGE")
if (question !="0"){
top.location = "YOUR LINK GOES HERE"
}
}
</script>
Now put this anywhere in your page and change YOUR LINK DESCRIPTION
117
<script language="JavaScript">
<!-- Hide the script from old browsers --
function surfto(form) {
var myindex=form.dest.selectedIndex
location=form.dest.options[myindex].value;
}
//-->
</SCRIPT>
<FORM NAME="myform">
<SELECT NAME="dest" SIZE=1>
<OPTION SELECTED VALUE="http://URL#1">URL #1
DESCRIPTION
<OPTION VALUE="http://URL#2">URL #2
DESCRIPTION
<OPTION VALUE="http://URL#3">URL #3
DESCRIPTION
<OPTION VALUE="http://URL#4">URL#4
DESCRIPTION
</SELECT>
<INPUT TYPE="BUTTON" VALUE="GO NOW!" onClick="surfto(this.form)">
</FORM>
118
119
LOOP
JavaScript statements consist of keywords used with the appropriate syntax. A single statement may span
multiple lines. Multiple statements may occur on a single line if each statement is separated by a semi-
colon.
Syntax conventions: All keywords in syntax statements are in bold. Words in italics represent user-
defined names or statements. Any portions enclosed in square brackets, [ ], are optional. {statements}
indicates a block of statements, which can consist of a single statement or multiple statements delimited
by a curly braces {}.
8.1 BREAK
A statement that terminates the current while or for loop and transfers program control to the statement
following the terminated loop.
Syntax
break
Examples
The following function has a break statement that terminates the while loop when i is 3, and then returns
the value 3 * x. function func(x) { var i = 0 while (i < 6) { if (i == 3) break i++ } return i*x }
8.2 CONTINUE
A statement that terminates execution of the block of statements in a while or for loop, and continues
execution of the loop with the next iteration. In contrast to the break statement, continue does not
terminate the execution of the loop entirely: instead,
Syntax
continue
Examples
120
The following example shows a while loop that has a continue statement that executes when the value of
i is 3. Thus, n takes on the values 1, 3, 7, and 12.
8.3 FOR
A statement that creates a loop that consists of three optional expressions, enclosed in parentheses and
separated by semicolons, followed by a block of statements executed in the loop. The parts of the for
statement are:
The initial expression, generally used to initialize a counter variable. This statement may optionally
declare new variables with the var keyword. This expression is optional.
The condition that is evaluated on each pass through the loop. If this condition is true, the statements
in the succeeding block are performed. This conditional test is optional. If omitted, then the
condition always evaluates to true.
An update expression generally used to update or increment the counter variable. This expression is
optional.
A block of statements that are executed as long as the condition is true. This can be a single
statement or multiple statements. Although not required, it is good practice to indent these statements
from the beginning of the for statement.
Syntax
for ([initial expression]; [condition]; [update expression]) {
statements
}
initial expression = statement | variable declaration
Examples
This for statement starts by declaring the variable i and initializing it to zero. It checks that i is less than
nine, and performs the two succeeding statements, and increments i by one after each pass through the
loop. for (var i = 0; i < 9; i++) { n += i myfunc(n) }
<HTML>
<HEAD>
<TITLE>for Loop Example</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
var name = prompt("What is your name?","name");
121
8.4 FOR…..IN
A statement that iterates a variable var over all the properties of object obj. For each distinct property, it
executes the statements in statements.
Syntax
for (var in obj) {
statements }
Examples
The following function takes as its argument an object and the object's name. It then iterates over all the
object's properties and returns a string that lists the property names and their values. function
dump_props(obj, obj_name) { var result = "" for (var i in obj) { result += obj_name + "." + i + " = " +
obj[i] + " " } result += " " return result }
8.5 IF…..ELSE
A conditional statement that executes the statements in statements if condition is true. In the optional else
clause, it executes the statements in else statements if condition is false. These may be any JavaScript
statements, including further nested if statements.
122
Syntax
if (condition) {
statements
} [else {
else statements
}]
Examples
if ( cipher_char == from_char ) { result = result + to_char x++ } else result = result + clear_char
A statement that creates a loop that evaluates the expression condition, and if it is true, executes
statements. It then repeats this process, as long as condition is true. When condition evaluates to false,
execution continues with the statement following statements.
Although not required, it is good practice to indent the statements a while loop from the beginning of a
for statement.
Syntax
while (condition) {
statements
}
Examples
The following while loop iterates as long as n is less than three. Each iteration, it increments n and adds it
to x. Therefore, x and n take on the following values:
After completing the third pass, the condition n < 3 is no longer true, so the loop terminates. n = 0 x = 0
while( n < 3 ) { n ++; x += n }
123
124
return mth;
}
</SCRIPT>
</HEAD>
<body>
<script language="JavaScript">
clock= wkdy(day) + ", " + dd + " " +month(mth) +" " +yy + ", ";
clock += " " +hh + ":" + min;
document.write(clock, "<br>");
</SCRIPT>
</body>
<HTML>
125
<HEAD>
<TITLE>Listing 7.4</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
var row = 0;
var col = 0;
var playerSymbol = "X";
var computerSymbol = "O";
board = new createArray(3,3);
function createArray(row,col) {
var index = 0;
this.length = (row * 10) + col;
for (var x = 1; x <= row; x ++) {
for (var y = 1; y <= col; y++) {
index = (x*10) + y;
this[index] = "";
}
}
function buildBoard(form) {
var index = 0;
for (var field = 0; field <= 8; field ++) {
index = eval(form.elements[field].name);
form.elements[field].value = board[index];
}
function clearBoard(form) {
var index = 0;
for (var field = 0; field <= 8; field ++) {
form.elements[field].value = "";
index = eval(form.elements[field].name);
board[index] = "";
}
126
function win(index) {
// CHECK ROWS
if ((board[index] == board[(index < 30) ? index + 10 : index
- 20]) &&
(board[index] == board[(index > 11) ? index - 10 :
index + 20])) {
win = true;
}
// CHECK COLUMNS
if ((board[index] == board[(index%10 < 3) ? index + 1 :
index - 2]) &&
(board[index] == board[(index%10 > 1) ? index - 1 :
index + 2])) {
win = true;
}
// CHECK DIAGONALS
if (Math.round(index/10) == index%10) {
if ((board[index] == board[(index < 30) ? index + 11 :
index - 22]) &&
(board[index] == board[(index > 11) ? index - 11 :
index + 22])) {
win = true;
}
if (index == 22) {
if ((board[index] == board[13]) && (board[index]
== board[31])) {
win = true;
}
}
}
if ((index == 31) || (index == 13)) {
if ((board[index] == board[(index < 30) ? index + 9 : index -
18]) &&
(board[index] == board[(index > 11) ? index - 9 : index
+ 18])) {
win = true;
}
127
function play(form,field) {
128
buildBoard(form);
alert("Computer Just Won!");
clearBoard(form);
} else {
// CAN'T WIN, CHECK IF NEED TO STOP A WIN
for (row = 1; row <=3; row++) {
for (col = 1; col <= 3; col++) {
index = (row*10) + col;
if (board[index] == "") {
board[index] = playerSymbol;
if (win(index)) {
playIndex = index;
done = true;
board[index] = "";
break;
}
board[index] = "";
}
}
if (done)
break;
}
// CHECK IF DONE
if (done) {
board[playIndex] = computerSymbol;
buildBoard(form);
} else {
// NOT DONE, CHECK FOR FIRST EMPTY SPACE
for (row = 1; row <= 3; row ++) {
for (col = 1; col <= 3; col ++) {
index = (row*10) + col;
if (board[index] == "") {
playIndex = index;
done = true;
break;
}
}
if (done)
break;
}
board[playIndex] = computerSymbol;
buildBoard(form);
}
129
}
}
</HEAD>
<BODY>
<TABLE>
<TR>
<TD>
<INPUT TYPE=text SIZE=3 NAME="11"
onFocus="if (this.value != '') {blur();}"
onChange="play(this.form,this);">
</TD>
<TD>
<INPUT TYPE=text SIZE=3 NAME="12"
onFocus="if (this.value != '') {blur();}"
onChange="play(this.form,this);">
</TD>
<TD>
<INPUT TYPE=text SIZE=3 NAME="13"
onFocus="if (this.value != '') {blur();}"
onChange="play(this.form,this);">
</TD>
</TR>
<TR>
<TD>
<INPUT TYPE=text SIZE=3 NAME="21"
onFocus="if (this.value != '') {blur();}"
onChange="play(this.form,this);">
</TD>
<TD>
<INPUT TYPE=text SIZE=3 NAME="22"
onFocus="if (this.value != '') {blur();}"
130
onChange="play(this.form,this);">
</TD>
<TD>
<INPUT TYPE=text SIZE=3 NAME="23"
onFocus="if (this.value != '') {blur();}"
onChange="play(this.form,this);">
</TD>
</TR>
<TR>
<TD>
<INPUT TYPE=text SIZE=3 NAME="31"
onFocus="if (this.value != '') {blur();}"
onChange="play(this.form,this);">
</TD>
<TD>
<INPUT TYPE=text SIZE=3 NAME="32"
onFocus="if (this.value != '') {blur();}"
onChange="play(this.form,this);">
</TD>
<TD>
<INPUT TYPE=text SIZE=3 NAME="33"
onFocus="if (this.value != '') {blur();}"
onChange="play(this.form,this);">
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
131
g. for ( j = 4 ; j > 0; j -- ){
document.writeln( j + "<BR>" );
}
132
A window that can display multiple, independently scrollable frames on a single screen, each with its own
distinct URL. Frames can point to different URLs and be targeted by other URLs, all within the same
screen. A series of frames makes up a page.
Syntax
To define a frame object, use standard HTML syntax. The onLoad and onUnload event handlers are
specified in the <FRAMESET> tag but are actually event handlers for the window object:
<FRAMESET
ROWS="rowHeightList"
COLS="columnWidthList"
[onLoad="handlerText"]
[onUnload="handlerText"]>
[<FRAME SRC="locationOrURL" NAME="frameName">]
</FRAMESET>
The URL cannot include an anchor name; for example <FRAME SRC="doc2.html#colors"
NAME="frame2"> is invalid. See the location object for a description of the URL components.
[windowReference.]frameName.propertyName
[windowReference.]frames[index].propertyName
window.propertyName
self.propertyName
parent.propertyName
windowReference is a variable windowVar from a window definition (see window object), or one of the
synonyms top or parent.
133
frameName is the value of the NAME attribute in the <FRAME> tag of a frame object.
Description
The <FRAMESET> tag is used in an HTML document whose sole purpose is to define the layout of
frames that make up a page. Each frame is a window object.
If a <FRAME> tag contains SRC and NAME attributes, you can refer to that frame from a sibling frame
by using parent.frameName or parent.frames[index]. For example, if the fourth frame in a set has
NAME="homeFrame", sibling frames can refer to that frame using parent.homeFrame or
parent.frames[3].
The self and window properties are synonyms for the current frame, and you can optionally use them to
refer to the current frame. You can use these properties to make your code more readable. See the
properties listed below for examples.
The top and parent properties are also synonyms that can be used in place of the frame name. Top refers
to the top-most window that contains frames or nested framesets, and parent refers to the window
containing the current frameset. See the top and parent properties.
[frameReference.]frames[index]
[frameReference.]frames.length
[windowReference.]frames[index]
[windowReference.]frames.length
windowReference is a variable windowVar from a window definition (see window object), or one of the
synonyms top or parent.
To obtain the number of child frames in a window or frame, use the length property:
[windowReference.].frames.length
134
[frameReference.].frames.length
Elements in the frames array are read-only. For example, the statement
The value of each element in the frames array is <object nameAttribute>, where
Properties
The frame object has the following properties:
parent is a synonym for the window or frame containing the current frameset
Methods
clearTimeout
setTimeout
Event handlers
None. The onLoad and onUnload event handlers are specified in the <FRAMESET> tag but are
actually event handlers for the window object.
Property of
The frame object is a property of window
Examples
135
The following example creates two windows, each with four frames. In the first window, the first frame
contains pushbuttons that change the background colors of the frames in both windows.
FRAMSET1.HTML, which defines the frames for the first window, contains the following code:
<HTML>
<HEAD>
<TITLE>Frames and Framesets: Window 1</TITLE>
</HEAD>
<FRAMESET ROWS="50%,50%" COLS="40%,60%" onLoad="alert('Hello, World.')">
<FRAME SRC=framcon1.html NAME="frame1">
<FRAME SRC=framcon2.html NAME="frame2">
<FRAME SRC=framcon2.html NAME="frame3">
<FRAME SRC=framcon2.html NAME="frame4">
</FRAMESET>
</HTML>
FRAMSET2.HTML, which defines the frames for the second window, contains the following code:
<HTML>
<HEAD>
<TITLE>Frames and Framesets: Window 2</TITLE>
</HEAD>
<FRAMESET ROWS="50%,50%" COLS="40%,60%">
<FRAME SRC=framcon2.html NAME="frame1">
<FRAME SRC=framcon2.html NAME="frame2">
<FRAME SRC=framcon2.html NAME="frame3">
<FRAME SRC=framcon2.html NAME="frame4">
</FRAMESET>
</HTML>
FRAMCON1.HTML, which defines the content for the first frame in the first window, contains the
following code:
<HTML>
<BODY>
<A NAME="frame1"><H1>Frame1</H1></A>
<P><A HREF="framcon3.html" target=frame2>Click here</A> to load a different file into frame 2.
<SCRIPT>
window2=open("framset2.html","secondFrameset")
</SCRIPT>
<FORM>
<P><INPUT TYPE="button" VALUE="Change frame2 to teal"
onClick="parent.frame2.document.bgColor='teal'">
<P><INPUT TYPE="button" VALUE="Change frame3 to slateblue"
onClick="parent.frames[2].document.bgColor='slateblue'">
136
FRAMCON2.HTML, which defines the content for the remaining frames, contains the following code:
<HTML>
<BODY>
<P>This is a frame.
</BODY>
</HTML>
<HTML>
<BODY>
<P>This is a frame. What do you think?
</BODY>
</HTML>
Contains information on the current document, and provides methods for displaying HTML output to the
user.
Syntax
To define a document object, use standard HTML syntax:
<BODY
BACKGROUND="backgroundImage"
BGCOLOR="backgroundColor"
TEXT="foregroundColor"
137
LINK="unfollowedLinkColor"
ALINK="activatedLinkColor"
VLINK="followedLinkColor"
[onLoad="handlerText"]
[onUnload="handlerText"]>
</BODY>
BGCOLOR, TEXT, LINK, ALINK, and VLINK are color specifications expressed as a hexadecimal
RGB triplet (in the format "rrggbb" or "#rrggbb") or as one of the string literals listed in Color Values.
document.propertyName
document.methodName(parameters)
Description
An HTML document consists of a <HEAD> and <BODY> tag. The <HEAD> includes information on
the document's title and base (the absolute URL base to be used for relative URL links in the document).
The <BODY> tag encloses the body of a document, which is defined by the current URL. The entire
body of the document (all other HTML elements for the document) goes within the <BODY> tag.
You can reference the anchors, forms, and links of a document by using the anchors, forms, and links
arrays. These arrays contain an entry for each anchor, form, or link in a document.
Properties
alinkColor reflects the ALINK attribute
138
Methods
clear
close
open
write
writeln
Event handlers
None. The onLoad and onUnload event handlers are specified in the <BODY> tag but are actually
event handlers for the window object.
Property of
window
Examples
The following example creates two frames, each with one document. The document in the first frame
contains links to anchors in the document of the second frame. Each document defines its colors.
<HTML>
<HEAD>
<TITLE>Document object example</TITLE>
</HEAD>
<FRAMESET COLS="30%,70%">
<FRAME SRC="doc1.html" NAME="frame1">
<FRAME SRC="doc2.html" NAME="frame2">
</FRAMESET>
</HTML>
139
DOC1.HTML, which defines the content for the first frame, contains the following code:
<HTML>
<SCRIPT>
</SCRIPT>
<BODY
BGCOLOR="antiquewhite"
TEXT="darkviolet"
LINK="fuchsia"
ALINK="forestgreen"
VLINK="navy">
<P><B>Some links</B>
<LI><A HREF="doc2.html#numbers" TARGET="frame2">Numbers</A>
<LI><A HREF="doc2.html#colors" TARGET="frame2">Colors</A>
<LI><A HREF="doc2.html#musicTypes" TARGET="frame2">Music types</A>
<LI><A HREF="doc2.html#countries" TARGET="frame2">Countries</A>
</BODY>
</HTML>
DOC2.HTML, which defines the content for the second frame, contains the following code:
<HTML>
<SCRIPT>
</SCRIPT>
<BODY
BGCOLOR="oldlace" onLoad="alert('Hello, World.')"
TEXT="navy">
<P><A NAME="numbers"><B>Some numbers</B></A>
<LI>one
<LI>two
<LI>three
<LI>four
<LI>five
<LI>six
<LI>seven
<LI>eight
<LI>nine
<P><A NAME="colors"><B>Some colors</B></A>
<LI>red
<LI>orange
<LI>yellow
<LI>green
<LI>blue
<LI>purple
<LI>brown
<LI>black
<P><A NAME="musicTypes"><B>Some music types</B></A>
<LI>R&B
140
<LI>Jazz
<LI>Soul
<LI>Reggae
<LI>Rock
<LI>Country
<LI>Classical
<LI>Opera
<P><A NAME="countries"><B>Some countries</B></A>
<LI>Afghanistan
<LI>Brazil
<LI>Canada
<LI>Finland
<LI>India
<LI>Italy
<LI>Japan
<LI>Kenya
<LI>Mexico
<LI>Nigeria
</BODY>
</HTML>
9.3 working with the status bar
To have a scrolling message at the status bar. Insert this code into your head ( <head>Insert in between
here</head> )
<script language="JavaScript">
<!-- Hide the script from old browsers --
function scrollit(seed)
{
var m1 = " THIS IS WHERE YOUR MESSAGE GOES ";
var msg=m1; var out = " ";
var c = 0;
141
timerTwo=window.setTimeout(cmd,7);
}
else if (seed <= 0)
{
if (-seed < msg.length)
{
out+=msg.substring(-seed,msg.length);
seed--;
var cmd="scrollit(" + seed + ")";
window.status=out;
timerTwo=window.setTimeout(cmd,7);
}
else
{
window.status=" ";
timerTwo=window.setTimeout("scrollit(100)",
75);
}
}
}
// --End Hiding Here -->
</script>
<body onLoad="timerONE=window.setTimeout('scrollit(100)',500)">
Or
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#FF0000" VLINK="#000080"
ALINK="#000080" onLoad="timerONE=window.setTimeout('scrollit(100)',500)">
142
<script language="JavaScript">
<!-- Hide the script from old browsers --
var timerID = null;
var timerRunning = false;
var id,pause=0,position=0;
function ticker() {
var i,k,msg="YOUR MESSAGE GOES HERE";
k=(75/msg.length)+1;
for(i=0;i<=k;i++) msg+=" "+msg;
document.form2.ticker.value=msg.substring
(position,position+75);
if(position++==38) position=0;
id=setTimeout("ticker()",1000/10); }
function action() {
if(!pause) {
clearTimeout(id);
pause=1; }
else {
ticker();
pause=0; } }
// --End Hiding Here -->
</script>
Now put this inside your body code.
<body onLoad="ticker()">
OR
Now put this where ever you want in your HTML document
<form name="form2">
<input type="text" name="ticker" size="75">
To change the size of the ticker tape, change the number "75" to what ever size you want in the line...
<input type="text" name="ticker" size="75">
143
144