HTML DHTML and Java Script
HTML DHTML and Java Script
V1.0
Objectives
• Explain Introduction of WWW
• Understand Client/Server Architecture
• Explain Internet Concepts
Introduction to Web
The web is a complex, international, cross platform, cross language, cross cultural mesh of servers,
clients, users, databases, and quite a few artificial intelligences all talking, working, searching,
viewing, accessing, downloading together. Tim Berners-Lee, a computer specialist from the European
Particle Physics Laboratory (CERN) in 1989, initially created the web. It is the largest client/server
system implemented to date. A client/server system is a very keen way of distributing information
across information systems like a local area network (LAN), a wide area network (WAN), or the
Internet.
Protocol use for communication in between client and server is HTTP (HyperText Transfer Protocol).
HTTP is a "request-response" type protocol that specifies that a client will open a connection to a
server then send a request using a very specific format. The server will then respond and closes the
connection.
These requests will be in some language and some format that the computer understands normally
HTML (Hyper Text Markup Language). Upon Request of client (Web browser) server send a response
(Web page), actually the web browser will display a document exactly the way it receives it from the
web server. For example, if the document requested is an image, the web browser will display it
directly. However, if the document is an HTML document, the web browser will "interpret" the HTML
and display it according to the instructions contained within the HTML code.
HTML (Hyper Text Markup Language) is a very simple language used to "describe" the logical structure
of a document.
Though HTML is often called a programming language it is really not. In HTML itself, there is no
programming-just the "marking up" of regular text for emphasis and organization. Programming
languages can be used to compute something such as the square root of pi or some other such task.
Typically programming languages use conditional branches and loops and operate on data contained in
abstract data structures. HTML is much easier than all of that. HTML is simply a 'markup language' used
to define a logical structure rather than compute anything.
The Web is fairly unique among Internet services (which include Internet e-mail, Gopher, and FTP) in
that its protocols allow for the Web server to send information of many different types ,
(text, sound, graphics), as well as offer access to those other Internet services. Most Web browsers are
just as capable of displaying UseNet newsgroup messages and Gopher sites as they are able to display
Web pages written in HTML
Web site organization is an important consideration for any HTML designer, including those designing
and building corporate Web sites. The typical corporate Web site needs to offer a number of different
types of information, each of which might merit its own Web page or pages.
Hypermedia: Text and Graphics on the Web
With graphical browsers such as NCSA Mosaic and Netscape Navigator, the hypertext concept of the
Web was introduced to the world of multimedia, resulting in the hypermedia links that are possible in
HTML.
Now, this really isn't much different from the hypertext links we talked about in the previous section-
the only difference is that hypermedia links point to files other than HTML documents. For instance, a
hypermedia link might point to an audio file, a QuickTime movie file, or a graphic file such as a GIF- or
JPEG-format graphic.
Because of the flexibility of the Web protocol, a Web server can send these files just as easily as can an
HTML document. All you need to do is create the link to a multimedia file. When users click that link,
the multimedia file will be sent over the Web to their browser programs.
Helper Applications
Once the user’s Web browser receives the multimedia file, it's up to the browser to decide how to
display or use that multimedia file. Some browsers have certain abilities built in-especially the basics,
such as displaying graphics files or plain ASCII text files. At other times, browsers will employ the
services of a helper application
Most of these helper applications will be add-on programs that are available as commercial or
shareware applications. The browser will generally need to be configured to recognize particular types
of multimedia files, which, in turn, will cause the browser to load the appropriate helper application.
Once loaded, the downloaded multimedia file will be fed to the helper applications, which can then
play or display the multimedia file
Common Multimedia Formats
Although it seems that multimedia formats are constantly being added and improved for the Web,
some of the more common types of multimedia files are listed in Table 1.1 with their associated file
extensions. This list isn't exhaustive, but it should give you an idea of the types of files that can be
distributed on the Web.
Not all of these different file formats necessarily require a special helper application. Many sound
helpers will play the majority of different sound files, for instance, and some graphics programs can
handle multiple file types. For the most part, you will need different helper applications for the
various video, animations, and formatted text file types.
.jp Japanese
Common First-Level Domain Names
You may have also noticed that the address doesn't include a host name or a sub-domain. For this
particular address, it is unnecessary because America Online handles all incoming Internet e-mail
through a gateway. Once it receives the e-mail, it may indeed send it to another computer within its
online service, but this is an internal operation that doesn't require a specified host in the Internet
address.
Consider todd@lechery.isc.tamu.edu. Notice how it uses all of the possible parts of an Internet
address. todd is the username, lechery is a host computer (in this case, an actual, physical computer
named "lechery"), isc is a sub-domain name that represents the computers in the Institute for Scientific
Computation, tamu is the domain name for all Internet-connected computers at Texas A&M University,
and edu is the three-letter code for educational, which is the type of organization that Texas A&M is
considered to be on the Internet.
UseNet Newsgroups
The next Internet service we'll talk about is UseNet newsgroups. These are the discussion groups on the
Internet, where people gather to post messages and replies on thousands of topics ranging from
computing to popular entertainers, sports, dating, politics, and classified advertising. UseNet is a very
popular Internet service, and most Web browsers have some built-in ability to read UseNet discussion
groups.
Like Internet e-mail, UseNet discussion groups have their own system of organization to help you find
things. This system uses ideas and syntax that are similar to e-mail addresses, but you'll notice that
UseNet doesn't require that you find specific hosts and servers on the Internet-just a particular group.
UseNet newsgroup names use the following format:
first-level name.second-level.third.forth...
The first-level name indicates the type of UseNet group this is, the second narrows the subject a bit,
and the address continues on until it more or less completely describes the group. For instance, the
following are both examples of UseNet newsgroup addresses:
co.general
comp.sys.ibm.pc.misc
The first-level name co means this is a local UseNet group for the Colorado area, and general shows
that it's for discussion of general topics. Comp is a common first-level name that suggests this is an
internationally available newsgroup about some sort of computing issue (see Table). The other levels of
the name tell you more about the group.
WAIS, or Wide Area Information Servers, are basically database servers that allow you to search
databases that are attached to Gopher menus. Library databases, academic phonebooks, and similar
information are kept in WAIS systems.
Gopher and WAIS both generally require that you have the exact address of the Gopher server available
to you. These addresses are in the following form:
host.sub-domain.domain.first-level domain
This works essentially like an e-mail address without a username. All the Gopher application needs to
know is the exact Internet location of the Gopher server computer you'd like to talk to. An example
might be marvel.loc.gov. This takes you to a Gopher menu for the Library of Congress.
FTP
The File Transfer Protocol (FTP) is the Internet service that allows computers to transfer binary files
(programs and documents) across the Internet. This is the uploading/downloading protocol that you
might use to obtain copies of shareware or freeware programs, or that might be useful for downloading
new software drivers from a particular computer hardware company.
Using a model identical to the Gopher system, FTP addresses use the following format:
host.sub-domain.domain.first-level domain
Like Gopher addresses, an FTP address is simply the Internet address of a particular host computer. In
fact, the same host address can be used to serve you both Gopher documents and FTP file directories,
based on the type of protocol your access software requests. The following example is the FTP address
for downloading support and driver files for Apple Macintosh computers and Apple-created Mac and
Windows software:
ftp.support.apple.com
In most cases, FTP connections also require some sort of login procedure, which means you'll need a
username and password from the system administrator to gain access. The majority of public FTP sites,
however, are anonymous sites, which allow anyone access to their files. For these sites, the username
is generally anonymous, and you're asked to enter your e-mail address for the system's password.
Review Questions
1. What does URL stand for?
a. United Route Link
b. Uniform Resource Locator
c. Up Real Late
d. Unknown Redirection Link
2. What is the name of the language you use to write a web page?
a. HTTP
b. UML
c. HTML
d. URL
Summary
Web is a complex, international level, cross platform, cross language, cross cultural
mesh of servers, clients, users and databases. The World Wide Web is an Internet
service, which allows a particularly configured server computer to distribute
documents across the Internet. HTTP is used between client and server
communication so that communication can happen smoothly and properly. Internet
e-mail is designed for the transmission of ASCII text messages from one Internet
user to another. Newsgroups are the discussion groups on the Internet, where
people gather to post messages and replies on thousands of topics ranging from
computing to popular entertainers, sports, dating, politics, and classified
advertising. Gopher is a system of menu items that link sites around the world for
the purpose of information retrieval. Using File Transfer Protocol (FTP), the
transfer of binary files (programs and documents) across the Internet is happening.
Objectives
• To explain Advantages and Disadvantages of Web
• Understanding Current state of HTML
• Understand what is web Server
• Speed of web server, ISP for web sites
• Discuss uploading of pages on web server
Another emerging use for HTML on the Web is as a basis for something called a Web application. In
essence, a Web application is a Web site designed to do more than simply present pages and
hypermedia links to its users-it actually acts as a front end for data processing. Once the data are
entered on the page, the Web server passes them to programs that process the information looking up
the product in the database or taking the order. The results of these programs can be generated
complete with HTML codes, so that the answers can be viewed by the salesperson in her Web browser.
Advantages
There are many good reasons to commit to creating a presence on the World Wide Web. Most of these
are geared toward businesses, but you'll notice that these advantages are available to any Web site:
Multimedia presentation-A Web site allows you to do things that are simply not possible in any other
medium. With some of the visual impact of television, the informational utility of print, and the
personal appeal of radio, the Web is an effective tool for taking marketing information to another
level. Products can be explained and offered in depth, along with pictures, video, sound, and even
animation.
Interactivity-There are a number of different areas where the fact that your user can interactively
determine what to view or hear can really make the difference for a business. Especially important is
the added value the Web gives you for customer service, technical or product support, and immediate
feedback. While most of any Web site is automated, it gives you an opportunity to answer frequently
asked questions and point customers to resources that may help them solve problems on their own.
While this may seem like an advantage reserved for computer companies, consider the implications for
service-oriented industries like travel, consulting, catalogue sales, and business-to-business sales.
Flexibility-If your business relies on printing or publishing as a medium, you may immediately see the
advantage of the Web. Changes on the Web are relatively instantaneous, and the speed with which an
update can be made is measured in minutes, not weeks. Consider the financial planner's or real estate
agent's sales newsletter. Instant changes on the World Wide Web give their Net-savvy clients a time-
based edge. Incorporating the Web into the services you offer a client gives you an added value in their
eyes, especially in time-sensitive industries.
Easy High-Tech-Whether you're a small or large business, it's important to keep up with technology in
order to satisfy customers and be up on the "latest." Web pages are moving toward a point where
they'll be expected of large businesses and not unusual from small ones. Like e-mail a couple years ago,
and fax machines before that, it's become important to keep up with the Web. Fortunately, it's also
rather easy to get started with HTML and quickly develop a Web site.
Disadvantages
It's difficult to say that there are disadvantages in having a Web site, since most people and companies
will use a Web site to enhance their marketing and customer service efforts, not supplant them. That
said, there are a few hurdles to leap, and they should definitely be considered before your Web project
takes off:
Learning Curve- It will take a while for folks to learn HTML, figure out how to upload pages, create
appropriate graphics, and design effective Web sites. You'll also need to find an effective and helpful
Internet service provider (or a similar in-house IS employee at a larger corporation) who can help you
get online.
Appearance- To be truly effective, a Web site also needs to be attractive and easy to use. For many
companies, especially larger ones, that will mean using professional artists, writers, and designers.
Beginning this task can be daunting, and will require a reasonable budget-which may be intimidating
when management isn't sure what the benefits will be.
Maintenance and Timeliness- One of the worst things that can happen to a Web site is for it to sit
dormant for weeks or months because it's the pet project of an interested employee who has less time
for it than she originally anticipated, or because every change to the Web site must first be approved
by a committee. It's important that a Web developer be relatively free to spend time on the project,
and that someone be available to make timely decisions. Without this, the Web site loses some of its
inherent advantages.
Security- Transmitting data via Internet technology, including the Web, is inherently a rather
unsecured process. For data to be transmitted over the Web, it has to pass through a number of
different servers and hosts-and any of the information you offer could potentially be read or held by
any of these people. This has been a strong argument against commerce on the Web, as people
recognize the dangers in revealing personal information (for instance, credit card numbers). Currently,
it's difficult to create completely secure Web sites that offer access only to password-bearing users,
and those passwords are often not impossible to intercept.
Copyright Issues- The lack of security holds true for the Web designer-nearly anything you create on
the Web can easily be read or copied by anyone with Web access. This is intimidating both to artists
and publishers who want to make sure that Internet access doesn't, in some way, devalue their
published (and profitable) efforts.
Cost-Depending on the size of your organization and the expertise of its people, a Web site can quickly
become expensive. Learning HTML and creating a reasonable site isn't that difficult (as you'll see in this
book), but maintaining the appropriate equipment, paying the dedicated staffers, and bringing in
consultants, designers, programmers, and IS technicians as the site grows can quickly expand the
budget. The advantages will often outweigh these costs, but any Web developer should be aware that
Web sites tend to get bigger and more time-consuming as time goes on.
standards can be agreed on as technology emerges-and competing browsers can all use the same
methods to incorporate new technology.
Web Server
Before you can display your HTML pages on the Web, you'll need access to a Web server. This may
already be taken care of for you, especially if you work with an Information Systems (IS) department in
a larger corporation. If this is the case, you'll just need to know how and where to send your HTML files
when you want to update the site. Otherwise, you'll need to make some arrangements on your own.
It isn't terribly difficult to set up your own Web server-especially if you already have a high-speed
connection to the Internet. If you access the Internet through an Internet service provider (ISP), you'll
want to discuss this with them, though. More than likely, they're willing to provide you with space on
their Web server computers. If your Web site is a fairly small venture, or if you're not ready for a heavy
investment in equipment, then using your ISP's Web server is a great (and very common) alternative.
Web server software generally requires a fairly robust operating system (like UNIX, Windows NT, or
OS/2), although software is available for other versions of Microsoft Windows, and the Macintosh OS is
a very popular choice for Web server computers. The software you use depends on your level of
experience with Internet connections and various operating systems.
The minimum for an acceptable Web server connection is probably a basic-rate ISDN (Integrated
Services Digital Network) connection, which offers 128,000 bps connections to the Internet. ISDN
technology uses your existing phone wiring to provide an enhanced, digital, telephone connection.
Training & Development Division Page 17 of 282
HTML, DHTML & JavaScript
Using a special network adapter card for your computer, you can use the ISDN line to dial an
appropriately equipped ISP. You can also use the ISDN connection for regular telephone calls.
A T-1 line is the typical connection for an ISP or a large business, and these lines generally cost
thousands of dollars per month for Internet access, as do primary-rate ISDN connections. T-3 lines
currently serve as the backbone of the Internet, and are generally only found connecting university,
government, and supercomputing organizations.
For the typical smaller Web site, you'll want to buy space on the ISP's Web site. Generally this will give
you an URL that begins with the name of the ISP's host computer, but points to a special directory for
your HTML pages, such as http://www.isp.com/username/index.html.
With most Web server programs, the default page that is first loaded is named index.html, so that's the
name you'll use for the first page you'd like presented to users when they access your Web site.
• Site's default URL- This should be something like the ISP's host address and a directory for your
username. For instance, if your username is user1 and your ISP's Web server is
www.lntinfotech.com then the default URL for Site will be
http://www.lntinfotech.com/user1/.
Different ISPs will organize this in different ways, so you'll need to make sure you get this right.
• Uploading files to the site's directory- You should get instructions for accessing your Web
site's directory on the Web server computer using either FTP or a UNIX shell account.
• Limitations to the names you can give to your files- The operating system in use by the Web
server may not be instantly obvious to you. If this is the case, you'll want to ask if there is a
certain filename length or a certain format for naming files you need to follow.
• Creating subdirectories within your main Web site directory- Most Web servers will give you
this capability, but some will not allow you to create new subdirectories.
• Support offered for CGI programming- Some servers wouldn’t allow you to add CGI scripts to
your Web site for processing forms or adding other interactive features. At the same time,
some will, but require you to pay extra or pay to have the provider write those scripts
(regardless of your ability). If you plan a highly interactive site, then you should ask about CGI
support.
Organizing a Web Site
The most important thing to remember when organizing a Web site is how the server computer you're
using will differ from the computer you use to create Web pages. This is because you'll need to know
the exact path to HTML pages and multimedia files you use in creating your Web page. As we've seen
before, an URL requires both a server name and a path statement to the file. This includes files that
you've placed on your own Web server-so while you're creating your Web pages, you'll need to know
where your files will eventually be.
Training & Development Division Page 18 of 282
HTML, DHTML & JavaScript
Although there are a number of different ways to arrange a Web site, there are some rules of thumb to
keep in mind. For the most part, any organization you create for your Web site files should be designed
to make updating your pages easy in the future. If you have to move all your files around every time
you change something on a Web page, you'll also be forced to change all the hypertext links on many
other pages-and that can be incredibly time-consuming.
Different types of organization for Web sites:
• Single-directory sites- Smaller sites (with just a few HTML pages and graphics) can often get
by with a single directory on the Web server. All your graphics and HTML pages are in this one
directory. One of the biggest advantages of this system is that links to local files and graphics
require no special path statements.
• Directory by function- One way to organize more complicated sites is to put each section of
related Web pages in the same directory. For instance, in your main directory you might offer
only your first (index) page and its associated graphics. For a business site then, you'd have
subdirectories for About the Business, Product Information, Technical Support, and so on. In
each of these subdirectories, you'd include all the related HTML files and the graphics for those
pages.
• Directory by file type- Some people prefer to create subdirectories according to the type of
file as opposed to the content of the page. Your main directory may have only the index page
of your site. Other subdirectories might be Graphics, Web Pages, Downloadable Files, and so
on. The main advantage in organizing this way is that files generally have to be replaced only
once. If you use a graphic on a number of different pages, for instance, you replace it once in
the Graphics subdirectory, and all the HTML pages that access this graphic will use the new
one.
• Hybrid- The best way to organize a large site might be a hybrid of the last two methods above.
Creating separate subdirectories for nonrecurring items (such as individual Web pages in each
category) while creating other subdirectories for items used multiple times (such as graphics)
lets you get to all the files in an efficient way.
Naming Your Files
We've already mentioned that file extensions are an important part of all the filenames you use for
your Web site. Because other Web browsers may rely on the file extension to know what sort of
document or file it is, you'll need to include the appropriate extensions with all your Web site files.
Web site will almost always begin with a file called index.html. Most Web server software programs
will automatically load this page if the URL of your site is accessed without a specific path and file
reference. For example, entering http://www.sun.com/ in your browser actually results in the URL
http://www.sun.com/index.html being loaded in your browser. Web site's first page (whether it's a
"front door" page or the first page of your site) should be designed with this in mind. If you plan to
offer only Netscape-enhanced pages, for instance, you'll want to let your users know this on the
index.html page. The other consideration for naming your files is the organization you plan to use for
your site. If you're using a single-directory organization, your filenames should be as unique as possible,
and graphics and other files should probably have names that relate to associated Web pages.
For instance:
about_company.html
about_header.jpeg
about_ceo_photo.jpeg
When possible, these names will help you determine which files are associated with which HTML pages
when you go to update those files.
For graphics and other files that show up on multiple pages, you might want to come up with a
memorable prefix, like gen_ or site, just so you can easily replace these universal files when necessary.
Your Web space provider will require you to enter a username and password to gain access to the Web
server, whether by FTP or shell account. Generally, you will point your FTP server to the Web server
itself (for instance, www.isp.com), unless the provider has created a mirror site to avoid direct access
to the Web server.
After clearing the security procedure, you'll most likely be in your personal Web site's main directory.
(If not, you'll need to use the ‘cd’ command in UNIX or otherwise change directories in your FTP
program.) From that point, you can update files using the Put command. Simply upload the updated
files with the same names as the outdated files-in nearly every case, the old files will simply be
overwritten. If you're using new files, upload them using the names and paths that your Web page links
use to refer to them.
Tip: It's a good idea to maintain a folder or directory on your own hard drive that is as identical as
possible to the Web site you make available on a server-so you can test your organization and
filenames.
Review Questions
1. All HTML tags are enclosed in ____.
a. < and >
b. % and %
c. # and #
d. “ and “
4. The most recommended file name to "save as" for your homepage is
a. Home.html
b. Index.html
c. Page.html
d. Front.html
Summary
As there are certain advantages of the Web and there are certain disadvantages
too. We'll need Web server software, an Internet connection, a Web URL for our
pages, and a system for organizing our pages and graphics. Before we can display
our HTML pages on the Web, we need access to a Web server. With most Web
server programs, the default page that is first loaded is named index.html, so
that's the name we'll use for the first page we'd like presented to users when they
access our Web site. Smaller sites (with just a few HTML pages and graphics) can
often get by with a single directory on the Web server.
Objectives
• Use various tools of web designing
• List type of tags used in HTML pages
• Create a HTML page
With the basics behind you, it's time to start creating your first HTML pages. As already been
mentioned, the basic building block of an HTML page is text. To create these pages, all you really need
is a text editor and a Web browser for testing your creation (you'll eventually need a graphics program
to create and edit your graphics, too). So let's look at the basic tools for Web publishing, and then
create your own HTML template.
Tip: If you create an HTML page in a word processor, don't forget to use the Save As command to save
it as an ASCII text file.
We'll also need a Web browser to check on the appearance of your Web page as you create it. All Web
browsers should have the ability to load local pages from your hard drive, just as they can load HTML
pages across the Web. Check the menu of your Web browser (if it's a graphical browser) for a command
like File,
In Microsoft Internet Explorer for Windows XP, the File, Open command opens the Open Internet Address dialog box which
contains an Open File command button to open a file from a drive
You may have heard of some dedicated HTML editing programs that are designed to make your work in
HTML easier. They do indeed exist, and they can be very useful. Unfortunately, many of them also hide
the HTML codes from the designer, so they would be difficult for us to use as you learn how HTML
works. Once you understand HTML, though, it can be a great benefit to use one of these browsers.
Document Tags
The first HTML tags we're going to look at are the document tags. These are the tags that are required
for every HTML page we create. They define the different parts of the document.
Just like a magazine article, an HTML document has two distinct parts-a head and a body. The head of
the HTML document is where you enter the title of the page.
To create the head portion of HTML document and to give the document a title, type the following in
your text editor:
<HEAD>
<TITLE>My First Page</TITLE>
</HEAD>
This tells a Web browser what information should be considered to be in the head portion of the
document, and what it should call the document in the title bar of the browser window.
The body is where we'll do most of our work-you'll enter text, headlines, graphics, and all our Web
goodies. To add the body section, start after the </HEAD> tag, and enter the following:
<BODY>
</BODY>
Between these two tags, you'll eventually enter the rest of the text and graphics for your Web page.
There's one last thing you need to consider, in order that all Web browsers understand that this is an
HTML document (remember that you're saving it as ASCII text, so the browser could be confused), you
need to add some tags on either side of the head and body tags you've created. Above the first <HEAD>
tag, enter the following:
<HTML>
After the last </BODY> tag, type the following:
</HTML>
Now, at least as far as your Web browser is concerned, you have a complete Web document!
Example: Creating an HTML Template
Let's take what you know and create a template. By saving this template as a generic text file, you'll
have a quick way to create new HTML files-simply load the template and use the File, Save As
command to save it as your new Web page.
Start by entering the following in a blank text file:
<HTML>
<HEAD>
<TITLE>Enter Title Here</TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>
Now save this as an ASCII text file called template.html (or template.htm if you're using DOS or
Windows 3.1). Now, whenever we are ready to create a new HTML document, simply load
template.html into your text editor and use the Save As command to rename it.
Empty Tags
All other tags in HTML fall into one other category, called empty tags. These tags have only on tag-
there are no off tags. The reason for this is that empty tags don't act on blocks of text. Instead, they
do something all on their own. An example of this would be the <HR> (horizontal rule) tag. This tag
draws a line across the width of your document. For example:
The following is a horizontal line
<HR>
The rest of this is just more text.
When viewed in a Web browser, a horizontal line, as shown below, will separate the two sentences:
</P>
Here's that same example, except you'll throw in some spaces. Remember, spaces and returns almost
never affect the way the text will be displayed on the screen. In a paragraph container, the browser
will ignore more than one space and any returns.
<P>Here is the text for my paragraph.
It doesn't matter how long it is, how many spaces are between the words
or when I decide to hit the return key. It will create a new paragraph
only when I end the tag and begin with another one. </P>
<P>
Richard Smith<BR>
14234 Main Street<BR>
Any city, ST 00001<BR>
</P>
And it would look just right in your Web browser, just as in figure below
If you'd like to, most browsers will let you view the document source for any Web page they can load.
This allows you to download the raw HTML codes and ASCII text, just as if you'd created the page
yourself.
To do this, select the View Document command in the Edit menu of your Web browser (the command
may differ slightly, so look for a similar name if you can't find View Document). What results is the
plain ASCII text file that was used to create that Web page.
Depending on your browser, this source file will either be displayed in the browser window, or saved to
your hard drive and displayed in the default text editor. If the source is displayed in the browser
window, then select File, Save As to save the source to your hard drive.
Now you might be able to imagine how comments can come in handy. If you would rather not have
people copy and use the source from your Web pages (or if your pages contain otherwise copyrighted
material that you want to protect), you can use the comment tag to let others know that you consider
the page your property. For instance:
<!-- Contents of this document Copyright 1996 Todd Stauffer. Please do not copy or otherwise
reproduce the source HTML code of this document without permission. -->
Of course, that's not to say that you shouldn't also offer a visible copyright notice or other legal
disclaimers. But comments within the code tend to talk directly to folks a little more HTML-savvy.
Using a comment tag like this is a great way to encourage other Web designers to ask you before using
your HTML pages for their own private use.
Review Questions
1. What does HTML do?
a. It processes code to form a program
b. It interprets code and display it on screen
c. It contains instructions for the browser to work
d. It is the language used to create websites
2. How to insert comments in HTML?
a. <-- ... -->
b. <!-- ... -->
c. <!- ... -->
d. <- ... -->
3. The Browser applies the feature of a tag until it encounters _____ tag.
a. Quit
b. Closing
c. Exit
d. Deactive
4. _______are the HTML codes that control the appearance of the document contents
a. Tags
b. Codes
c. Slashes
d. Properties
5. State True or False. HTML Tags are case sensitive.
a. True
b. False
Summary
Basically, all we need to remember is that HTML pages, while they include
the .htm or .html file extensions, are simply ASCII text files. We'll also
need a Web browser to check on the appearance of our Web page as we
create it. All Web browsers should have the ability to load local pages from
our hard drive, just as they can load HTML pages across the Web.
Document tags are the tags that are required for every HTML page we
create. In HTML, tags that include both an ‘on’ and an ‘off’ tag are called
container tags. Some tags in HTML fall into one other category, called
empty tags. These tags have only ‘on’ tag-there are no ‘off’ tags.
Objectives
• To use header and headline in document
• Quoting, Definitions, and Addresses
• To Preformat the text
HTML header tags at work. Notice that the fourth entry is regular text between <P> and </P>tags.
We cannot include a header tag on the same line as regular text, even if we close the header tag and
continue with unaltered text. A header tag has the same effect as a <P>, in that it creates a new line
after it’s "off" tag. The following:
In both cases, the Web browser will place the header text and plain text on different lines, with the
header text appearing larger and the plain text appearing "normal" in size.
Note: The HTML standard technically requires that using a particular header level requires that the
larger header tags be used previously. So, for instance, if you use an <H2> tag, you should have an
<H1> tag somewhere before it. Very few browsers (if any) actually require this and, for the most part,
HTML designers use header tags as simply a way to change the size of text for emphasis. That's how I
use them, even going so far as to use <H5> or <H6> for "fine print" on my pages. If you're an absolute
stickler for standards, though, realize that it's more correct to only use header tags for true headers in
your documents, and then only in order (i.e., <H1>, <H2>, <H3>, and so on).
header tags in somewhat similar ways, others (for instance, nongraphical browsers) have to come up
with another system for emphasis, such as underlining or highlighting the text.
Because HTML was originally created with the overriding mission of being displayed on nearly any
computer system, implicit tags for emphasis were a necessity. HTML allows the designer to decide what
text will be emphasized. But only explicit tags tell the Web browser how to render that text.
Explicit Styles
Explicit tags are also often called physical tags, since they very specifically tell the Web browser how
you want the text to physically appear. The browser is given no choice in the matter.
The basic explicit tags are containers that let the user mark text as bold, italic, or underlined.
Tags Meaning
<B>, </B> Bold text
<I>, </I> Italic text
<U>, </U> Underlined text
HTML Physical Container Tags
Note: Not all browsers will render underlined text (notable among them is Netscape Navigator),
because hypertext links are also often displayed as underlined, which could potentially be confusing.
With these tags, the browser really has no choice-it must either display the text as defined or, if it
can't do that, then it must add no emphasis to the text. If we prefer that text not be emphasized at all
if it can't be italic, for example, then we should use the <I> tag.
Another feature of explicit (physical) tags is that they can generally be used in combination with other
tags. As we'll see in the next section, this isn't always a good idea with implicit tags. For instance, most
graphic browsers will render the following example by applying both tags to the text
Most browsers can render two physical tags applied to the same selection of text.
<H1><I>Welcome Home!</I></H1>
<B><I>This is bold and italic</I></B>
Above table includes a section that tells you how these tags are often rendered in graphical Web
browsers. There's no rule for this, though, and the tags don't necessarily have to be rendered in that
way.
There are two other distinctions between these tags and the physical tags (such as bold and italic) that
you've already discussed. First, any Web browser that views them will always render these logical tags.
Even text browsers (which are unable to show italic text) will display the <EM> or <STRONG> tags by
underlining, boldfacing, or highlighting the text.
Second, these tags are generally not effective when used together. Where <B><I>text</I></B> will
sometimes offer useful results, <EM><STRONG>text</STRONG></EM> rarely will. Combining these tags
with other tags (such as header tags or physical tags) is often either ineffective or redundant.
Notice that the majority of these tags are often displayed in exactly the same way-in the default
monospaced font for the browser. Then why use them?
First, not all browsers will necessarily follow the "general" way. Some browsers will actually render
these tags in slightly different ways from one another, so that <SAMP>, for instance, might appear in a
slightly larger font than <CODE>.
Second, using these tags is a great way to internally document your HTML pages, so that you can tell at
a glance what certain text is supposed to be. This will help you later when you return to the document
to update it or fix errors-especially as the document becomes more complex.
Again, notice that the <CITE> tag isn't going to be rendered any differently from the italics, emphasis,
or variable tags we've seen previously. The <DFN> tag is often not rendered as any special sort of text
at all, whereas the <ADDRESS> tag is identical in function to the italics tag. So the best use for these
tags (with the exception of the <BLOCKQUOTE> tag) is as internal documentation of your HTML
documents.
Example: Using the <BLOCKQUOTE> and <ADDRESS> Tags
The only really new tag in the above table is the <BLOCKQUOTE> tag. This tag usually indents the left
margin of regular text in the browser window, just as you might find a blocked quotation formatted in
a printed document.
Also as part of the tag, <BLOCKQUOTE> generally adds a return or one extra line on either side of the
tag, so no paragraph tags are needed. Paragraph tags should, however, be used to contain text on
either side of the blockquote.
Although the <ADDRESS> tag is similar to italics or emphasis, I've thrown in an example of using it
correctly. Remember to include a line break after each line of the address.
Listing -between the body tags.
The <BLOCKQUOTE> and <ADDRESS> Tags
<BODY>
<P>I believe it was Abraham Lincoln who once said (emphasis is mine):
<BLOCKQUOTE>Four score and seven years ago our <B>forefathers</B> brought
forth on this continent a new nation, conceived in <I>liberty</I> and
dedicated to the proposition that all men are created <EM>equal</EM>.
</BLOCKQUOTE>
It was something like that, wasn't it?
</P>
<P>If you liked this quote, feel free to write me at:<BR>
<ADDRESS>
Rich Memory<BR>
4242 Sumtin Street<BR>
Big City, ST 12435<BR>
</ADDRESS>
</P>
</BODY>
Notice that an off paragraph tag isn't required before you get into the address tag-remember,
<ADDRESS> works very much as italics does, and the <BR> tag is designed to work as well inside a
paragraph container as it does outside one. So you can put the paragraph tag after the address, to
contain both address listing and the text in the same paragraph.
Take a look at next figure <BLOCKQUOTE>, unlike some of the tags you've looked at, really does offer
unique abilities that make it worth using in your documents.
Preformatted Text
The HTML 3.0 standard is not designed for layout. In fact, you haven't even learned how to put two
blank lines between paragraphs. We've also said that spaces and returns in between tags (like the
paragraph tag) don't matter. Well, there is at least one exception to this rule: the <PRE> tag.
The <PRE> (preformatted text) tag is designed to allow us to keep the exact spacing and returns that
we've put between the on and off tags. The basic reasoning behind this tag is the notion that every
once in a while we'd like your text to stay exactly as we put it-for instance, in a mathematical formula,
or if we create a table. While there are other ways to do both tables and math, they don't fall under
the HTML 3.0 standard. On top of that, you can use <PRE> for a number of other reasons: lists, lining
up decimals for dollar figures, and even poetry.
Sure it's a familiar refrain, but it won't look so familiar in a browser if we leave it between paragraph
tags. Instead, we can use the <PRE> tag to keep things exactly the way we want them:
<PRE>Oh beautiful, for spacious skies,
For amber waves of grain.
For purple mountains' majesty,
Above the fruited plains.</PRE>
In a browser, it'll look exactly the way we want it to
We have noticed that the preformatted text is in a monospace font, it will always be that way.
Otherwise, the <PRE> tag works pretty much like the paragraph font, except that it lets us decide
where the line breaks and spaces will appear. Look at the following example:
<PRE>
I simply want to make this <B>really</B> clear to you.
</PRE>
With the above code, the browser will display this line in nearly exactly the same way as it would using
the <P> tag, except that it will be in a monospace font, and the extra spaces and extra return will
appear as well. In fact, there will be two blank lines below the line of text-one for the return, and one
for the </PRE> tag itself.
We can even use the <PRE> tags to create extra lines in a document without typing any text between
them. This example adds two blank lines to a document:
<PRE>
</PRE>
For each additional blank line you want to add, just press Enter after the first tag one time.
Note: There is one potential drawback to the <PRE> tag. It doesn't allow the browser screen to wrap
text automatically-instead; users need to expand their browser window if we use particular long lines
within a <PRE> container. Just keep this in mind, and make sure your lines of text are reasonably short
so that all browsers can view them without scrolling.
Tip: One way to keep the columns in a table straight is to type your table first, and then add emphasis
tags afterward.
Load your template and save it as pre_tbl.html. Now enter listing between the body tags.
<BODY>
<PRE>
</PRE>
<HR>
<H2>Price Per Item in Bulk Orders</H2>
<PRE>
</PRE>
<H5>Prices do not include applicable sales taxes.</H5>
</BODY>
You may need to play with the spacing a bit to line everything up. Save the HTML document, and then
choose the Open File command in browser to proof it. Keep playing with it until it looks right.
Once we have everything aligned correctly, it's actually a fairly attractive and orderly little table
Review Questions
1. The page title is inside the ____ tag.
a. Body
b. Head
c. Division
d. Table
2. All normal webpages consist of what two parts?
a. Top and bottom
b. Body and Frameset
c. Head and Body
3. Which of the following will NOT be found in the <head> section?
a. Metatags
b. Table
c. Title
d. None from the Above
4. Which section is used for text and tags that are shown directly on your web page?
a. Head
b. Body
c. Foorter
d. All of the above options
5. To specify a font for your whole page add which tag?
a. <targetfont>
b. <defaultfont>
c. <basefont>
Summary
Header tags are containers, and unlike many other HTML tags, they double
as paragraph tags. Browsers can render two physical tags applied to the
same selection of text. Part of the HTML 3.0 standard, offers some implicit
(logical) HTML tags that allow HTML designers to mark text in a way that
makes it easier to present computer-programming codes. Various publisher
tags can be used to make designing of web pages attractive. Preformatted
text tag is designed to allow us to keep the exact spacing and returns that
we've put between the on and off tags.
Objectives
• To list content of page by using List tag
• Use Directories, Definitions, and Menus
• Quoting Definitions, and Addresses
<LIST TYPE>
<ITEM> First item in list
<ITEM> Second item in list
<ITEM> Third item
</LIST TYPE>
Each of the items appears on its own line, and the <ITEM> tag itself is generally responsible for
inserting either a bullet point or the appropriate number, depending on the type of list that's been
defined. It's also possible that the <ITEM> tag could insert no special characters (bullets or otherwise),
as is the case with definition listings.
You'll look at each type in the following sections. The basics to remember are to use the main
container tags for list type and the individual empty tags to announce each new list item. The type of
list you choose is basically a question of aesthetics.
Ordered and Unordered Lists
It might be better to think of these as numbered (ordered) and bulleted (unordered) lists, especially
when we're talking about their use in HTML. The only drawback to that is the fact that the HTML codes
for each suggest the ordered/unordered names. For numbered/ordered lists, the tag is <OL>, and for
bulleted/unordered lists, the tag is <UL>.
For either of these lists, a line item is designated with the empty tag <LI>. In the case of ordered lists,
the <LI> tag inserts a number; for unordered lists, it inserts a bullet point. Examples of both follow.
The following is an ordered list:
<OL>
<LI> Item number one.
<LI> Item number two.
<LI> Item number three.
</OL>
And here's an unordered list:
<UL>
<LI> First item.
<LI> Second item.
<LI> Third Item.
</UL>
<MENU>
<LI>House Salad
<LI>Fresh <B>Soup of the Week</B>
<LI>Buffalo Wings
<LI>Escargot
<LI>Liver and Onions
<LI>Turkey Sandwich, <EM>open faced</EM>
<LI>Turkey Sandwich, <EM>pre-fab</EM>
</MENU>
Note: You might use the <MENU> tag when creating a list of hypertext links. It's thought that future
interpretations of the menu list may be built into future browsers, and that designers will eventually
see more benefit in using the <MENU> tag.
In theory, the <DIR> tag is a little more limiting. It's designed as a mechanism for listing computer file
directories in HTML pages. Technically, it doesn't support interior HTML tags, although most browsers
will display them. The <DIR> tag is also supposed to be limited to 24 characters (for some unknown
reason) and show the filenames in rows and columns, like a DIR/W command in MS-DOS, but the bulk of
browsers seems to ignore both of these constraints as well, as in the following example:
<DIR>
<LI> autoexec.bat
<LI> config.sys
<LI> .signature
<LI> .password
<LI> System Folder
<LI> commaand.com
<LI> .kernel
</DIR>
Most browsers (including Netscape) will use the same font and layout for menus and directories, as
they will for unordered lists. In some cases, browsers will display one or the other (more often
directory lists) without a bullet point, which can make them mildly useful. Some browsers can be set to
a different font for directories and menus (versus ordered lists). So you may want to use these types, if
only because some Web-savvy users' browsers will make an effort to display them differently (as shown
in below figure).
Definition Lists
The final list tag is the definition list, which is designed to allow for two levels of list items, originally
conceived to be the defined term and its definition. This is useful in many different ways, though, and
is also nice for its consistent lack of bullet points or numbering items (as opposed to the menu and
directory listings, which are often rendered haphazardly by browsers). The tags for this list are the
container tag <DL> (definition list) and two empty tags, <DT> (definition term) and <DD> (definition).
The <DT> tag is designed (ideally) to fit on a single line of your Web page, although it will wrap to the
beginning of the next line if necessary. The <DD> tag will accept a full paragraph of text, continuously
indented beneath the <DT> term. The following is an example of all three tags:
<DL>
<DT><B>hero</B> <I>(n.)</I>
<DD>A person admired for his or her brave or noble deeds.
<DT><B>hertz</B> <I>(n.)</I>
<DD>A unit used in the measurement of the frequency of electromagnetic waves
<DT><B>hex</B> <I>(n.)</I>
<DD>An evil spell or magical curse, generally cast by a witch.
</DL>
Notice that standard HTML mark-up is permissible within the boundaries of a definition list, and that
using bold and italics for the defined terms adds a certain dictionary-like quality.
Tip: Not all browsers will display definition lists in the same way, so adding spaces to <DT> items (to
get them to line up with the <DD> text) is often a waste of time.
It should also be pointed out that just because definition lists allow for two different types of list
items, you needn't necessarily use both. Using just the <DT> tag in your list, for instance, will result in
a list not unlike an unordered list-except that nearly all browsers will display it without bullets:
<DL>
<DT>Milk
<DT>Honey
<DT>Eggs
<DT>Cereal
</DL>
And, although more difficult to find a use for, the <DD> item could be used on its own to indent
paragraphs repeatedly.
<P>I must say that I was shocked at his behaviour. He was:
<DL>
Training & Development Division Page 47 of 282
HTML, DHTML & JavaScript
<DD><I>Rude.</I> Not rude in your standard sort of affable way, or even in a way that would be
justifiable were he immensely wealthy or critically wounded. It was just a rudeness spilling over with
contempt.
<DD><I>Unjust.</I> If there was something he could accuse you of falsely,
he would do it. I could almost see him skulking around his apartment after a particularly unsuccessful
party, doing his best to find things stolen, which he could blame on people who hadn't actually
bothered to show up.
</DL>
</P>
The definition list offers some additional flexibility over the standard lists, giving you more choices in
the way you layout the list items.
This is an example of correctly nesting the <EM> tag within a paragraph container. On the other hand,
many browsers would still manage to display this next code:
<P>She was easily the most <EM>beautiful</P> girl in the room.</EM>
But this second example is really poorly constructed HTML. It often works, but the <EM> tag isn't
properly nested inside the <P>. In this example, that doesn't matter too much, since you can still
reason out what this statement is trying to do.
With lists, however, things can get complicated. So it's best to remember the "nesting" concept when
you begin to add lists within lists. As far as HTML is concerned, a nested list works as marked-up text
within the previous list item. When the next list item is called for, HTML moves on.
Tip: It's a good idea to indent nested lists as shown in the example. The browser doesn't care-it just
easier for you (or other designers) to read in a text editor. (Regardless of your spacing, most browsers
will indent the nested lists-after all, that's the point.)
Notice that the nested list acts as a sublevel of the Chapter One list item. In this way, we can simulate
an outline in HTML. Actually, the nested list is just HTML code that is part of the <LI>Chapter One list
item. As we saw in below listing you can use the <BR> tag to create a line break in a list element
without moving on to the next list item. Following the same theory, an entire nested list works as if it's
a single list item in the original list.
The following:
<OL>
<LI>Section Five<BR>
This section discusses ducks, geese, finches and swans.
<LI>Section Six
</OL>
is essentially the same as the list that follows:
<OL>
<LI>Section Five
<OL>
<LI> Ducks
<LI> Geese
<LI> Finches
<LI> Swans
</OL>
<LI> Section Six
</OL>
In both cases, the nest HTML container is simply a continuation of the first list item. Both the text after
the <BR> in the first example and the ordered list in the second example are part of the list item
labelled Section Five.
In both of the examples, the HTML container is simply part of the list.
<OL>
<LI>Introduction
<LI>Company Financial Update
<UL>
<LI>First Quarter
<LI>Second Quarter
<LI>Third Quarter
<LI>Fourth Quarter
</UL>
<LI>Advertising Update
<UL>
<LI>Results of Newspaper Campaign
<LI>Additions to Staff
<LI>New Thoughts on Television
</UL>
<LI>Human Resources Update
</OL>
There's nothing terribly difficult to learn here-just the added benefit of being able to nest different
types of lists within others. You're still simply adding HTML markup code to items in the original list.
This time, however, you have more choice over how your outline looks (see fig. 6.6).
Review Questions
1. To separate single list items use?
a. <ol> and </ol>
b. <ul> and </ul>
c. <li> and </li>
d. <list> and < /list>
2. When making bulleted lists you have what options?
a. square, disc, polygon
b. disc, circle, square
c. triangle, square, circle
d. No other shapes than default
3. To start a list using circles use which of these tags?
a. <ul type="circle">
b. <ul "circle">
c. <ul type="round">
d. None from the Above
4. To create a list using lowercase letters use?
a. <ol type="a">
b. <ol "a">
c. <ol letter="a">
d. Any one of the above options
5. <ol> tags will create what kind of list?
a. Numbered List
b. Bulleted List
c. Grocery List
Summary
To list content of page, List tags can be used. <MENU> tag can be used
while creating a list of hypertext links. Like MENU, Definition Lists can be
used for two levels of list items. Nesting of Tags is possible if we want to
show nested lists. We can combine more than one type of lists together to
give better look to our web pages. Depends on users choice we can change
default shapes of bullets or we can change numbering style as well.
Objectives
• Use Images in web page
• Types of graphics that can be added to web page
• Creating and Manipulating Graphics
Now that we've seen many ways we can add some character to our text-and use different tags to better
communicate your ideas-it's time to jazz up your pages a little bit. Let's add some graphics!
First, though, we should know a couple of important things about placing graphics. Some of these
considerations may seem a bit foreign to you, especially if we're a graphic designer or commercial
artist. We have to think in a slightly different way about graphics for your HTML pages.
Tip: Any graphics program, even Microsoft Paint, can create Web graphics, although you may need to
use another program to change the graphic to an acceptable file format.
Download public-domain graphics: Tons of sites on the Internet allow us to download icons, interface
elements, and other graphics for our Web site. At the same time, public-domain clipart collections
(such as those available on CD-ROM) can be useful for Web pages.
Use scanned photographs: Using scanned photographs (especially those that we've taken yourself) is a
great way to come up with graphics for your Web pages. Unless you have access to scanning hardware,
though, you may need to pay someone to scan the photos.
Digital cameras: Cameras are available that allow us to take photos that can be downloaded directly
from the camera to your computer. While some of this equipment can be very expensive, cameras
under $500 do exist, and those photos can easily be converted for use on the Web.
Use Photo CDs: Many photo development shops can create digital files of your photographs (from
standard 35mm film or negatives) and save those files in PhotoCD format. Most CD-ROM drives allow
you to access these photos, which you can then change to GIF or JPEG format and display on your Web
pages.
An absolute URL is essential, however, if we were accessing an image on a remote site, as in the
following example:
<IMG SRC="http://www.graphcom.com/pub/graphics/image1.gif">
(This example is fictitious.) Please realize that using a URL to a distant site on the Internet causes that
site to be accessed every time this <IMG> tag is encountered on your page, so you should probably have
some sort of arrangement with that Web site's system administrator before you link to a graphic on
their server.
Another popular use for graphics is including them in HTML lists. Best suited for this task is the <DL>
(definition) list, which allows you to use your own graphics as bullet points. (Ordered and unordered
lists display their numbers or bullets in addition to the graphic.)
A <DT> (definition term) tag can accept more than one <DD> (definition) element, so you can create a
bulleted list as follows:
<DL>
<DT>
<DD><IMG SRC="bullet.gif"> This is the first point
<DD><IMG SRC="bullet.gif"> This is the second point
<DD><IMG SRC="bullet.gif"> Here's the third point
<DD><IMG SRC="bullet.gif"> And so on.
</DL>
At the same time, you could use a definition list in conjunction with thumbnail graphics in a list that
uses both the <DT> and <DD> tags. An example might be the following real estate agent's pages
Use a <DL> tag to create custom bulleted lists and thumbnail lists.
<DL>
<DT><IMG SRC="Small_House14101.GIF">
<DD><EM>14101 Avondale</EM> This executive 3/2/2 is nestled among the live oak, with a
beautiful view of the foothills. $139,900.
<DT><IMG SRC="Small_House3405.GIF">
<DD><EM>3405 Main</EM> This timeless beauty is a cottage made for a prince (and/or princess!)
Spacious 2/1/1 is cozy and functional at the same time, with all-new updates to this 1880s
masterpiece. $89,995.
</DL>
Tip: Test your site with the Load Images option turned off so that you can see how your ALT text
displays.
Then load HTML template, and save it as a new HTML document. Between the body tags, type
something like
<BODY>
<IMG SRC="logo.gif" ALT="RealCorp Logo">
<H1>Welcome to RealCorp's Web Site</H1>
<H2><IMG SRC="photo.gif" ALT="Photo of CEO Bob MacFay" ALIGN=MIDDLE><EM>I'm Bob MacFay, CEO of
RealCorp...</EM></H2>
<P>We at RealCorp make it our business to be as productive and hard working as you are. That's why
we've set up this Web site...to work a little harder, so you don't have to. Take a look at the various
services our company offers, and maybe you'll see why we like to say, "We're the hardest working
corporation all week, every week."</P>
<DL>
<DT>
<DD><IMG SRC="bullet.gif" ALT="-" ALIGN=MIDDLE> Full service plans for any size of customers
<DD><IMG SRC="bullet.gif" ALT="-" ALIGN=MIDDLE> On-time service calls, any time, any day of the week
<DD><IMG SRC="bullet.gif" ALT="-" ALIGN=MIDDLE> Fully-equipped mobile
troublshooting vans
<DD><IMG SRC="bullet.gif" ALT="-" ALIGN=MIDDLE> Time honored appreciate for quality over
expediency
</DL>
</BODY>
Although the ALT attribute is optional and the bulleted list may survive without it, the example uses
ASCII to substitute hyphens for the bullet graphics if the browser can't display images. In most cases,
we'll want to describe an image that a user can't view. For an element such as a bullet, though, we can
use the ALT attribute to substitute an ASCII character for the graphic.
For the photo of the CEO, the <IMG> tag is called within the <H2> tag, because the <H2> container (like
a paragraph) otherwise would insert a carriage return and force the words I'm Bob MacFay... to appear
below the photo. Including the <IMG> tag inside the <H2> tag allows the text to appear next to the
photo
Review Questions
1. Gif and jpg are the two main types of ____?
a. Images
b. Animated effects
c. Outlines
d. Bullet types
2. Which format usually works best for photos?
a. HTML
b. jpg
c. gif
d. bmp
3. To change the size of an image in HTML use ____.
a. pliers
b. height and width
c. bigger and smaller
d. rows and cols
4. Which tag is used to insert images into your web page?
a. img
b. pic
c. src
d. scr
5. By adding alternative text to your image ______ ?
a. the user can save the image using the text as a name
b. the user can get an idea of what the image is before it loads
c. the user wishes to load a different picture
Summary
Images like GIF and JPEG format can be used to add the value of web
pages. We can create our own images by using some third party tools.
To show alternative text, we can use the ‘ALT’ attribute along with
<IMG> tag. On requirement we can set text wrapping properties, image’s
alignment etc.
Objectives
• Discuss Hypertext
• List anchor a tag and it’s attributes
• Demonstrate absolute and relative URL
We've seen in detail the ways we can mark up text for emphasis and add images to our Web pages, it's
time to take the leap into making these pages useful on the World Wide Web by adding hypertext links.
The anchor tag for hypertext links is simple to add to our already-formatted pages. We'll see how URLs
are useful for creating hypermedia links and links to other Internet services.
Be aware that HREF, although it's something that you'll use with nearly every anchor tag you create, is
simply an attribute for the <A> tag. Displayed in a browser, the words Text describing link would
appear underlined and in another colour (on a colour monitor) to indicate that clicking that text
initiates the hypertext link.
Notice that the anchor tag that creates the hyperlink is similar to the anchor tags that you have used
previously. The only difference is the pound sign (#) used at the beginning of the HREF text. This sign
tells the anchor that it is looking for a section within the current document, as opposed to within an
external HTML document.
The NAME attribute is used to create the actual section within the current HTML document. The text
that the NAME attribute contains is relatively unimportant, and it won't be highlighted or underlined in
any way when displayed by a browser. NAME is nothing more than an internal reference; without it,
though, the link won't work.
Note: Remember to use the pound sign (#) only for the actual hypertext link, not the NAME anchor.
Also, realize that the NAME text is case-sensitive and that the associated HREF text should use the
same case for all letters, as does the NAME. If the HREF calls for Section_ONE, and the NAME is actually
Section_One, the link will not work.
<BODY>
<H2>The Definition List</H2>
<P>Click one of the following words to move to its definition in the list:
<BR>
<A HREF="#EPITHET">epithet</A><BR>
<A HREF="#EPITOME">epitome</A><BR>
<A HREF="#EPOCH">epoch</A><BR>
<A HREF="#EPOXY">epoxy</A><BR>
<A HREF="#EQUAL">equal</A><BR>
</P>
<HR>
<DL>
<DT><A NAME="EPITHET"><B>ep i thet</B></A>
<DD><EM>noun.</EM> a descriptive, often contemptuous word or phrase
<DT><A NAME="EPITOME"><B>ep it o me</B></A>
<DD><EM>noun.</EM> someone who embodies a particular quality
<DT><A NAME="EPOCH"><B>ep och</B></A>
<DD><EM>noun.</EM> a division in time; a period in history or geology
<DT><A NAME="EPOXY"><B>ep ox y</B></A>
<DD><EM>noun.</EM> a synthetic, heat-sensitive resin used in adhesives
<DT><A NAME="EQUAL"><B>e qual</B></A>
<DD><EM>adj.</EM> having the same quality or status; having enough strength, courage, and so on.
<DD><EM>noun.</EM> a person or thing that is equal to another; a person
with similar rights or status
</DL>
</BODY>
In the example, clicking one of the words that appears as a hyperlink in the first section of the
paragraph moves the browser window down to that link's associated NAME anchor, so that the
definition becomes the focal point of the user's attention. Obviously, using section links would be of
greater use in a larger list. Consider the implications for turning an entire dictionary into HTML
documents.
Also notice that anchors can be placed within the confines other HTML tags, as in the first paragraph
container and in the definition lists of the example. In general, other HTML tags can act anchor tags on
Training & Development Division Page 66 of 282
HTML, DHTML & JavaScript
as though they were regular text. In the case of hyper linked text, the underlining and change in colour
in graphical browsers take precedence, but the hyper linked text also has any other qualities of the
surrounding text (for example, indenting with the rest of the definition text).
Notice which anchors cause the text to become a hyperlink and how the anchor tags respond within
other container tags.
Anchor tags are used to define and move between sections of an HTML document.
These absolute URLs can get rather tedious, not to mention the fact that if you happen to change the
name of your Web server or move your site to another basic URL, we'll probably have to edit every
page in your site to reflect the new URLs.
Note that the <BASE> tag is designed to appear only between the <HEAD> tags.
It may be helpful to think of <BASE> as doing something similar in function to a DOS path statement.
The <BASE> tag tells the browser that relative URLs within this particular Web document are based on
the URL defined in the <BASE> tag. The browser then assumes that relative URLs derive from the URL
given in the <BASE> tag and not necessarily from the current directory of the HTML document.
Consider a document named http://www.Dreamcorp.com/products/list.html that looks something like
this:
<HEAD>
<TITLE>Page One</TITLE>
</HEAD>
<BODY>
<A HREF="index.html">Back to Index</A>
</BODY>
In this example, the browser tries to find a document named index.html in the directory products,
because the browser assumes that all relative addresses are derived from the current directory. Using
the <BASE> tag, however, changes this example a bit, as follows:
<HEAD>
<BASE HREF="http://www.Dreamcorp.com/">
<TITLE>Page One</TITLE>
</HEAD>
<BODY>
<A HREF="index.html">Back to Index</A>
</BODY>
Now the browser looks for the file index.html in the main directory of this server, regardless of where
the current document is stored (such as in the products directory). The browser interprets the relative
URL in the anchor tag as though the complete URL were http://www.Dreamcorp.com/index.html.
Tip: If you plan to create a large Web site, you may want to add the <BASE> tag (complete with the
base URL) to your HTML template file.
Using the <BASE> tag to point to your Web site's main directory allows you to create the different types
of organization systems described in Chapter 5 by using relative URL statements to access HTML
documents in different subdirectories.
Note: Most browsers can accept hyperlinks only to anonymous FTP servers. We generally should not
include in our HTML documents links to FTP servers that require usernames and passwords.
Again, most browsers have some mechanism (sometimes built into the browser window) for reading
UseNet newsgroups. Some browsers launch a separate program to read UseNet groups. In either case,
you can create a link like the following:
<A HREF="news:news.answers">UseNet Help Newsgroup</A>
This link loads whatever UseNet reading features the browser employs and displays the specified
newsgroup (see fig. below). The news: URL type does not require a particular Internet server address
to function. Each browser should be set up with its own links to the user's news server.
For the most part, <LINK> is used to create an author-defined structure to other HTML documents on a
Web site. The attribute REL, for example, defines the relationship of the HREF URL to the current
document. Conversely, REV defines the relationship between the current document and the HREF'ed
URL.
In the HTML 3.0 standard, these definitions are relatively irrelevant-at least publicly on the Web. We
more commonly find these statements used within certain organizations (perhaps companies employing
an intranet), especially for advanced Web-based documentation efforts and for efforts that use HTML
and SGML together.
HTML 4.0 more than likely will introduce more widespread use of the <LINK> statement and other
<HEAD> tags for more tangible benefits.
We may want to use one <LINK> frequently: the REV="MADE" link, which tells users who created the
HTML page. Although this use of <LINK> doesn't actually call up a mailto: link in most browsers, some
may recognize it eventually. In the meantime, it gives people who view our source code the e-mail
address of the author, as in the following example:
<LINK HREF="mailto:tstauffer@aol.com" REV="MADE" REL="AUTHOR">
Review Questions
1. What tag tells where a link starts?
a. <a>
b. <lk>
c. <beginHere>
d. <refer>
5. To set the font for a single link, where do you add the <font></font> tags?
a. Outside the <a> and </a> tags
b. Anywhere in the <body> tag
c. Inside the <a> and </a> tags
Summary
A hyperlink allows us to navigate between different pages or within same
page. Anchor element ‘<A>’ can be used to create hypertext and
hypermedia links. Section links can be created within same document by
using ‘name’ attribute to the <A> tag. The ‘name’ text is case-sensitive
and that the associated HREF text should use the same case for all
letters.
Objectives
• Adding Image in web
• Use Imagemap for better interactivity
This chapter takes creating a graphical interface to our Web site one step further. With image maps,
we can create an entire interface for our Web pages and sites that rival the interfaces of popular
multimedia games, graphical operating environments, and interactive kiosks.
Image Maps Defined
The map part of image map conjures up two separate images. First, image maps on Web sites often act
like road maps for the Web site, adding interface elements that make it easier to get around on the
Web site. Second, the word map also suggests the way that image maps are created. Image maps begin
life as normal graphics (usually in GIF or JPEG format), designed with the Web in mind. Then another
program is used to map hot zones (clickable areas) on top of the graphics.
When put in place on a Web page, an image map allows users to access different HTML pages by
clicking different parts of the graphic. Because each hot zone has an associated URL, and because each
hot zone corresponds to part of the graphic, manoeuvrings about a Web site becomes more interesting,
graphical, and interactive.
Check out one more things. If the image map fills your screen, scroll down in your browser window so
that you can see what's below the interface on SPLICEM's Web page. The text directly below the
interface almost exactly mirrors the hyperlink options you have with the image map, because image
maps, unlike click able graphics, don't offer an ALT statement for the various hot zones. So you have to
include additional links to cater to your users of no graphical browsers.
When the shape is created, the Object URL dialog box appears (see below fig). Enter the URL that you
want to associate with your new hot zone. (You also can enter comments, if you want.) Then click OK
to continue.
Add more shapes by following steps 4 and 5 until you finish mapping your graphic.
Choose File, Save. Now you have a .MAP file for your image map.
Tip: By choosing File, Edit Default URL, you can determine whether your image map includes a default
URL for clicks outside your hot zones.
2. In this dialog box, enter testbar.map for the map file and testbar.gif for the graphics file. (If you
saved the GIF file in a different directory, use the Browse button to find and load it.)
3. When the graphic loads, pull down the Tools menu and make sure that Rect is selected.
4. Draw rectangles for the buttons, providing an appropriate URL for each button. For this example
(four buttons in all), use the following URLs:
http://www.Dreamcorp.com/index.html
http://www.Dreamcorp.com/product.html
http://www.Dreamcorp.com/service.html
http://www.Dreamcorp.com/help.html
5. Choose File, Edit Default URL. The Default URL dialog box appears.
We've created your map definition file. To look at the file, open Notepad (or a similar text editor), and
load the file testbar.map into it. The file should look something like figure below (although the
coordinates are bound to be slightly different).
• In the Open dialog box, select the graphic that you want to use for your map and the name of the
map definition file that you want to create.
• Click the OK button. After a moment, MapEdit displays your image file.
• To create a new hot zone, choose the shape from the floating tool palette, and drag to create a
hot zone. For a rectangle, circle, or oval, click and hold the mouse in the top left corner of your
shape, drag the mouse to make the shape the desired size, and then release the mouse button. To
create a polygon, choose the polygon shape from the tool palette and then click once on the
graphic for each point in your polygon. To complete the shape, click once on the first point you
created.
• When the shape is created, enter the URL in the space provided above the graphic file You can use
the pointer tool (the one that looks like a mouse pointer) to select different shapes that you've
created and then edit their URLs.
• To create a default URL, use the pointer tool to click the graphic background (not a shape). Default
URL should appear in the comment window. Then enter the default URL in the URL text box.
Note: It's perfectly acceptable to add other <IMG> tag attributes (such as ALT) to your image map
definition.
Using the ISMAP attribute doesn't do much for you unless the image map is also a hyperlink, so the
following code is everything that you need to add an image map to your Web page:
<A HREF="URL"><IMG SRC="graphic.ext" ISMAP></A>
Our next step is to figure out what to use as the URL in this hyperlink.
If the server requires you to access one of these scripting directories, though, it may not want you to
access the map definition file directly. Instead, the server will want you to use an alias.
Some servers store all map information in a single database file (often called imagemap.conf) and
require you to access information within the database by using an alias. You and your Web server
administrator have to determine what this alias is. In that case, your link would look more like the
following:
<A HREF="http://www.myserver.com/bin/mymap><IMG SRC="mymap.gif" ISMAP></A>
Example: Testing Your Link
The best way by far to participate in this example is to confer with your ISP, place your map definition
file on the Web server, and test it from a remote location using the correct URL. If that procedure
doesn't work, you can manage some testing on your own.
Save your template as a new HTML file, and have an image-mapped graphic handy in the same
directory. Then enter Listing between the <BODY> tags.
<BODY>
<A HREF="http://www.server.com/mymap.map>
<IMG SRC="mymap.gif" ISMAP ALT="My Image Map">
</A>
<H2>Welcome to my page!</H2>
</BODY>
Note: If you're going to test this example on an actual Web server, you need to replace the URL with
the appropriate one for your Web site (and add the type of link to your map info file that's required for
your server). Also, use the real name of the mapped GIF file in the <IMG> tag.
Save the HTML file and then load it in a graphical browser. If your graphic came up, chances are that
you set the <IMG> tag correctly. Notice that many browsers do not display a coloured link border
around the graphic, because the graphic is now considered to be an image map.
Before clicking any of the hot zones, move your mouse pointer around on the image map graphic. If you
have a status bar at the bottom of your browser window, you may notice that the link keeps changing
(see fig. below). Along with the URL of your map definition file, you should be seeing the current
coordinates of your pointer. All this information is sent to the map server to help it figure out what
region you clicked. (If you're testing this image map from your local drive, the status bar test is the
only part of the example that will work.)
An example image map, showing the URL and the coordinates that it will access if clicked
Now, if you are testing your image map on the Web server, go ahead and click the map to make sure
that all the links work. If you're viewing the image map locally, turn off the graphics-loading option in
your browser, and reload the page. You should notice that there's now no way to access the hyperlinks
in the image map-that's why you also need text links for your image map pages.
• Remember that image maps are usually little more than big graphics files. Ultimately, the
key to graphics on the Web is keeping them small. Even if your image map is incredibly
attractive, users will be annoyed if they have to wait many minutes for their four possible
choices to download to their browsers. Use all the tips in Chapter 9 to keep your graphic as
small as possible, and use image maps only to enhance usability.
• Image maps require redundant text links. Unless you plan to leave out everyone who can't
view your graphics, you need to create text links that do everything that your image map does.
Remember that with clickable graphics, the ALT attribute takes care of the problem. The ALT
attribute doesn't work for image maps, because a single image map graphic can have many
links, so you need to create an identical text link on your page for every hot zone link in your
image map.
• Stick to normal shapes whenever possible. You should try to be conservative with your image
maps (see fig. below). A graphic that looks as though it has rectangular buttons should function
as though it has rectangular buttons. In other words, make your hot zones correspond logically
to the image map graphics. Random hot zones randomly annoy users.
Some sites make it their business to use image maps that break the rules. This one doesn't
Review Questions
1. Defining clickable sub-areas on an image is called?
a. Multiple linking
b. Image Linking
c. Image mapping
d. subLinks
2. From the options below which are valid shapes for hotspots on images?
a. Polygon, rectangle and circle
b. Box, cube and line
c. Big and small
d. There is only one shape, oval
3. In the image where we are going to use Image-Map we have to use _____ attribute to specify
which map we are using.
a. usegraph
b. usemap
c. src
d. fileName
Summary
An image map allows us to access different HTML pages by clicking
different parts of the graphical image. To work with image map we have to
map the graphic for hot zones. Three shapes i.e. polygon, rectangle and
circle can be used to define the hot zones.
Objectives
• Explain Web form and it’s use
• Form Elements, it’s attributes
• Formatting of web form
The next set of HTML tags is designed to allow you to enhance the interactivity of Web pages by
increasing ability to request information from users. Using the forms tags, we can ask users to enter
text information, choose from menus, mark checkboxes, make choices from radio buttons, and then
send that information to the Web server for processing.
Tip: It's a good idea to let your users know that they're about to jump to a form-based page whenever
possible. Forms pages are a waste of time for users of older browsers that don't support them.
The idea behind a Web form is simple-it allows us to accept information or answers from our users with
varying levels of guidance. Users can be asked to type answers, choose their answers from a list of
possibilities you create, or even be limited to choosing one answer from a number of options that you
specify.
That data is then passed on to the Web server, which hands it to a script, or small program, designed
to act on the data and (in most cases) create an HTML page in response. In order to deal with forms
data then, you need to understand a little something about scripting, or programming, for a Web
server-or know someone who does.
Note: Most Web server scripts are written in Perl, C, or UNIX shell scripts. If your Web server is DOS,
Windows, or Mac based, however, you may have other options. Some DOS Web servers allow you to
script in the DOS batch language, while some Windows servers can accept Visual Basic scripts (not to be
confused with Microsoft's new Visual Basic Script language). Mac Web servers generally allow for
AppleScript or Frontier scripting.
Notice that the <FORM> tag takes two attributes: METHOD and ACTION. The METHOD attribute accepts
either POST or GET as its value. POST is by far the more popular, as it allows for a greater amount of
data to be sent. GET is a little easier for Web programmers to deal with, and is best used with single
responses, like a single textbox.
The second attribute is ACTION, which simply accepts the URL for the script that will process the data
from your form. Most often the script is stored in a directory called bin/ or cgi-bin/ located on your
Web server.
An example of the <FORM> tag then, would be the following:
As with any HTML container tag, this implementation of the <FORM> tag has actually created a
complete form (just like <P> and </P> is a complete paragraph). Unfortunately, our complete form
doesn't do anything yet, so that's somewhat academic.
Note I: You can't nest forms within one another. You need to add the end tag </FORM> for the first
form before creating another one in the same document. Generally, browsers will ignore any new
Training & Development Division Page 86 of 282
HTML, DHTML & JavaScript
occurrences of the <FORM> tag, since the purpose of the tag is to tell the browser how to submit data
to the server, and different parts of the form can't be submitted in different ways.
Note II: Nearly all-graphical browsers have a View Source command. Look in the Edit menu for this
command or a command with a similar name. The HTML source of the current Web document will then
be displayed or saved as a text file.
Notice a couple of things here. The <FORM> tag at lntinfotech is using the ACTION and METHOD
attributes that were discussed. ACTION is accessing a script called loginPage.html found in the cgi-bin/
directory of the Web server. The METHOD used is POST.
It may surprise you to find that <TEXTAREA> is a container tag, since it just puts a box for typing on the
page. What's contained in the tag is the default text-so you can guide your users by letting them know
what you'd like entered there. For instance:
<FORM>
<TEXTAREA NAME="comments" ROWS="4" COLS="40">
Enter comments about this Web site.
Good or Bad.
</TEXTAREA>
</FORM>
The default text appears in the textbox just as typed. Notice in figure below that text inside the
<TEXTAREA> tag works like <PRE> formatted text. Any returns or spaces you add to the text are
displayed in the browser window. In fact, notice that by hitting Return after the opening <TEXTAREA>
tag, I'm inserting a blank line at the top of the textarea (in many browsers).
The NAME attribute is a variable name for this string of text. It gets passed on to your processing script
on the Web server. ROWS and COLS can accept different numbers to change the size of the textarea
box, but you should take care that the majority of browsers can see the entire box on-screen. It's best
to limit COLS to 80 and ROWS to something like 24 (the typical size for a text-based computer screen).
But it's up to you.
<TEXTAREA> will also accept one other attribute: WRAP. WRAP can be set to OFF (which is the default
if WRAP is not included), VIRTUAL, or PHYSICAL. Setting wrap to PHYSICAL forces the browser to
include actual line breaks in the text when sending it to the Web server. VIRTUAL makes the textbox
seem to offer line wrap, but sends a continuous stream of words to the Web server (unless the user has
entered returns on his or her own).
<BODY>
<H3>Feedback Form</H3>
<P>Please take a moment to tell us what you thought of the Web site.<BR>
Your Feedback is appreciated!</P>
<FORM METHOD="POST" ACTION="cgi-bin/feedback">
Enter your comments below:<BR>
<TEXTAREA NAME="comments" ROWS="10" COLS="70" WRAP="VIRTUAL">
Dear BigCorp:
</TEXTAREA>
</FORM>
</BODY>
You can see how this looks in figure below. Notice in the example that some descriptive text is
enclosed inside the <FORM> tag, but outside of the <TEXTAREA> tag. This is completely legal-it just
lets you explain what the purpose of the textarea is.
You may have realized that there's something lacking in this sample form. There's no way to submit the
user's entry! You'll get to that in the next section, when I discuss this next tag for form entry.
Note: By the way, notice that <INPUT> is an empty tag. There's no </INPUT> element.
Text
The first possible value for the TYPE attribute is TEXT, which creates a single-line textbox of a length
you choose. Notice that the length of the box and the maximum length entered by the user can be set
separately. It's possible to have a box longer (or, more often, shorter) than the maximum number of
characters you allow to be entered. Here's an example of a textbox:
Last name:
<INPUT TYPE="TEXT" NAME="last_name" SIZE="40" MAXLENGTH="40">
When appropriately entered between <FORM> tags, this <INPUT> yields a box similar to figure below. If
desired, the attribute VALUE can be used to give the textbox a default entry, as in the following
example:
Type of Computer:
<INPUT TYPE="TEXT" NAME="computer" SIZE="50" MAXLENGTH="50" VALUE="Pentium">
PASSWORD
The PASSWORD option is nearly identical to the TEXT option except that it responds to typed letters
with bullet points or a similar scheme (chosen by the browser) to keep the words from being read. A
sample password box could be the following:
Enter Password:
<INPUT TYPE="PASSWORD" NAME="password" SIZE="25" MAXLENGTH="25">
When characters are typed into this textbox, they are shown on the screen as in figure below
PASSWORD hides text from people looking over your user's shoulder
Recognize that the text is still stored as the text typed by the user-not as bullet points or similar
characters.
CHECKBOX
This value for TYPE allows you to create a checkbox-style interface for your form. This is best used
when there are two possible values for a given choice-and no others. You can also determine whether
or not a checkbox will already be checked (so that it must be unchecked by the user, if desired), by
using the attribute CHECKED. Here's an example of adding checkboxes to a form:
Type of computer(s) you own: <BR>
In this example, it's possible to check as many of the options as are presented. CHECKBOX evaluates
each item separately from any others. Figure below illustrates how CHECKBOX is displayed in a
browser.
RADIO
Like CHECKBOX, RADIO is designed to offer your user a choice from pre-determined options. Unlike
CHECKBOX, however, RADIO is also designed to accept only one response from among its options.
RADIO uses the same attributes and basic format as CHECKBOX.
RADIO requires that you use the VALUE attribute, and that the NAME attribute be the same for all of
<INPUT> tags that are intended for the same group. VALUE, on the other hand, should be different for
each choice. For instance, look at the following example:
Choose the computer type you use most often: <BR>
With RADIO, it's important to assign a default value, since it's possible that the user will simply skip the
entry altogether. While the user can't check more than one, he or she can check none. So choose the
most common value and set it as CHECKED, just so that the form-processing script doesn't have
trouble.
Note: Of course, if you want to give your user the option of choosing none, then you can leave off the
CHECKED attribute. It's more complete and obvious for the user, however, to include another radio
button with a VALUE of none, and make it the CHECKED choice.
HIDDEN
This <INPUT> type technically isn't "input" at all. Rather, it's designed to pass some sort of value along
to the Web server and script. It's generally used to send a keyword, validation number, or some other
kind of string to the script so that the script knows it's being accessed by a valid (or just a particular)
Web page. The <INPUT TYPE="Hidden"> tag takes the attributes NAME and VALUE.
Note: This isn't really terribly covert (hidden), since an intrepid user could simply choose View Source
to see the value of the hidden field. It's more useful from a programmer's standpoint. For instance, on
a large Web site, the hidden value might tell a multi-purpose script which particular form (among
many) is sending the data, so the script knows how to process the data.
RESET
The <INPUT> tag has built into it the ability to clear an HTML form. RESET simply creates a push button
(named with the VALUE string) that resets all of the elements in that particular FORM to their default
values (erasing anything that the user has entered). An example would be the following:
<INPUT TYPE="RESET">
With a VALUE statement, you could enter the following:
<INPUT TYPE="RESET" VALUE="Reset the Form">
The results are shown in figure
SUBMIT
The <INPUT> tag also has a type that automatically submits the data that's been entered into the HTML
form. The SUBMIT type accepts only the attribute VALUE, which can be used to rename the button.
Otherwise, the only purpose of the Submit button is to send off all the other form information that's
been entered by your user. See the following two examples
<INPUT TYPE="SUBMIT">
<INPUT TYPE="SUBMIT" VALUE="SEND IT IN!">
You can use just about anything you want for the VALUE, although it's best to remember that really
small words, like OK, don't look great as buttons. To make a button larger, enter the VALUE with
spaces on either end, like in the following:
<INPUT TYPE="SUBMIT" VALUE=" GO ">
Example: A More Complete Form
Along with all the other <INPUT> types, now you've finally got a way to submit data. So, let's create a
more involved form that includes some of these examples-a subscription form.
Save your HTML template to create a new document. Then, enter something similar to Listing below.
Creating a Complete Form
<BODY>
<H2>Subscribe to CorpWorld</H2>
<P>Interested in receiving daily email updates of all the latest exploits of BigCorp? Well, now
you can. And, best of all, it's free! Just fill out this form and submit it by clicking the "Send it
In" button. We'll put you on our mailing list, and you'll receive your first email in 3-5 days.</P>
<FORM METHOD="Send" ACTION="http://www.Dreamcorp.com/cgi-bin/subscribe">
Please complete all of the following:<BR>
First Name: <INPUT TYPE="Text" Name="first" SIZE="25" MAXLENGTH="24"><BR>
Last Name: <INPUT TYPE="Text" Name="last" SIZE="35" MAXLENGTH="34"><BR>
Business: <INPUT TYPE="Text" Name="business" SIZE="50" MAXLENGTH="49"><BR>
We must have a correct email address to send you the newsletter:<BR>
Email: <INPUT TYPE="Text" Name="email" SIZE="50" MAXLENGTH="49"><BR>
How did you hear about BigCorp's email letter?<BR>
<INPUT TYPE="RADIO" NAME="hear" VALUE="web" CHECKED>Here on the Web
<INPUT TYPE="RADIO" NAME="hear" VALUE="mag">In a magazine
<INPUT TYPE="RADIO" NAME="hear" VALUE="paper">Newspaper story
<INPUT TYPE="RADIO" NAME="hear" VALUE="other">Other
<BR> Would you care to be on our regular mailing list?<BR>
<INPUT TYPE="CHECKBOX" NAME="snailmail" CHECKED> Yes, I love junk mail<BR>
<INPUT TYPE="RESET">
<INPUT TYPE="SUBMIT" VALUE="Send it in!">
</FORM>
</BODY>
Notice that, for text type <INPUT> boxes, the MAXLENGTH is one less than the size of the box. This
tends to look a little better, but choosing the size is up to you. Figure below shows how it looks on a
Web page.
You can also use the SIZE attribute to decide to display the menu in its entirety, by simply changing the
first line of the example to the following:
<SELECT NAME="food" SIZE="4">
Both examples are shown in figure below.
In the first example, selecting the menu item with the mouse causes the menu to pop-up on the page.
The user can then select from the choices. In the second example, it's necessary to click the desired
item.
What type of cars does your family own (select as many as apply)?
Review Questions
1. What is a field that allow the visitor to enter information called _____.
a. Meta tags
b. Form fields
c. Data field
d. Meta fields
Summary
Interactivity of Web pages can be increased by using ability to request
information from users. With the help of ‘FORM’ tag, we can ask users to
enter text information, choose options from menus, mark checkboxes, and
make choices from radio buttons and to send the information to the Web
Server for processing. Form controls are set between the <FORM> container
tags. <FORM> tag takes two attributes: METHOD and ACTION which will tell
to Server how to send the data and which page to be displayed after
submitting the data. We can't nest forms within one another. By using Input
Tag we can design various types of input controls like textbox, password
field, text area, buttons, hidden field etc.
Objectives
• Explain relationship of HTML and multimedia
• To include multimedia object in web page
Already, there are a couple of things you're required to know. You need to know the filename of the
multimedia file or the appropriate URL if it's not in the current directory. You also need to know the
MIME-style "type" of the data file.
MIME-style data types for newer multimedia formats (especially vendor-specific ones like Macromedia
Director) will generally be in the form of application/x-data type. More often than not, these are the
types you'll use for the <INSERT> tag, since these are the data types used for browser plug-ins.
<INSERT>'s Attributes
Aside from DATA and TYPE, <INSERT> can also accept the attributes ALIGN, WIDTH, HEIGHT, and
BORDER. Its format is as follows:
<INSERT ALIGN="direction">
ALIGN works much as it does with <IMG>. The values possible for ALIGN are shown in Table below.
Notice that some of these values (LEFT, CENTER, MIDDLE) cause <INSERT> to act as a separate object,
while the others assume the inserted multimedia object is supposed to be inline with the text of the
document. You may recall that this is almost identical to what you learned about <IMG> at the
beginning of this chapter.
WIDTH and HEIGHT accept numbers and unit suffixes (like px for pixels and in for inches). These two
attributes are used to define the size of the object for faster downloading. Some browsers will also
resize objects according to these attributes, so that you might expand a smaller inline movie's object
with WIDTH and HEIGHT, for instance, to save on downloading time. WIDTH and HEIGHT take the
following format:
The last parameter is BORDER, which has a default value of 1. The border will generally only appear
when the entire <INSERT> object in enclosed in an anchor tag, as in the following example:
The <PARAM> tag is used to offer additional parameters to the <INSERT> tag information like how many
times to play a movie clip. The <PARAM> tag takes elements NAME and VALUE, which work a little like
they do for certain table tags. Unfortunately, each different type of multimedia file will require
different NAME and VALUE values, so you'll have to seek those out from the creator of the particular
object type you want to send.
The <IMG> tag is used within an <INSERT> definition in the same way that it is used elsewhere, except
that the ALIGN attribute isn't really necessary since the <IMG> will only be used to directly replace the
inserted multimedia object. You can add the <IMG> like this:
Clearly, you'll often want the graphic to at least represent the multimedia file that can't be displayed
(see fig. below). Or, perhaps, you could cause a graphic to load that tells the user that he or she is
missing out on something better.
Review Questions
1. The background image will scroll when the user scrolls down the page, unless you add which
property to the <body> tag?
a. bgproperties="fixed"
b. bgproperties="stationary"
c. bgproperties="holdstill"
d. background-image=”stable”
2. Why should you specify a background color if you are using an image for the actual background
of your page?
a. The background color will be shown until the image loads
b. In case the image doesnt fit right
c. So the text shows up better
Summary
Various multimedia objects can be inserted to add interactivity and to give
better look to web pages. <INSERT> tag can be used to add multimedia
object to a web page. The <PARAM> tag is used to offer additional
parameters to the <INSERT> tag information.
Objectives
• Understanding how to create tables
• Using Captions, Table Headers and Table Data tags
• To know alignments of tables
Creating a Table
Tables work a lot like HTML list tags; in that you must use the table container tag to hold together a
group of tags that define each individual row. The main container is the <TABLE> tag, which uses
enclosing tags for table rows (<TR>) and table data (<TD>). Most tables will also use an element for
table headers (<TH>), which is generally used as the title text for rows and columns.
Tables take the following format:
<TABLE>
<CAPTION>Caption text for table</CAPTION>
<TR><TH>column1</TH><TH>column2</TH><TH>column3</TH>
<TR><TD>row1data1</TD><TD>row1data2</TD><TD>row1data3</TD>
<TR><TD>row2data1</TD><TD>row2data2</TD><TD>row2data3</TD>
...
</TABLE>
An example of a table using this format might be the following:
<TABLE>
<CAPTION>Team Members for 3-Person Basketball</CAPTION>
<TR><TH>Blue Team</TH><TH>Red Team</TH><TH>Green Team</TH>
<TR><TD>Mike R.</TD><TD>Leslie M.</TD><TD>Rick G.</TD>
<TR><TD>Julie M.</TD><TD>Walter R.</TD><TD>Dale W.</TD>
<TR><TD>Bill H.</TD><TD>Jenny Q.</TD><TD>Fred B.</TD>
</TABLE>
After you work with HTML list containers, it's fairly easy to make the jump to creating tables in HTML.
You can see how this table looks in figure below.
• WIDTH. The WIDTH attribute sets the relative or absolute width of your table in the browser
window. Values can be either percentages, as in WIDTH="50%", or absolute values. With
absolute values, you must also include a suffix that defines the units used, as in px for pixels or
in for inches (e.g., WIDTH="3.5in"). Absolute values for table widths are discouraged, though.
• COLS. The COLS attribute specifies the number of columns in your table, allowing the browser
to draw the table as it downloads.
• BORDER. The BORDER attribute defines the width of the border surrounding the table. Default
value is 1 (pixel).
• CELLSPACING. The CELLSPACING attribute tells the browser how much space to include
between the walls of the table and between individual cells. (Value is a number in pixels.)
• CELLPADDING. The CELLPADDING attribute tells the browser how much space to give data
elements away from the walls of the cell. (Value is a number in pixels.)
It is definitely not necessary to use all of these attributes for your table-in fact, the simple table
example earlier didn't use any of them. Often, however, they will come in handy.
Example: Playing with Table Attributes
This is another fairly freeform example. Let's look at the difference between a plain table and a table
embellished with a few attributes. Insert Listing below in a new HTML document.
<BODY>
<H2> BigCorp's Computer Systems </H2>
<P>We use only the highest quality components and software for all of our
Wintel computer systems. Plus, if you don't see a configuration you like,
call (or email) and let us know. We'll custom build to please! </P>
<TABLE>
<CAPTION>BigCorp's Computer Systems and Specifications</CAPTION>
<TR><TH>System 486</TH><TH>System 586</TH><TH>System 686</TH>
<TR><TD>486DX2-66 CPU</TD><TD>120 MHZ AMD586</TD><TD>200 Mhz Pentium Pro</TD>
<TR><TD>8 MB RAM</TD><TD>16 MB RAM</TD><TD>16 MB RAM</TD>
<TR><TD>500 MB HD</TD><TD>1 GB HD</TD><TD>1.4 GB HD</TD>
<TR><TD>14.4 Modem</TD><TD>28.8 Modem</TD><TD>28.8 Modem</TD>
<TR><TD>desktop case</TD><TD>minitower case</TD><TD>tower case</TD>
<TR><TD>DOS/Win 3.1</TD><TD>Windows 95</TD><TD>Windows NT 4.0</TD>
</TABLE>
</BODY>
Last time we tried a simple table, it communicated its data well. But this one is fairly ineffective, with
everything lined up so poorly. Using just the attributes only mentioned, though, you can change this
table so that it looks better to the user and is easier to read.
All that needs to change is the first <TABLE> tag:
<TABLE BORDER ALIGN="LEFT" CELLSPACING="3" CELLPADDING="3">
That makes for a much nicer looking table, complete with borders and lines for cells, and a
comfortable amount of spacing to separate cell data elements from one another (see figure below).
Look how nice the table looks with spacing and borders
The rest of this example is up to you. Play with CELLSPACING and CELLPADDING without a border, for
instance, or increase all values out of proportion. See the range of what's available, to help you choose
how to format your tables in the future.
Just about any sort of markup tags are possible inside the <CAPTION> tags, although some-like list tags-
wouldn't make much sense.
The <CAPTION> tag has one attribute, ALIGN. ALIGN="TOP" and ALIGN="BOTTOM" are encouraged. By
default, text is also aligned to center (horizontally). By TOP and BOTTOM, I'm referring to the entire
table; the caption will default to the top of the table if not otherwise specified. To align the caption to
BOTTOM, for instance, enter the following:
The <CAPTION> tag is commonly the first tag just inside the <TABLE> tag (although this placement is
not required). Regardless of where you place the <CAPTION> tag, however, you must use ALIGN to
force it to the bottom of the table. Otherwise, it will appear at the top, according to its default.
Let's create an entire table and use the ALIGN attribute to the <CAPTION> tag to force the caption to
the bottom, like this:
<BODY>
<H3>Favourite Ice Cream Flavours</H2>
<TABLE BORDER>
<CAPTION ALIGN="BOTTOM">Data from the <I>New Jersey Times</I></CAPTION>
<TR><TH>Date</TH><TH>Chocolate</TH><TH>Vanilla</TH>
<TR><TH>1970</TH><TD>50%</TD><TD>50%</TD>
<TR><TH>1980</TH><TD>76%</TD><TD>24%</TD>
<TR><TH>1990</TH><TD>40%</TD><TD>60%</TD>
</TABLE>
</BODY>
When the browser interprets this table, it should place the caption at the bottom of the table,
centered horizontally (see fig. below).
Table Rows
Table rows (<TR>) can accept one attribute you should concern yourself with-ALIGN. The ALIGN
attribute is used to determine how text will appear (horizontally) in each of the rows data cells. For
instance:
<TR ALIGN="CENTER"><TH>Date</TH><TH>Chocolate</TH><TH>Vanilla</TH>
<TR ALIGN="CENTER"><TH>1970</TH><TD>50%</TD><TD>50%</TD>
<TR ALIGN="CENTER"><TH>1980</TH><TD>76%</TD><TD>24%</TD>
<TR ALIGN="CENTER"><TH>1990</TH><TD>40%</TD><TD>60%</TD>
Here, I've added the ALIGN attribute (with a value of CENTER) to the rows in the previous example.
Notice now that all cells center data horizontally (see fig. below). This ALIGN attribute can also accept
LEFT and RIGHT.
Note: HTML 4.0 also supports another useful attribute, VALIGN, which accepts the values TOP,
BOTTOM, and CENTER. Using this attribute, you can choose to align cells vertically as well as
horizontally. Until they support VALIGN, non-HTML 4.0 browsers should ignore VALIGN. Unfortunately,
those are currently the most popular browsers!
<TABLE BORDER=2>
<TR><TH>Student</TH><TH>Test 1</TH><TH>Test 2</TH><TH>Average</TH>
<TR><TH>Mike M. </TH><TD>100</TD><TD>75</TD><TD ROWSPAN="3">N/A</TD>
<TR><TH>Susan T.</TH><TD>80</TD><TD>95</TD>
<TR><TH>Bill Y.</TH><TD COLSPAN="2">Dropped Course</TD>
</TABLE>
Review Questions
1. To add rows to your tables use which tags?
a. <td> and </td>
b. <tr> and </tr>
c. <cr> and </cr>
d. <trow> and </trow>
Summary
Tables help us to align contents and to keep data in tabular format.
<TABLE> tag is used to create table structure on web pages. Attributes like
border, cellspacing, cellpadding can be used to add impact of tables.
<TR> tag is used to define table rows and <TD> is used to define data in
table cells. Incase if we require to merge two or more cell or columns then
we can use either rowspan or colspan attributes inside <TH> or <TD> tags.
Objectives
• Apply frames for formatting
• Explain attributes of frames
• Discuss use of Noframe in HTML
• To Target frame window
One of the most exciting Netscape-only additions to HTML recently has been the frames specification.
Although submitted to the W3C, frames, for now, remain almost exclusively Netscape-only.
Frames aren't overwhelmingly difficult to add to your pages, although they do require a slight shift in
thought. Although they seem similar to tables at first, frames are considerably more powerful. In fact,
that frames can even divide your Web page so that it is accessing more than one URL at a time.
Using frames in this way takes you one step closer to the ideal Web interface, because it makes it as
intuitive and universal as possible.
• Fixed interface elements. As mentioned previously, you can force click able graphics, logos,
and other information to stay in one fixed portion of the screen, while the rest of your
document scrolls in another frame.
• Better forms and results. Frames also enable you to create a form in one frame and offer
results in another frame. This is something we're beginning to see extensively with Web search
pages (refer to fig. below). With the search text box always available, you're free to change
search phrases or pinpoint your search more quickly, without moving back in the hierarchy of
the Web pages.
Creating Frames
Probably most unique among the HTML-style tags so far is the <FRAMESET> tag. This container is
required for frames-style pages-but it also replaces the <BODY> tag completely on these pages. When
you use frames then, you're committed to using them completely-you can't just add frames to part of
your page. On a typical page, <FRAMESET> is added like this:
<HTML>
<HEAD>
...HEAD markup...
</HEAD>
<FRAMESET>
...Frames and other HTML markup...
</FRAMESET>
</HTML>
The <FRAMESET> tag can accept two attributes: ROWS and COLS. Both attributes accept numerical
values (size in pixels), percentages, or a combination of both. The value * can also be used to suggest
that a particular row or column should take up the rest of the page. The number of values suggests the
number of rows or columns you give the attribute. These attributes take the following format:
<FRAMESET ROWS="numbers,percentages,*" COLS="numbers,percentages, *">
An example like the following would create two rows: one 50 pixels long and another row that took up
the rest of the page:
<FRAMESET ROWS="50,*">
(This would be useful for a page that displays a fixed map or graphic at the top.) The following
example would create a Web interface with two columns: one on the leftmost 25 percent of the screen
and one on the other 75 percent:
<FRAMESET COLS="25%,75%">
This would be a good way to set up a documentation (or FAQ) site that offered contents in the first
frame and actual text and examples in the second, larger frame.
Each <FRAMESET> statement will work with one attribute or the other. That means you can only create
a frameset with either rows or columns. In order to create rows within columns (or vice-versa), you can
nest <FRAMESET> statements. For instance, the following will create a page with two columns:
<FRAMESET COLS="25%,75%">
<FRAMESET ROWS="50%,50%">
</FRAMESET>
<FRAMESET ROWS="10%,90%">
</FRAMESET>
</FRAMESET>
The first column will be divided into two rows that take up 50 percent of that column a piece. The
second column will be divided into two rows, the first taking ten percent and the second taking the
rest of that column. Although this doesn't display anything in and of itself, it creates logical breaks in
the page that look like figure below. You'll come back to nesting <FRAMESET> tags as you develop more
advanced frame interfaces in this chapter.
<FRAMESET COLS/ROWS="numbers">
<FRAME SRC="URL">
...
</FRAMESET>
The SRC attribute is used to tell the frame what URL should be loaded in that frame. For instance, the
following would create two frame rows-one that loaded the URL index.html at the top of the Web page
and one that loaded the URL help.html at the bottom of the page (see fig. below):
By using the <FRAME> tag, you create what's known as a frame window. Each window corresponds to a
"row" or "column" definition in the <FRAMESET> tag, but nothing is drawn or displayed until an
appropriate <FRAME> tag is used to define each individual window.
Example: A Simple Frame Document
You'll essentially create the same document that was shown in the previous figure, but you should feel
free to play with the numbers a bit to see how different percentages and even different attributes to
<FRAMESET> changes how the page displays. Enter Listing as shown below in your text editor.
While you're at it, you also need to create some files to put in those frames. If you have some HTML
documents hanging around, you can rename menu.html and help.html to any HTML file you'd like to
load. For this example, any HTML document names will work (see fig. below).
If you'd like to experiment further, try changing the <FRAMESET> tag in Listing 20.1 to the following:
<FRAMESET COLS="25%,75%">
Or, change the percentages to see how that affects your layout.
This creates a five-pixel border between the contents of text.html and the frame edges.
SCROLLING can accept the values yes, no, and auto and is used to determine whether or not scroll bars
will appear in the frame window. The default value is auto, and this is probably the best to use in most
cases. Since users have all different screen resolutions and available browser window space, even short
documents will sometimes need to be scrolled.
The NORESIZE attribute doesn't require a value assignment, and is used to keep the user from resizing a
frame window. (Frame windows can be resized by dragging the frame with the mouse in the viewer
window.)
<FRAMESET ROWS="25%,75%">
<FRAME SRC="menu.html">
<FRAME SRC="index.html">
<NOFRAMES>
<P>This page requires a Frames capable browser to view. If you'd prefer,
you can access our <a href="2_index.html">HTML 3.0 compliant pages</a>
to view this information without the frames interface.</P>
</NOFRAMES>
</FRAMESET>
Experiment with different values for the <FRAME> attributes and see what makes a big difference in
terms of margins, scrolling, and resizing. Also, if you have access to a browser that isn't frames-
capable, load the page and see how the <NOFRAMES> markup looks (see fig. below).
Although you can pretty much name your frame window anything you want, there is one restriction:
you can't start the name with an underscore character (_). If you do, the name will be ignored. But,
there's a good reason for that.
The underscore is used to signal a number of "magic" target names. You'll get to those after you learn
how to target regular browser windows.
Targeting Frame Windows
With your frame successfully named, you're ready to target the name with a hypertext link. This is
accomplished with the TARGET attribute to a typical <A> anchor tag. It follows this format:
<A HREF="new_URL" TARGET="window_name">link text</A>
The new_URL is the new document that you want to appear in the frame window. The window_name is
the same name that you used to name the frame windows with the NAME attribute to the <FRAME> tag.
An example would be the following:
<A HREF="products.html" TARGET="main_viewer">View Products</A>
Advanced Targeting
Other link-related tags have been updated to accept a TARGET attribute along with the anchor tag. For
instance, client-side image maps have their AREA tag updated to accept a target window, so that an
area defined to access a certain link loads that page into the target. This is the format:
<AREA SHAPE="shape" COORDS="numbers" HREF="URL" TARGET="window_name">
Likewise, you can add a TARGET attribute to the <FORM> tag. Remember that it's the <FORM>
container tag that tells the browser the URL for the script that is required to process the form data. In
that same tag, you can also specify a target window for the results that are received from the server. If
you want users to be able to use your form repeatedly (to allow them to generate different results),
you can leave both the form and the results in separate frames. This attribute takes the following
format:
<FORM ACTION="Script_URL" TARGET="window_name">
<BASE> Targets
The last example you went through (Listing 20.4) would have been a great candidate for this one type
of target. What if you want the majority of your links to point to a particular frame window? In the
early example, you created a file called control2.html that had nothing but hypertext links. Each one
of those links required a TARGET attribute that pointed to the big_window. You could have made that
easier with a <BASE> tag in the head of your document. Use this format:
<HEAD>
<BASE TARGET="window_name">
</HEAD>
A good example of this for the previous example would be:
<BASE TARGET="big_window">
You don't have to specify the target window in each individual anchor in an HTML document that has
this tag in its head. Now all links will default to the target defined in the <BASE> tag.
Note: If you do use TARGET attributes, they will override the <BASE> tag for that particular link.
"Magic" Targets
Here's why you can't name frame windows with something that starts with an underscore. The "magic"
target names all start with an underscore, which signals to the browser that they should treat this link
extra special. The following are some examples:
• TARGET="_blank"-The URL specified in this link will always be loaded in a new blank browser
window.
• TARGET="_self"-This is used for overriding a <BASE> tag, and forcing a link to load in the same
window that it's clicked in.
• TARGET="_top"-The document is loaded in the topmost frame of the current browser window.
Basically, these magic targets are designed to let you break out of the current <FRAMESET> structure in
some way. Experiment with them to see how you can move around to different windows.
<HTML>
<HEAD>
<TITLE>Control Map</TITLE>
<BASE TARGET="toc_window">
</HEAD>
<BODY>
<DIV ALIGN="CENTER">
<IMG SRC="control.gif" USEMAP="#control">
</DIV>
<MAP NAME="control">
<AREA SHAPE="rect" COORDS="0,0,61,22" HREF="index_toc.html">
<AREA SHAPE="rect" COORDS="62,0,146,22" HREF="prod_toc.html">
<AREA SHAPE="rect" COORDS="146,0,222,22" HREF="serv_toc.html">
<AREA SHAPE="rect" COORDS="222,0,296,22" HREF="supp_toc.html">
<AREA SHAPE="rect" COORDS="296,0,359,23" HREF="about_toc.html">
</MAP>
</BODY>
</HTML>
Notice that this graphic isn't designed to change the main window. It's going to change the documents
that show up in your table of contents window. Each of the TOC documents should be a simple HTML
list of links that shows the branch that the users have travelled down. For instance, let's create the
document serv_toc.html (see Listing below).
serv_toc.html - A Sample TOC Document
<HTML>
<HEAD>
<TITLE>Service Contents</TITLE>
<BASE TARGET="main_window">
</HEAD>
<BODY>
<UL>
<LI><A HREF="products.html">Main Products Page</A>
<UL>
<LI><A HREF="software.html">Software</A>
<LI><A HREF="hardware.html">Hardware</A>
<LI><A HREF="furniture.html">Furniture</A>
<LI><A HREF="access.html">Accessories</A>
</UL>
</UL>
</BODY>
</HTML>
See what we are getting here? The image map will change these controls, and then these links will
change the main frame window. It gives a nice, easy interface to the whole site. Now let's create the
frames page which we'll call main.html (see Listing below).
The Main Frames Interface
<HTML>
<HEAD>
<TITLE>BigCorp on the Web</TITLE>
</HEAD>
<FRAMESET ROWS="15%,85%">
<FRAME SRC="controls.html" SCROLLING="no" NORESIZE>
<FRAMESET COLS="30%,70%">
<FRAME SRC="index_toc.html" NAME="toc_window" MARGINWIDTH="3"
MARGINHEIGHT="3">
<FRAME SRC="index.html" NAME="main_window" MARGINWIDTH="3"
MARGINHEIGHT="3">
</FRAMESET>
</FRAMESET>
</HTML>
This one doesn't take up much space. Here's what you've done. The first <FRAMESET> created two rows-
one for image map and one for the rest of the page. In that bottom row, you used another <FRAMESET>
to create two columns within that row. The smaller is for the table of contents pages. In the other
frame window, you put all of the main HTML documents. Look at figure below to see how the whole
thing looks in Netscape.
Note: For this example to work well, you may need to create some other files like index_toc.html, or
rename files to work in your main window.
Review Questions
1. A file that specifies how the screen is divided into frames is called a __________ .
a. frametable
b. tablelink
c. frameset
d. <framedesign>
2. You can add names to each frame window using which setting?
a. name
b. src
c. ur
3. If you don’t want the frame windows to be resizable, simply add what to the <frame> lines?
a. save
b. dontresize
c. noresize
d. notsizable
Summary
Frames are basically another way we can create a unique interface for our Web
site. Frames can be used for applications like Table of Contents (TOC), Fixed
Interface elements and to make ‘Form’ look more attractive and for good form
look. <FRAMESET> tag can be used to create frames. Rows and cols attributes are
used to define layout of frameset. To add webpage to frameset <FRAME> tag is
used with ‘src’ as source file name. <NOFRAMES> tag is used to contain HTML mark-
up intended for browsers that do not support the frames specification. By naming
frames we can open resultant link inside particular frame window.
Objectives
• Introduction to DHTML
• Understanding the history of DHTML
• Enhancing User Experience
• To understand components of DHTML
Introduction
DHTML is the combination of several built-in browser features in fourth generation browsers that
enable a web page to be more dynamic.
DHTML is NOT a scripting language (like JavaScript), but merely a browser feature- or enhancement-
that gives your browser the ability to be dynamic. DHTML is a collection of features that together,
enable your web page to be dynamic. I think its important now to define just what the creators of
DHTML meant when they say "dynamic". "Dynamic" is defined as the ability of the browser to alter a
web page's look and style after the document has loaded.
Web designers are often limited by default fonts such as Helvetica, Arial and Times Roman. DHTML
allows downloadable fonts. Readers will be able to see web pages the way they are designed, with text
that responds to exact font, size and style.
DHTML is a new tool for designers to create Web pages with special effects and animation such as
flying headlines and news tickers. Designers can attach a simple script to any object on a page and the
user can change the appearance of a Web page "on the fly." Prior to DHTML, designers were limited to
writing complicated programs to achieve the same effects.
History of DHTML
During 1960’s, IBM scientists were working on a Generalized Markup Language (GML) for describing
documents and their formatting. In 1986, the International Standards Organization (ISO) adopted a
version of this standard called Standard Generalized Markup Language (SGML). SGML offers a highly
sophisticated system for marking up documents so that their appearance is independent of specific
software applications. It is big, powerful, filled with options, and well suited for large organizations
that need exacting document standards. As Internet began to grow, data increase rapidly.
Unfortunately, SGML made the language unsuitable for quick easy Web publishing (Randall, 319). The
straightforward text was too dull for the mass-market of the Internet. Data needs to be displayed in an
interesting structure and so HTML (HyperText Markup Language) was created. HTML is a subset of
SGML. SGML means Standard Generalized Mark-Up Language. A Mark-Up Language alters the
presentation of the content of a document. HTML presents data in a browser window in a multitude of
shapes, sizes, colors, and provides extra features, such as forms and hyperlinks (Perry). HTML is a good
tool for publishing small file size documents over the Internet. However, HTML in its traditional form is
not powerful enough to create the interactive and multitude-rich documents that today’s commercial
web sites demand.
HTML’s limitation is the control over page layout. Web authors do not have the ability to lay out pages
with the pixel-level accuracy available to the traditional desktop publishing author. In addition, a
standard HTML document cannot specify that text and images are located at exact coordinates, on top
of each other, or even that the text be displayed in a particular point size (Heinle). Most computer
programming languages have more functionality than HTML.
The programming language is called JavaScript and it has powerful range of command. In order to
combine these two programming languages together to be more powerful, Dynamic HTML emerged
Enhanced User Experience
DHTML makes the Web experience faster and more interactive for end users. Live updates can be
activated by user and browser-driven events. For example, text and images can be hidden in a
document until a user moves the mouse over an element or clicks a button. A browser-driven event can
be triggered by internal actions, such as when the browser finishes downloading the Web page.
DHTML uses Cascading Style Sheets which provides absolute positioning of every object on a page. Web
designers can have precise 3-D control over x, y, and z coordinates. That means text and graphics can
overlay each other, creating more visual effects.
Data binding is a technique that ties elements in a Web page to a data source. It allows the creation of
a Web page that displays up-to-the-minute data extracted from a database. When the page is loaded,
the current information from the data source can be read and inserted in a table. The data can be
dynamically updated or sorted through a script without redrawing the page or having to go back to the
server. Data binding is supported by IE4 but not by NN4.
In a client-server environment, DHTML lets the client/browser make changes after a web page has been
downloaded, without the burden of relying on server-side programs or complicated sets of HTML pages
to achieve special effects. In other words, the client does not need to reload the document or load a
new document, or require a remote server to generate new content. That means a user does not have
to wait for text and data to complete time and bandwidth consuming round-trips to and from a server
before seeing results.
Components of DHTML
DHTML requires four independent components to work: HTML, Cascading Style Sheets, Scripting and the
Document Object Model. The section provides a brief description of each component.
HTML: HTML defines the structure of a Web page, using such basic elements as headings, forms,
tables, paragraphs and links. On December 18, 1997, HTML 4.0 attained "recommended" status at the
W3C. Changes and enhancements introduced in HTML 4.0 made DHTML possible.
Cascading Style Sheets (CSS): Similar to a template in a word-processing document, a style sheet
controls the formatting of HTML elements. Like in traditional desktop publishing, one can use style
sheet to specify page margins, point sizes and leading. Cascading Style Sheets is a method to determine
precedence and to resolve conflicts when multiple styles are used.
Scripting: Scripting provides the mechanisms to interpret user actions and produce client-side changes
to a page. For example, scripts can interpret mouse actions (such as the mouse passing over a specified
area of a page through the event model) and respond to the action by using a set of predefined
instructions (such as highlighting the text activated by the mouse action). Although DHTML can
communicate with several scripting languages, JavaScript is the de facto standard for creating cross-
browser DHTML pages.
Document Object Model (DOM): The DOM outlines Web page content in a way that makes it possible
for HTML elements, style sheets and scripting languages to interact with each other. The W3C defines
the DOM as "a platform- and language-neutral interface that will allow programs and scripts to
dynamically access and update the content, structure, and style of documents. The document can be
further processed and the results of that processing can be incorporated back into the presented
stage."
Review Questions
1. DHTML is extension of _______ language.
a. HTML
b. SGML
c. JScript
d. XML
3. State True or False. Using DHTML, we can do client side form Validation.
a. True
b. False
Summary
Dynamic HTML is an extension of HTML. It contains a number of new tags
that lets you define a user interface in terms of HTML elements and lets
users interact with that interface. DHTML consists of a number of related
technologies like HTML who defines the structure of the information being
conveyed to the user, Cascading Style Sheets (CSS) determines the
appearance of that information as it is being rendered, and the Document
Object Model (DOM). Scripting languages such as VBScript and JavaScript
interact with the HTML elements in the document. Netscape and Microsoft
have pledged future support for a standard that is currently being decided
by the World Wide Web Consortium (W3C).
Objectives
• Understanding basics of CSS
• To know the benefits of using CSS
• To explore syntax of CSS
• Understanding various types of CSS
• Learning various selectors in CSS like font, background
Cascading Style Sheets (CSS) is a fantastic tool to add layout to your websites. It can
save you a lot of time and it enables you to design websites in a completely new way.
CSS is a must for anyone working with web design.
This tutorial will get you started with CSS in just a few hours. It is easy to understand
and it will teach you all the sophisticated techniques.
Learning CSS is fun. As you go along through the tutorial, remember to take enough
time to properly experiment with what you learn in each lesson.
For example, Microsoft Windows comes with a program called Notepad. It is usually located in
Accessories in the start menu under Programs. Alternatively, you can use a similar text editor e.g. Pico
for Linux or Simple Text for Macintosh.
A simple text editor is ideal for learning HTML and CSS because it doesn't affect or change the codes
you type. That way, your successes and errors can only be attributed to yourself - not the software.
You can use any browser for this session. We encourage you to always keep your browser updated and
use the latest version.
HTML can be (mis-)used to add layout to websites. But CSS offers more options and is more accurate
and sophisticated. CSS is supported by all browsers today.
After only a few lessons of this tutorial, you will be able to make your own style sheets using CSS to
give your website a new great look.
What is the difference between CSS and HTML?
HTML is used to structure content. CSS is used for formatting structured content.
Okay, it sounds a bit technical and confusing. But please continue reading. It will all make sense to you
soon.
Back in the good old days a guy called Tim Berners Lee invented the World Wide Web, the language
HTML was only used to add structure to text. An author could mark his text by stating "this is a
headline" or "this is a paragraph" using HTML tags such as <h1> and <p>.
Training & Development Division Page 128 of 282
HTML, DHTML & JavaScript
As the Web gained popularity, designers started looking for possibilities to add layout to online
documents. To meet this demand, the browser producers (at that time Netscape and Microsoft)
invented new HTML tags such as for example <font> which differed from the original HTML tags by
defining layout - and not structure.
This also led to a situation where original structure tags such as <table> were increasingly being
misused to layout pages instead of adding structure to text. Many new layout tags such as <blink> were
only supported by one type of browser. "You need browser X to view this page" became a common
disclaimer on web sites.
CSS was invented to remedy this situation by providing web designers with sophisticated layout
opportunities supported by all browsers. At the same time, separation of the presentation style of
documents from the content of documents makes site maintenance a lot easier.
Which benefits will CSS give you?
CSS was a revolution in the world of web design. The concrete benefits of CSS include:
Many of the properties used in Cascading Style Sheets (CSS) are similar to those of HTML. Thus, if you
are used to use HTML for layout, you will most likely recognize many of the codes. Let us look at a
concrete example.
The basic CSS syntax
Let's say we want a nice red color as the background of a webpage:
<body bgcolor="#FF0000">
As you will note, the codes are more or less identical for HTML and CSS. The above example also shows
you the fundamental CSS model:
But where do you put the CSS code? This is exactly what we will go over now.
An external style sheet is simply a text file with the extension .css. Like any other file, you can place
the style sheet on your web server or hard disk.
For example, let's say that your style sheet is named style.css and is located in a folder named style.
The situation can be illustrated like this:
The trick is to create a link from the HTML document (default.htm) to the style sheet (style.css). Such
link can be created with one line of HTML code:
<link rel="stylesheet" type="text/css" href="style/style.css" />
Notice how the path to our style sheet is indicated using the attribute href.
The line of code must be inserted in the header section of the HTML code i.e. between the <head> and
</head> tags. Like this:
<html>
<head>
<title>My document</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
...
This link tells the browser that it should use the layout from the CSS file when displaying the HTML file.
The really smart thing is that several HTML documents can be linked to the same style sheet. In other
words, one CSS file can be used to control the layout of many HTML documents.
This technique can save you a lot of work. If you, for example, would like to change the background
color of a website with 100 pages, a style sheet can save you from having to manually change all 100
HTML documents. Using CSS, the change can be made in a few seconds just by changing one code in the
central style sheet.
Try it yourself
Open Notepad (or whatever text editor you use) and create two files - an HTML file and a CSS file -
with the following contents:
default.htm
<html>
<head>
<title>My document</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h1>My first stylesheet</h1>
</body>
</html>
style.css
body {
background-color: #FF0000;
}
Now place the two files in the same folder. Remember to save the files with the right extensions
(respectively ".htm" and ".css")
Open default.htm with your browser and see how the page has a red background. Congratulations! You
have made your first style sheet!
Colors and backgrounds
In this lesson you will learn how to apply colors and background colors to your websites. We will also
look at advanced methods to position and control background images. The following CSS properties will
be explained:
• color
• background-color
• background-image
• background-repeat
• background-attachment
• background-position
• background
For example, imagine that we want all headlines in a document to be dark red. The headlines are all
marked with the HTML element <h1>. The code below sets the color of <h1> elements to red.
h1 {
color: #ff0000;
}
Colors can be entered as hexadecimal values as in the example above (#ff0000), or you can use the
names of the colors ("red") or rgb-values (rgb(255,0,0)).
The element <body> contains all the content of an HTML document. Thus, to change the background
color of an entire page, the background-color property should be applied to the <body> element.
You can also apply background colors to other elements including headlines and text. In the example
below, different background colors are applied to <body> and <h1> elements.
body {
background-color: #FFCC66;
}
h1 {
color: #990000;
background-color: #FC9804;
}
As an example of a background image, we use the butterfly below. You can download the image so you
can use it on your own computer (right click the image and choose "save image as"), or you can use
another image as you see fit.
To insert the image of the butterfly as a background image for a web page, simply apply the
background-image property to <body> and specify the location of the image.
body {
background-color: #FFCC66;
background-image: url("butterfly.gif");
}
h1 {
color: #990000;
background-color: #FC9804;
}
Note: Notice how we specified the location of the image as url("butterfly.gif"). This means that the
image is located in the same folder as the style sheet. You can also refer to images in other folders
using url("../images/butterfly.gif") or even on the Internet indicating the full address of the file:
url("http://www.html.net/butterfly.gif").
The table below outlines the four different values for background-repeat.
Value Description
background-repeat: repeat-x The image is repeated horizontally
background-repeat: repeat-y The image is repeated vertically
background-repeat: repeat The image is repeated both horizontally and vertically
background-repeat: no-repeat The image is not repeated
For example, to avoid repetition of a background image the code should look like this:
body {
background-color: #FFCC66;
background-image: url("butterfly.gif");
background-repeat: no-repeat;
}
h1 {
color: #990000;
background-color: #FC9804;
}
A fixed background image will not move with the text when a reader is scrolling the page, whereas an
unlocked background image will scroll along with the text of the web page.
The table below outlines the two different values for background-attachment. Click on the examples to
see the difference between scroll and fixed.
Value Description
Background-attachment: scroll The image scrolls with the page - unlocked
Background-attachment: fixed The image is locked
For example, the code below will fix the background image.
body {
background-color: #FFCC66;
background-image: url("butterfly.gif");
background-repeat: no-repeat;
background-attachment: fixed;
}
h1 {
color: #990000;
background-color: #FC9804;
}
There are numerous ways to set the values of background-position. However, all of them are formatted
as a set of coordinates. For example, the value '100px 200px' positions the background image 100px
from the left side and 200px from the top of the browser window.
The coordinates can be indicated as percentages of the browser window, fixed units (pixels,
centimetres, etc.) or you can use the words top, bottom, center, left and right. The model below
illustrates the system:
Value Description
background-position: 2cm 2cm The image is positioned 2 cm from the left and 2 cm down the page
background-position: 50% 25% The image is centrally positioned and one fourth down the page
background-position: top right The image is positioned in the top-right corner of the page
The code example below positions the background image in the bottom right corner:
body {
background-color: #FFCC66;
background-image: url("butterfly.gif");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: right bottom;
}
h1 {
color: #990000;
background-color: #FC9804;
}
Compiling [background]
The property background is a short hand for all the background properties listed in this lesson.
With background you can compress several properties and thereby write your style sheet in a shorter
way which makes it easier to read.
background-color: #FFCC66;
background-image: url("butterfly.gif");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: right bottom;
Using background the same result can be achieved in just one line of code:
If a property is left out, it will automatically be set to its default value. For example, if background-
attachment and background-position are taken out of the example:
These two properties that are not specified would merely be set to their default values which as you
know are scroll and top left.
Fonts
In this lesson you will learn about fonts and how they are applied using CSS. We will also look at how to
work around the issue that specific fonts chosen for a website can only be seen if the font is installed
on the PC used to access the website. The following CSS properties will be described:
• font-family
• font-style
• font-variant
• font-weight
• font-size
• font
There are two types of names used to categorize fonts: family-names and generic families. The two
terms are explained below.
Family-name
Examples of a family-name (often known as "font") can e.g. be "Arial", "Times New Roman" or
"Tahoma".
Generic family
Generic families can best be described as groups of family-names with uniformed appearances.
An example is sans-serif, which is a collection of fonts without "feet".
The difference can also be illustrated like this:
When you list fonts for your web site, you naturally start with the most preferred font followed by
some alternative fonts. It is recommended to complete the list with a generic font family. That way at
least the page will be shown using a font of the same family if none of the specified fonts are
available.
Headlines marked with <h1> will be displayed using the font "Arial". If this font is not installed on the
user's computer, "Verdana" will be used instead. If both these fonts are unavailable, a font from the
sans-serif family will be used to show the headlines.
Notice how the font name "Times New Roman" contains spaces and therefore is listed using quotation
marks.
Font style [font-style]
The property font-style defines the chosen font either in normal, italic or oblique. In the example
below, all headlines marked with <h2> will be shown in italics.
If font-variant is set to small-caps and no small-caps font is available the browser will most likely show
the text in uppercase instead.
h1 {font-variant: small-caps;}
h2 {font-variant: normal;}
There are many different units (e.g. pixels and percentages) to choose from to describe font sizes. In
this tutorial we will focus on the most common and appropriate units. Examples include:
h1 {font-size: 30px;}
h2 {font-size: 12pt;}
h3 {font-size: 120%;}
p {font-size: 1em;}
There is one key difference between the four units above. The units 'px' and 'pt' make the font size
absolute, while '%' and 'em' allow the user to adjust the font size as he/she see fit. Many users are
disabled, elderly or simply suffer from poor vision or a monitor of bad quality. To make your website
accessible for everybody, you should use adjustable units such as '%' or 'em'.
Below you can see an illustration of how to adjust the text size in Mozilla Firefox and Internet Explorer.
Try it yourself - neat feature, don't you think?
Compiling [font]
Using the font short hand property it is possible to cover all the different font properties in one single
property.
For example, imagine these four lines of code used to describe font-properties for <p>:
p{
font-style: italic;
font-weight: bold;
font-size: 30px;
font-family: arial, sans-serif;
}
p{
font: italic bold 30px arial, sans-serif;
}
Text
Formatting and adding style to text is a key issue for any web designer. In this lesson you will be
introduced to the amazing opportunities CSS gives you to add layout to text. The following properties
will be described:
• text-indent
• text-align
• text-decoration
• letter-spacing
• text-transform
Text indention [text-indent]
The property text-indent allows you to add an elegant touch to text paragraphs by applying an indent
to the first line of the paragraph. In the example below a 30px is applied to all text paragraphs marked
with <p>:
p{
text-indent: 30px;
}
In the example below the text in table headings <th> is aligned to the right while the table data <td>
are centered. In addition, normal text paragraphs are justified:
th {
text-align: right;
}
td {
text-align: center;
}
p{
text-align: justify;
}
h1 {
text-decoration: underline;
}
h2 {
text-decoration: overline;
}
h3 {
text-decoration: line-through;
}
An example could be the word "headline" which can be presented to the user as "HEADLINE" or
"Headline". There are four possible values for text-transform:
capitalize
Capitalizes the first letter of each word. For example: "john doe" will be "John Doe".
uppercase
Converts all letters to uppercase. For example: "john doe" will be "JOHN DOE".
lowercase
Converts all letters to lowercase. For example: "JOHN DOE" will be "john doe".
none
No transformations - the text is presented as it appears in the HTML code.
As an example, we will use a list of names. The names are all marked with <li> (list-item). Let's say
that we want names to be capitalized and headlines to be presented in uppercase letters.
Try to take a look at the HTML code for this example and you will see that the text actually is in
lowercase.
h1 {
text-transform: uppercase;
li {
text-transform: capitalize;
}
Links
You can apply what you already learnt in the previous lessons to links (i.e. change colors, fonts,
underline, etc). The new thing is that CSS allows you to define these properties differently depending
on whether the link is unvisited, visited, active, or whether the cursor is on the link. This makes it
possible to add fancy and useful effects to your website. To control these effects you use so-called
pseudo-classes.
What is a pseudo-class?
A pseudo-class allows you to take into account different conditions or events when defining a property
for an HTML tag.
Let's look at an example. As you know, links are specified in HTML with <a> tags. We can therefore use
a as a selector in CSS:
a{
color: blue;
}
A link can have different states. For example, it can be visited or not visited. You can use pseudo-
classes to assign different styles to visited and unvisited links.
a:link {
color: blue;
}
a:visited {
color: red;
}
Use a:link and a:visited for unvisited and visited links respectively. Links that are active have the
pseudo-class a:active and a:hover is when the cursor is on the link.
We will now go through each of the four pseudo-classes with examples and further explanation.
Pseudo-class: link
The pseudo-class: link is used for links leading to pages that the user has not visited.
a: link {
color: #6699CC;
}
Pseudo-class: visited
The pseudo-class :visited is used for links leading to pages that the user has visited. For example, the
code below would make all visited links dark purple:
a:visited {
color: #660099;
}
Pseudo-class: active
The pseudo-class: active is used for links that are active.
a: active {
background-color: #FFFF00;
}
Pseudo-class: hover
The pseudo-class: hover is used when the mouse pointer hovers over a link.
This can be used to create interesting effects. For example, if we want our links to be orange and be
italicized when the cursor is pointed at them, our CSS should look like this:
a: hover {
color: orange;
font-style: italic;
}
a:hover {
letter-spacing: 10px;
font-weight:bold;
color:red;
}
a:hover {
text-transform: uppercase;
font-weight:bold;
color:blue;
background-color:yellow;
}
The two examples gives you an idea about the almost endless possibilities for combining different
properties. You can create your own effects - give it a try!
You should consider carefully whether it is necessary to remove the underlining as it might
decrease usability of your website significantly. People are used to blue underlined links on web
pages and know that they can click on them. Even my mum knows that! If you change the underlining
and color of links there is a good chance that users will get confused and therefore not get the full
benefit of the content on your website.
That said, it is very simple to remove the underlining of links. As you will recall from one of the
previous sessions, the property text-decoration can be used to determine whether text is underlined or
not. To remove underlining, simply set the value of text-decoration to none.
a{
text-decoration:none;
}
Alternatively, you can set text-decoration along with other properties for all four pseudo-classes.
a:link {
color: blue;
text-decoration:none;
}
a:visited {
color: purple;
text-decoration:none;
}
a:active {
background-color: yellow;
text-decoration:none;
}
a:hover {
color:red;
text-decoration:none;
}
How can you color one particular headline differently than the other headlines on your website? How
can you group your links into different categories and give each category a special style? These are just
examples of questions we will answer in this lesson.
Then we want the white wine links to be yellow, the red wine links to be red and the rest of the
existing links on the webpage to stay blue.
To achieve this, we divide the links into two categories. This is done by assigning a class to each link
using the attribute class.
We can hereafter define special properties for links belonging to whitewine and redwine, respectively.
a{
color: blue;
}
a.whitewine {
color: #FFBB00;
}
a.redwine {
color: #800000;
}
As shown in the example you can define the properties for elements which belong to a certain class by
using .classname in the style sheet of the document.
Identification of element using id
In addition to grouping elements, you might need to identify one unique element. This is done by using
the attribute id.
What is special about the attribute id is that there can not be two elements in the same document with
the same id. Each id has to be unique. In other cases, you should use the class attribute instead. Now,
let us take a look at an example of a possible usage of id:
<h1>Chapter 1</h1>
...
<h2>Chapter 1.1</h2>
...
<h2>Chapter 1.2</h2>
...
<h1>Chapter 2</h1>
...
<h2>Chapter 2.1</h2>
...
<h3>Chapter 2.1.2</h3>
...
The above could be headings of any document split into chapters or paragraphs. It would be natural to
assign an id to each chapter as follows:
Let us say that the headline for chapter 1.2 must be in red. This can be done accordingly with CSS:
#c1-2 {
color: red;
}
As shown in the example above you can define the properties in a specific element by using #id in the
stylesheet of the document.
In this lesson, we will take a closer look at the use of <span> and <div> as exactly these two HTML
elements are of central importance with regards to CSS.
Lets us say we want what Mr. Franklin sees as the benefits of not sleeping your day away emphasized in
red. For that purpose, we can mark the benefits with <span>. Each span is then added a class, which
we can define in our style sheet:
span.benefit {
color:red;
}
Of course you may also use id to add style to the <span>-elements. Just as long as you remember, that
you'll have to apply a unique id to each of the three <span>-elements, as you learnt in the previous
lesson.
Aside from this difference, the grouping with <div> works in more or less the same way. Let us take a
look at an example with two lists of U.S. presidents divided into their political affiliations:
<div id="democrats">
<ul>
<li>Franklin D. Roosevelt</li>
<li>Harry S. Truman</li>
<li>John F. Kennedy</li>
<li>Lyndon B. Johnson</li>
<li>Jimmy Carter</li>
<li>Bill Clinton</li>
</ul>
</div>
<div id="republicans">
<ul>
<li>Dwight D. Eisenhower</li>
<li>Richard Nixon</li>
<li>Gerald Ford</li>
<li>Ronald Reagan</li>
<li>George Bush</li>
<li>George W. Bush</li>
</ul>
</div>
And in our style sheet, we can utilize the grouping in the exact same way as above:
#democrats {
background:blue;
}
#republicans {
background:red;
}
In the examples above, we have only used <div> and <span> on very simple things such as text and
background colors. Both elements have the potential to do much more advanced things. However this
will not be introduced in this lesson. We will look into these later in this tutorial.
The illustration above might seem pretty theoretical to look at, so let's try to use the model in an
actual case with a headline and some text. The HTML for our example is (from the Universal
Declaration of Human Rights):
<h1>Article 1:</h1>
By adding some color and font-information the example could be presented as follows:
The example contains two elements: <h1> and <p>. The box model for the two elements can be
illustrated as follows:
Even though it may look a bit complicated, the illustration shows how each HTML-element is
surrounded by boxes. Boxes which we can adjust using CSS.
As the first example, we will look at how you define margins for the document itself i.e. for the
element <body>. The illustration below shows how we want the margins in our pages to be.
body {
margin: 100px 40px 10px 70px;
}
You can set the margins in the same way on almost every element. For example, we can choose to
define margins for all of our text paragraphs marked with <p>:
body {
margin: 100px 40px 10px 70px;
}
p{
margin: 5px 50px 5px 50px;
}
The usage of padding can be illustrated by looking at a simple example where all headlines have
background colors:
h1 {
background: yellow;
}
h2 {
background: orange;
}
By defining padding for the headlines, you change how much filling there will be around the text in
each headline:
h1 {
background: yellow;
padding: 20px 20px 20px 80px;
}
h2 {
background: orange;
padding-left:120px;
}
Borders
Borders can be used for many things, for example as a decorative element or to underline a separation
of two things. CSS gives you endless options when using borders in your pages.
• border-width
• border-color
• border-style
• border
The width of borders [border-width]
The width of borders is defined by the property border-width, which can obtain the values thin,
medium, and thick, or a numeric value, indicated in pixels. The figure below illustrates the system:
The property border-color defines which color the border has. The values are the normal color-values
for example "#123456", "rgb(123,123,123)" or "yellow".
Types of borders [border-style]
There are different types of borders to choose from. Below are shown 8 different types of borders as
Internet Explorer 5.5 interprets them. All examples are shown with the color "gold" and the thickness
"thick" but can naturally be shown in other colors and thicknesses.
The values none or hidden can be used if you do not want any border.
h1 {
border-width: thick;
border-style: dotted;
border-color: gold;
}
h2 {
border-width: 20px;
border-style: outset;
border-color: red;
}
p{
border-width: 1px;
border-style: dashed;
border-color: blue;
}
ul {
border-width: thin;
border-style: solid;
border-color: orange;
}
It is also possible to state special properties for top-, bottom-, right- or left borders. The following
example shows you how:
h1 {
border-top-width: thick;
border-top-style: solid;
border-top-color: red;
border-bottom-width: thick;
border-bottom-style: solid;
border-bottom-color: blue;
border-right-width: thick;
border-right-style: solid;
border-right-color: green;
border-left-width: thick;
border-left-style: solid;
border-left-color: orange;
}
Compilation [border]
As it is also the case for many other properties, you can compile many properties into one using border.
Let us take a look at an example:
p{
border-width: 1px;
border-style: solid;
border-color: blue;
}
p{
border: 1px solid blue;
}
• width
• height
Setting the width [width]
With the width-property, you can define a certain width of an element.
The simple example below provides us with a box wherein text can be typed:
div.box {
width: 200px;
border: 1px solid black;
background: orange;
}
div.box {
height: 500px;
width: 200px;
border: 1px solid black;
background: orange;
}
If we for example would like to have a text wrapping around a picture, the result would be like this:
How is it done?
The HTML code for the example above, look as follows:
<div id="picture">
<img src="bill.jpg" alt="Bill Gates">
</div>
To get the picture floating to the left and the text to surround it, you only have to define the width of
the box which surrounds the picture and thereafter set the property float to left:
#picture {
float:left;
width: 100px;
}
Now the desired width of the columns is set to e.g. 33%, and then you simply float each column to the
left by defining the property float:
#column1 {
float:left;
width: 33%;
}
#column2 {
float:left;
width: 33%;
}
#column3 {
float:left;
width: 33%;
}
By default, the subsequent elements are moved up to fill the available space which will be freed when
a box is floated to a side. Look at the example above wherein the text is automatically moved up
beside the picture of Bill Gates.
The property clear can assume the values left, right, both or none. The principle is, if clear, for
example, is set to both for a box, the top margin border of this box will always be under the lower
margin border for possible floating boxes coming from above.
<div id="picture">
<img src="bill.jpg" alt="Bill Gates">
</div>
<h1>Bill Gates</h1>
To avoid the text from floating up next to the picture, we can add the following to our CSS:
#picture {
float:left;
width: 100px;
}
.floatstop {
clear:both;
}
Positioning of elements
With CSS positioning, you can place an element exactly where you want it on your page. Together with
floats, positioning gives you many possibilities to create an advanced and precise layout.
• Absolute positioning
• Relative positioning
The principle behind CSS positioning
Imagine a browser window as a system of coordinates:
The principle behind CSS positioning is that you can position any box anywhere in the system of
coordinates.
Let's say we want to position a headline. By using the box model the headline will appear as follows:
If we want this headline positioned 100px from the top of the document and 200px from the left of the
document, we could type the following in our CSS:
h1 {
position:absolute;
top: 100px;
left: 200px;
}
As you can see, positioning with CSS is a very precise technique to place elements. It is much easier
than trying to use tables, transparent images or anything else.
Absolute positioning
An element which is positioned absolute does not obtain any space in the document. This means that it
does not leave an empty space after being positioned.
To position an element absolutely, the position property is set as absolute. You can subsequently use
the properties left, right, top, and bottom to place the box.
As an example of absolute positioning, we choose to place 4 boxes in each corner of the document:
#box1 {
position:absolute;
top: 50px;
left: 50px;
}
#box2 {
position:absolute;
top: 50px;
right: 50px;
}
#box3 {
position:absolute;
bottom: 50px;
right: 50px;
}
#box4 {
position:absolute;
bottom: 50px;
left: 50px;
}
Relative positioning
To position an element relatively, the property position is set as relative. The difference between
absolute and relative positioning is how the position is being calculated.
The position for an element which is relatively positioned is calculated from the original position in
the document. That means that you move the element to the right, to the left, up or down. This way,
the element still obtains a space in the document after it is positioned.
As an example of relative positioning, we can try to position three pictures relatively to their original
position on the page. Notice how the pictures leave empty spaces at their original positions in the
document:
#dog1 {
position:relative;
left: 350px;
bottom: 150px;
}
#dog2 {
position:relative;
left: 150px;
bottom: 500px;
}
#dog3 {
position:relative;
left: 50px;
bottom: 700px;
}
For that purpose, you can assign each element a number (z-index). The system is that an element with
a higher number overlaps an element with a lower number.
Let us say we are playing poker and have a royal flush. Our hand can be presented in a way where each
card has got a z-index:
In this case, the numbers follow on another (1-5) but the same result can be obtained by using 5
different numbers. The important thing is the chronological sequence of the numbers (the order).
#ten_of_diamonds {
position: absolute;
left: 100px;
bottom: 100px;
z-index: 1;
}
#jack_of_diamonds {
position: absolute;
left: 115px;
bottom: 115px;
z-index: 2;
}
#queen_of_diamonds {
position: absolute;
left: 130px;
bottom: 130px;
z-index: 3;
}
#king_of_diamonds {
position: absolute;
left: 145px;
bottom: 145px;
z-index: 4;
}
#ace_of_diamonds {
position: absolute;
left: 160px;
bottom: 160px;
z-index: 5;
}
The method is relatively simple but the possibilities are several. You can place images on text or text
above text etc.
Review Questions
1. Which would you NOT be able to do with CSS?
a. Add text
b. Position the content
c. Define the look of your pages in one place
Summary
Cascading Style Sheets (CSS) is a fantastic tool to add layout to your website. We don’t
require any special software to work with CSS. CSS is used for formatting structured
contents. CSS will give you more precise control of layout. There are total three types
of CSS, In-line Style Sheet, Internal Style Sheet and External Style Sheet. Various
selectors like font, text, background can be used to control complete layout of the
webpage. The major advantage of using CSS to specify fonts is that, at any given time,
you can change font on an entire website in just a few minutes. CSS saves time and
makes your life easier.
Objectives
• To examine the Evolution of JavaScript and describe some of its key features
• To explain JavaScript fundamentals
• To understand difference between Interpreted programs versus Compiled programs
• To explain why to use JavaScript
History of JavaScript
Web pages made using only HTML are somewhat static with no interactivity and negligible user
involvement. Interactive pages can be described as those that understand and process user behaviour
(actions) like mouse movements, mouse button clicks, HTML button clicks etc.
HTML tags are just instructions on document layout and structure; the display of the document in the
window is dependent on the browser. Interactive pages cannot be built with only HTML, we need a
programming language. Further, since the response time to user actions should be quick, the
programming language has to be embedded in the browser itself. (Programs residing on servers can not
bring about interactivity due to the time taken for sending the user input and receiving the response.)
Keeping these things in mind, the people at Netscape came out with a client-side (read browser)
language that was integrated with version 2 of Netscape Navigator. They called this language
JavaScript. (Actually, JavaScript was initially christened LiveScript. Seeing the popularity gained by
Sun Systems' Java, the bigwigs at Netscape changed its name... a clever marketing policy!)
Microsoft's implementation of JavaScript is called JScript and was first introduced with version 3 of
Internet Explorer.
JavaScript is thus, a client-side scripting language. There is also a server-side version that is used in
Active Server Pages, a technology promoted by Microsoft. This tutorial describes only client-side
JavaScript.
JavaScript enables browsers to take decisions and process information. This is the key to interactivity.
JavaScript versus JAVA
JAVA is a strongly typed, compiled programming language developed by Sun Microsystems. JavaScript,
developed originally by Netscape, is a lightweight, interpreted programming language initially called
LiveScript. The two languages are not related in any way. All programming languages share a certain
amount of similarity.
Interpreted programs versus Compiled programs
Before we start discussing the differences between interpreted and compiled we have to define the
term source code or as it is more commonly referred to, the code. The code is the plain text commands
that the program is written in. All programming languages start out as source code; it is then either
interpreted or compiled. The code that you will create in this course can be considered source code.
Interpreted programming languages tend to be simpler to program but slower to execute in general.
Each time a program is run it has to be interpreted (interrogated) line by line, based on the flow of
execution (you will see later branches and loops affect the flow of execution).
Compiled programming languages have a more complex syntax, and require more strict programming
practices. With a compiled programming language you first write the source code, and then you feed it
to a compiler (a special computer program) which produces an executable binary program. On the
Windows platforms the output of the compiler usually ends in the ".exe" file extension. The program
that comes out of the compilation process tends to be platform (operating system) specific. The key
benefit for the programmer is that no other programmer can look at the source code once it is
compiled. The other key factor is that the language used to write the source code becomes irrelevant
once it has been compiled.
• Validate forms at the client-side saving both the precious server resources and time.
Nature of JavaScript
JavaScript is based on Object Oriented Programming concept. Its syntax is quite similar to C, C++ and
Java. As it is based on Object Oriented Programming concepts, it is called as “Object Based”.
However, it is much easier to learn and implement.
Other Client-side languages like JavaScript
JScript: Invented by Microsoft, this language is similar to JavaScript. Supported by almost all the
browsers.
VBScript: Implemented only under Internet Explorer, this client-side language is similar to BASIC. It is
commonly used in ASP technology.
PerlScript: Similar to the Perl Language. Not well supported by all browsers.
Review Questions
1. State True or False: JavaScript is an interpreted language.
3. State True or False: JAVA and JavaScript were created by the same company.
a. JavaScript
b. JAVA
c. BASIC
d. VBScript
e. C++
f. Perl
Summary
Objectives
• To place JavaScript in an HTML page
• To explain the Case-sensitivity of JavaScript
• To understand importance of Semicolons
• Understanding Whitespace, Brackets and Comments
• To declare Variable and Function Names
• To understand Reserved words in JavaScript
JavaScript code should also be placed inside an HTML Comment tag set.
When used with JavaScript the ending comment tag will also start with two slashes // which is the
JavaScript code for comment. This tells the JavaScript interpreter to ignore that statement.
This is a standard way for adding JavaScript to your HTML pages so that it works properly for browsers
that are JavaScript enabled and those that do not support JavaScript.
<HTML>
<HEAD>
<TITLE>Web Page containing JavaScript</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
</SCRIPT>
</HEAD>
<BODY>
(HTML document goes here)
</BODY>
</HTML>
You may also put in a single line of code attached to an event. Events will be explained later. The
general syntax for this structure is:
Start a text editor (example, Notepad in Windows) and type the following:
<HTML>
<HEAD>
<TITLE>My First JavaScript</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">
<!--
document.write("This is JavaScript!");
//-->
</SCRIPT>
</BODY>
</HTML>
Save this file with a .html or .htm extension and view it in a browser.
Explanation:
document.write("This is JavaScript!"); is a JavaScript statement.
Note the following points:
• The code informs the browser to write some text in the document. In this case, the text to be
written is This is JavaScript!.
• The text is enclosed in quotes and placed inside parenthesis. The quotes are NOT written along
with the text; they help to signify the beginning and the end of the text.
Though, it is not necessary to end JavaScript statements with a semi-colon, it’s always a good habit.
Case-sensitivity:
JavaScript is a case-sensitive language, meaning that the language will treat these words differently:
example, Example, EXAMPLE
Semicolons:
It is not compulsory that all statements should end with a semicolon. The semicolon separates one
statement from another.
White Space:
JavaScript, like HTML, ignores spaces, tabs, and newlines that appear in statements. JavaScript does,
however recognize spaces, tabs, and newlines that are part of a string. We will talk more about strings
later in next sessions.
All of these examples will produce the same results. It is a good idea to put some spacing in your code
to make it easier to read. It is not good programming practice to stretch statements over several lines.
You do need a space between a programming command and the thing it is working on. For example,
you need a space between var and the variable name.
A string is a sequence of zero or more characters enclosed within single or double quotes (‘single’,
"double").
The double quotation mark can be found within strings that start, and end with (are delimited by)
single quotes ('He said, "JavaScript is an interesting language." ').
The single quotation mark can be used within a string delimited by double quotation marks. This syntax
will be used quite often through out the JavaScripting codes.
For example:
In the example above you have line of HTML code that uses double quotes to delimit the tag's
attributes. So to create a popup window that displays the string "You Clicked me" we need to enclose
the string within single quotes. This is done so that the entire JavaScript statement is interpreted and
the HTML syntax also remains valid.
The backslash character named as such because it leans backwards, and it should not be confused with
the forwardslash character (/) that leans forwards. The backslash has a special purpose in JavaScript
strings. It will be followed by another character that represents something in a string that cannot be
typed on the keyboard.
For example you want the word "You" to appear on one line and the word "Clicked" on a new line and
"me" on a third line. The string would look like this:
'You\nClicked\nme'
The ‘\n’ represents a carriage return and a line feed. These are the two operations that take place
when you use the return on a typewriter. The results would look like this:
You
Clicked
me
These backslash and letter combinations are commonly referred to as escape sequences. Some of the
common sequences are:
\b backspace
\f form feed
\n new line
\t tab
The last two are important and can be used like this:
'You didn\'t get that done' or "You didn\'t get that done"
The \ tells the interpreter that in this case it should print the single quote and not interpret it as a
delimiter.
i.e.
winpop = window.open('ex1.htm','popup','scrollbars=yes');
if ( x[0] == 10 )
{
x[0] = 0;
x[1] = 0;
}
The curly brackets { } are used to contain multiple JavaScript statements. In the above example x[0]=0;
and x[1]=0; are two different statements.
The square brackets [ ] are part of a special data structure called arrays. Arrays will be covered later.
The curved brackets ( ) are used to contain a function or a method’s arguments. Functions and methods
will be described shortly. Multiple arguments are separated by commas.
i.e. ('ex1.htm','popup','scrollbars=yes').
Comments:
You can create a comment using the double forward slashes, like this:
// this is a comment
Or for multiple line comments you can open the comment with a forward slash and an asterisk "/*", and
close it with an asterisk followed by a forward slash "*/" like this:
/* Comments are often used by programmers to leave notes about their program logic so that when
they return to update it, or someone else needs to edit it, they can understand what the programmer
was doing at the time. */
In the next chapter you will be introduced to variables and functions. As the programmer you get to
choose and assign the names. The names of the variables and functions must follow these simple rules.
1. The first character must be a letter of the alphabet (lowercase or uppercase), an underscore (_) or
a dollar sign ($). The dollar sign is not recommended as it is not supported prior to JavaScript ver
1.1.
add_two_num
x13
_whatever
$money_string
We recommend that you use descriptive names for your variables and your functions and that you
adopt a standard way of naming things. The two formats that are common are; using the underscore to
replace spaces, or capitalizing the first letter of complete words after the first word in the name. For
example:
add_two_num
addTwoNumbers
Reserved Words
There are a number of words that make up the components of the JavaScript language. These words
cannot be used for variable or function names because the program interpreter would be unable to
distinguish between a default JavaScript command and your variable or function name.
Review Questions
1) Which of the following are valid variable or function names:
a) y
b) 100percent
c) a big number
d) break
e) subtractTwoNumbers
f) First_Name
if _ z_0_ == 0 _ _
x = 2;
Summary
Objectives
• To declaring Variables
• To understand how to use Operators
• Creating Control Structures ( Branches and Loops )
• To work with Functions ( Built-in and programmer-created)
var x;
var y;
var sum;
Here var stands for ‘Variant’. You can also declare multiple variables with the same var keyword.
var x, y, sum;
To take it one step further you can combine variable declaration with initialization.
var x = 1, y = 3, sum = 0;
If you don't specify an initial value for a variable when you declare it, the initial value is a special
JavaScript undefined value.
Remember: JavaScript is very case-sensitive so ‘x’ and ‘X’ are two different variable names.
Types of Variables
A big difference between JavaScript and other languages like JAVA and C is that JavaScript is untyped.
This means that a JavaScript variable can hold a value of any data type, and its data type does not
have to be set when declaring the variable. This allows you to change the data type of a variable
during the execution of your program, for example:
var x = 10;
x = "ten";
In this example the variable x is first assigned the integer value of 10, and then the string value of the
word ten.
Using Operators
Operators are the things that act on variables. We have already seen an operator used in the previous
example, where we were assigning values to our variables. The example used one of the most common
operators, "=" or the assignment operator. Another operator would be the addition operator "+".
var x = 1, y = 3, sum = 0;
sum = x + y;
This small chunk of JavaScript code will declare the variables x, y and sum and assign the number 1 to
x, 3 to y and 0 to sum. The second line of the script will add x to y and assign it to sum. The value of
the sum variable will be 4.
Other operators are used to compare things, i.e. "==" equality, ">" greater than. For example,
var x = 1, y = 3, sum = 0;
if ( sum == 0 )
sum = x + y;
This bit of code first checks to see if sum is equal to zero, and if so then it adds x and y together and
assigns the result to sum. The "if" statement is an example of a control structure which you will
examine in coming session.
JavaScript Operators
Computational
These are probably the most common operators. They are used for common mathematical operations.
Unary negation ( - )
Increment ( ++ )
Decrement ( -- )
Multiplication ( * )
Division ( / )
Modulo arithmetic ( % )
Addition ( + )
Subtraction ( - )
Logical
These operators are very commonly used in conditional statements like "if" and "switch" that you will be
learning about shortly.
Logical NOT ( ! )
Less than ( < )
Greater than ( > )
Less than or equal to ( <= )
Greater than or equal to ( >= )
Equality ( == )
Inequality ( != )
Logical AND ( && )
Logical OR ( || )
Conditional (trinary) ( ?: )
Comma ( , )
Bitwise
You have probably heard that computers work with bits and bytes. These operators do work with bits or
zeros and ones. These operators are very rarely used.
Bitwise NOT ( ~ )
Bitwise Shift Left ( << )
Bitwise Shift Right ( >> )
Unsigned Shift Right ( >>> )
Bitwise AND ( & )
Bitwise XOR ( ^ )
Bitwise OR ( | )
Assignment
It is important to note that the single equal sign is used for assignment and not for testing equality.
The compound assignment operators can combine a couple of programming steps to make your code
tighter, and more efficient.
Assignment ( = )
if ( (x == 1) && (y == 3) )
{
sum = y - x;
}
In this statement the value of the x variable is compared to 1 to see if it is equal, and the value of the
y variable is compared with 3 to see if it is equal. The use of the "&&", which is the "and" operator,
adds an additional logical condition that says that the first comparison must be true and the second
comparison must be true for the overall result of the test to be true. If the test results in an overall
true condition then the statements that follow the if statement will be executed. If the test results are
false nothing will occur.
An additional clause you can add to the "if" statement is the "else", an example:
if (sum == 0)
{
sum = x + y;
}
else
{
subtotal = sum;
}
This statement is read as: if sum equals 0 then sum equals x plus y, or else subtotal equals sum.
switch
The switch statement is handy when a variable may take on a number of values and you want to test
for some of those values. The use of "switch" is shorter and easier to read than a number of "if"
statements.
switch(n)
{
case 1: //start here if n equals 1.
// place code here
break;
case 2: //start here if n equals 2.
// place code here
break; // stop here
.
.
.
default; // if all other conditions fail do this
// place code here
break;
}
Loops
A loop is a programming structure that forces the statements contained within its delimiters to execute
over and over again until a condition is met at which point the loop ends.
While Loop
The JavaScript while loop is much simpler than the for loop. It consists of a condition and the
statement block.
while (condition)
{
...statements...
}
As long as the condition evaluates to 'true', the program execution will continues to loop through the
statements.
In the previous session, we had used the for loop to display digits 1 to 10 in an alert box. We'll now
employ the while loop to do the same thing.
var msg = "";
var x = 1;
while (x <= 10)
{
msg = msg + x + "\n";
x++;
}
alert(msg);
Note that the initialization statement (X = 1) has been placed before the loop. The condition lies
between the parenthesis and the updation statement (x++) is present inside the statement block.
It's a common error by beginners to forget the updation statement in which case the condition will
never evaluate to 'false' and this will result in an infinite loop. To avoid such situations, my humble
advice is to write the updation statement right after starting the statement block. You can then build
the rest of the code in the statement block.
We can also employ the while loop to display the 12 times table as we had done with for.
var msg = "";
var x = 1;
var res = 0;
while (x <= 10)
{
res = 12 * x;
If the condition in while evaluates to 'false' at the very beginning, the loop is skipped altogether and
program execution starts at the statement immediately following the loop.
In the code above, the value of variable x is 20, hence the condition evaluates to 'false'. However, the
loop is executed once since the condition is presented at the end of the loop and not at the beginning.
• break: causes the loop to stop and program execution to begin at the statement immediately
following the loop.
For example, continue can be employed to display only the even numbers between 1 to 20, skipping
the odd numbers.
var msg = "";
for (var x = 0; x <=20; x++)
{
if (x%2)
{
continue;
}
msg = msg + x + "\n";
}
alert(msg);
The condition in if checks for a remainder when variable x is divided by 2. Thus, for odd numbers, the
condition will be 'true' and the loop will be skipped because of continue.
When the JavaScript interpreter comes across a for loop, it executes the initialization statements and
then checks the condition. Only when the condition returns 'true', the interpreter enters the loop. After
the first iteration, the updation statements are executed and then the condition is evaluated again.
This continues till the condition returns 'false' and the loop stops.
Some important points to note are:
• The initialization statements are executed once; only when the for loop is encountered.
• After every iteration, the updation statements are executed and then the condition is checked.
Output:
First, the variable x is initialized to 1, the condition is then evaluated. Since x is less than equal to 10,
the statements inside the for loop are executed. The JavaScript interpreter then runs the updation
statement that adds 1 to variable x. The condition is again checked. This goes on till the value of x
becomes larger than 10. At this point, the statement immediately following the for loop is executed.
Output
For...In Statement
The for...in statement is used to loop (iterate) through the elements of an array or through the
properties of an object.
The code in the body of the for ... in loop is executed once for each element/property.
Syntax
for (variable in object)
{
code to be executed
}
The variable argument can be a named variable, an array element, or a property of an object.
Example
Using for...in to loop through an array:
<html>
<body>
<script language="JavaScript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>
Output:
Functions
Functions are an important part of programming as they allow you to create chunks of code that
performs a specific task. Functions in JavaScript are called subroutines or procedures in other
programming languages. JavaScript has a number of built-in functions that are part of the language.
JavaScript also gives you the ability to create your own functions. Your JavaScript programs may be
made up of one function or several functions.
Built-in:
The built in functions are there to perform a number of actions that programmers expect to be part of
a programming language. Some of the built in functions include: parseFloat(string value),
parseInt(string value), isNaN(value), etc.. We will use these functions later in the coming sessions.
Programmer Created:
Functions that you create start with the command "function" and are followed by the name for the
function. For example:
Usually the name is an indicator of the action the function is going to provide such as "checkForm". The
name is followed by a set of parenthesis and inside the parenthesis there can be a number of
arguments. Arguments are the variable names that will be used for values (data) being passed to the
function.
All functions have the ability to pass back a value through the return statement. Another way of saying
this is you can pass data into a function using its arguments, and get the results out with a returned
value. Functions can only return one value. In the example below the sum of two numbers is returned
by the add_two_num() function.
function add_two_num( a, b)
{
var sum = a + b;
return sum;
} // end of function add_two_num
function mainProgram()
{
var x = 5, y = 3, total = 0;
total = add_two_num( x , y );
alert(total); // display the value of total
1. The function mainProgram declares variables and assigns their initial values as follows - "x"
equal to 5, "y" equal to 3 and "total" equal to 0
2. Then it calls the add_two_num function and passes in the values of x and y.
3. In the add_two_num function the values are added together and stored in a variable named
sum.
4. The value of sum is returned back to the mainProgram function and stored in the variable
named total.
Variables declared in a function are only available while within that function’s braces { }. These are
commonly referred to as local variables. Another type of variable is a global variable. Global variables
are available to all functions, and should be used with caution, as it is easy to assign the wrong value
to a global variable. In the above example globalVar is a global variable because it is declared outside
of all of the functions.
Calling a function
While calling a JavaScript function you have to just mention function name on particular event or you
have to call it without using any keyword to make a function call.
Eg:
function callMe()
To call the above function we can use one of the two methods
a) <SCRIPT language=”JavaScript”>
callMe();
<SCRIPT>
or
Review Questions
1. True or False. Variables in JavaScript are strongly typed.
a. = assignment
b. == addition
c. + equality
5. Create an if structure that will make sure the value of the p variable is greater than or equal to
99, and if so set the total equal to the value of p.
6. Create a function that will multiply two numbers together and return the result.
Summary
Variables are declared using the keyword var. Default value associated to any
variable is ‘undefined’ until specified explicitly. Variuos operators can be used
to perform certain calculations. Control structures, branches and loops can be
used for descrising size of the code. There are two types of functions, built-in
and programmer-created.
Objectives
• To understand Objects in JavaScript
• How to use the "new" operator
• To understand the Document Object Model
• Working with Arrays and its methods
• To use Events
o onClick
o onSubmit
o onMouseOver
o onMouseOut
o onFocus
o onChange
o onBlur
o onLoad
o onUnload
Objects
An object is a collection of variables (parameters) and functions (methods). The syntax for using an
object is: object.parameter, or object.method(). A string is an object in JavaScript and has several
methods and parameters.
var x = StringVar.length;
StringVar = StringVar.toUpperCase();
If this code is executed StringVar is a new variable with the value of "This is a string of characters.".
The x variable is set to the length of the StringVar, in this case 31. Length is a property of the string
object. If you count the characters (letters, spaces, and punctuation) between the quotes you will see
that it adds up to 31. The toUpperCase() method converts all of the alpha characters in the string to
upper case i.e. "THIS IS A STRING OF CHARACTERS.".
JavaScript has the following objects built into the language: String, Math, Date and Array. The string
object has a number of methods for manipulating strings as demonstrated above with the
toUpperCase() method. The math object is a collection of methods and properties for performing
mathematical operations like: min(), max(), sin(), cos(), etc.. The date object is a collection of
methods for working with dates and time. The array object allows programmers to create collections of
data. Arrays will be discussed shortly.
The new operator
Objects and arrays cannot simply be typed into your JavaScript programs! They must be created. We
use the "new" operator to create a new instance of an object or an array. To put that another way the
new operator creates a copy of an existing object or an array structure and assigns the name you want
to it.
Since objects are made up of methods (functions) and parameters (variables), the newly created object
"obj" in this case has all of the same methods and parameters of the original Object. The parameters
will all be set to their default value. Arrays will be covered shortly.
The HTML elements that you add to a page also extend the object hierarchy. An example is the FORM
element and the elements that reside inside the form. This means that you can reference these
objects, as illustrated in the HTML page below:
window.document.forms[0]
Refers to the first form in the document. Forms are implemented as arrays in the DOM. If there is more
than one form on page the numbers will start at zero and go up.
window.document.Form1
window.document.Form1.FirstName.value
Refers to the value typed into the textbox named FirstName by the client, in the form named Form1
<HTML>
<HEAD>
<TITLE>Simple Form</TITLE>
</HEAD>
<BODY>
<FORM NAME="Form1">
Name: <INPUT TYPE="TEXT" NAME="FirstName"><BR>
<INPUT TYPE="Button" VALUE="Submit Info" >
</FORM>
<FORM NAME="Form2">
Name: <INPUT TYPE="TEXT" NAME="LastName"><BR>
<INPUT TYPE="Button" VALUE="Submit Info" >
</FORM>
</BODY>
</HTML>
Objects located in the current document, in the current window can drop the reference to those two
objects. For example:
forms[0]
Form1
Form1.FullName.value
refers to the value typed, in the browser by the client, into the textbox named FullName, in the form
named Form1, in this document
We recommend that you use the NAME attribute of any HTML tag that you are going to script, as in the
above example the form is named Form1. This practice will simplify object naming for you.
Window
document
links Plug-ins
Frames
anchors frames
History
input
elements scripts
Navigator submit
filters forms
event reset
body selection
screen option
applet Style sheets
Location
embeds all
Arrays
JavaScript, similar to other programming languages, has the capabilities to use a data structure called
an array. An array is a collection of data where each piece of data is held in a numbered position
within the array. A one-dimensional array would be similar to a column in a spreadsheet.
Each position in the array is assigned an index number beginning with 0 for the first position, 1 for the
second position, and so on. This allows any position within the array, or "element" of the array, to be
referenced by its index number.
The index of the array is indicated by the number contained within the square brackets. An array is
implemented as an object in JavaScript and can be created using the "new" statement.
Arrays are important to understand because a number of components of the Document Object Model
(DOM) are implemented as arrays, like forms, images, and elements.
Defining Arrays
The Array object is used to store a set of values in a single variable name.
We define an Array object with the new keyword. The following code line defines an Array object
called myArray:
var myArray=new Array()
There are two ways of adding values to an array (you can add as many values as you need to define as
many variables you require).
1:
var mycars=new Array();
mycars[0]="Saab";
mycars[1]="Volvo";
mycars[2]="BMW";
You could also pass an integer argument to control the array's size:
var mycars=new Array(3);
mycars[0]="Saab";
mycars[1]="Volvo";
mycars[2]="BMW";
2:
var mycars=new Array("Saab","Volvo","BMW");
Note: If you specify numbers or true/false values inside the array then the type of variables will be
numeric or Boolean instead of string.
Accessing Arrays
You can refer to a particular element in an array by referring to the name of the array and the index
number. The index number starts at 0.
<body>
<script type="text/javascript">
arr[0] = "Jani";
arr[1] = "Tove";
arr[2] = "Hege";
arr2[0] = "John";
arr2[1] = "Andy";
arr2[2] = "Wendy";
document.write(arr.concat(arr2));
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
document.write(arr.join("."));
</script>
</body>
</html>
Output: -> Jani,Hege,Stale //Here separator among two array elements is ‘,’
Jani.Hege.Stale //Here separator among two array elements is ‘.’
<html>
<body>
<script type="text/javascript">
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[4] = "Borge";
arr[5] = "Tove";
document.write(arr.sort());
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
function sortNumber(a, b)
return a – b;
arr[0] = "10";
arr[1] = "5";
arr[2] = "40";
arr[3] = "25";
Training & Development Division Page 206 of 282
HTML, DHTML & JavaScript
arr[4] = "1000";
arr[5] = "1";
document.write(arr.sort(sortNumber));
</script>
</body>
</html>
JavaScript Events
Events are the triggers that call (start) one of your functions. Your client-side JavaScript programs will
not execute (run / be interpreted) unless started by an event. An event could be an action such as
clicking on a button or placing your mouse over an image. We will use the onClick event for starting our
form validation scripts, and the onMouseOver event for creating graphic images that change when you
place your cursor over them.
onClick( )
A click event occurs when a button, checkbox, radio button, reset button, or submit button is clicked.
This event is regularly used with a button to start script execution.
In the above example when you click on the button "Click Me" it will execute the JavaScript statement
"window.alert('You Clicked me');". You can call any function or method this way.
onSubmit( )
A submit event occurs when the user submits a form. This event is regularly used with a form and a
submit button to start the form validation script.
In the above example when the user clicks on the submit button, it will execute the function
"checkform()". If the form passes all the validation tests, a true value is returned and the data will be
passed to the "formtest.asp" CGI program. If the form contents do not pass the validation tests, it will
not send the data to the "formtest.asp" CGI program.
Note: You will be using these events while using Alerts, Prompts, and Confirmations; as well as, for
Form Validation.
onMouseOver( )
An onMouseOver event occurs when the user positions their mouse over a hyperlink, over any object of
page, or a linked region of a client-side image map.
<html>
<head>
</head>
<body>
<a href="http://www.lntinfotech.com"
</body>
</html>
Training & Development Division Page 208 of 282
HTML, DHTML & JavaScript
In the above example an HTML link to a web site is created using the anchor tag. The onMouseOver()
event is added to the anchor tag, and in this case the script will pop-up an alert message on the
browser window. Take a look at the results below.
onMouseOut( )
An onMouseOut event occurs when the user moves their mouse off of a hyperlink, or a linked region of
a client-side image map.
<html>
<head>
<title>Window Loop Test</title>
</head>
<body>
<A href="http://www.lntinfotech.com"
onMouseOut="window.status='L&T Infotech'">Click for information of L&T
Infotech</A>
</body>
</html>
In above example when the mouse is over the link, the hyperlink URL is shown in the status line, and
when the mouse is moved off the hyperlink the message is displayed.
onFocus( )
This event occurs when a user tabs into or clicks on a password field, a text field, a textarea, or a
FileUpload field in an HTML form. If a user clicks on one of these elements in a form, it is receiving the
user's focus.
onFocus="window.status=('Please enter the Month as two digits 01 through 12'); return true;">
In this example when the user clicks on the month box or tabs into it a message is displayed in the
status line of the browser that indicates what the user should type in.
onChange( )
The change event happens when the user leaves a password, text, textarea or FileUpload field in an
HTML form, and its value has changed.
onBlur( )
The blur event triggers when the user leaves a password, text, textarea or FileUpload field in an HTML
form.
onBlur="window.status=('Do you not care about the value of the Month!'); return true;">
Note: It is usually a good idea to use either onChange or onBlur, and not both at the same time as they
will appear to conflict with one another.
onLoad( )
The load event triggers when the browser finishes loading a document or all the frame pages within a
<FRAMESET>.
In this example after the page has completed loading into the browser the alert message below is
popped up.
onUnload( )
The unload event occurs when you move to a new document. For example if you use the back button,
or click on a link to another page the unload event will occur.
This example will popup the following message when someone moves off of the current page.
For example,
<html>
<head>
<title>Window Loop Test</title>
</head>
<body>
<A href="http://www.lntinfotech.com" onMouseOver="window.status='Mouse Over';
return true;" onMouseOut="window.status='Mouse Out'; return true;">
Click me</A>
</body>
</html>
Observe the output (on Status bar), if you keep mouse cursor over the link, you will get message as:
If you keep cursor away then you will get status message as
The following table shows you what events are supported on the HTML Form Elements.
Events / Blur Click Change Focus Load Mouseover Select Submit Unload
HTML
Elements
Button X
Checkbox X X X
Document X
Form X
Link X
Radio X
Reset X
Selection X X X
Submit X
Text X X X X
Textarea X X X X
Review Questions
1) An object is a collection of ______________ and _______________.
2) The four objects that are built into the JavaScript language are:
a) _______________
b) _______________
c) _______________
d) _______________
3) (True or False) The DOM is a collection of objects added to the JavaScript language by the browser.
4) (True or False) Events are key to beginning the execution of your scripts.
5) Which event would you use to start a script after a page has been fully loaded by the browser?
a) onClick()
b) onSubmit()
c) onLoad()
d) onMouseOver()
e) onload()
Summary
An object is nothing but instance of class. The new operator can be used to create objects
and initialised it to some variable. To reach on any level of any specific control (it can be
Form control or non-form control) Document Object Model is used. DOM contains readymade
collection of objects which are helping us while finding some values or while doing certain
settings. Array can be created using Array class. There are various events which are allowing
us to do specific operation on particular event. There are certain built-in events like onClick,
onSubmit, onMouseOver, onMouseOut, onFocus, onChange, onBlur, onLoad, onUnload etc.
window.alert( message )
The "message" is plain text (not HTML) that displays in a dialog box popped up over a window. The alert
box will have a button labeled "OK" that will dismiss the alert box when clicked.
window.alert("Hello Gary!");
The above line of code would produce the following popup window.
The "message" is again plain text that will be displayed in the dialog box popped up over the window,
and the default is a string that is displayed as the default input. When default is set to "", nothing will
be in the prompt box. The prompt window will have an input field for the user to enter information and
an "OK" button and a "Cancel" button. This method will return the value that the user types in.
The above line of code would produce the following popup window
window.confirm( question )
The question is another plain text string. It should be a question that you want answered by the user.
The above line of code would produce the following popup window.
If the user clicks on the OK button the method will return a Boolean value of true. If however the user
clicks on the cancel button the method will return a Boolean value of false. These return values can be
stored in a variable like ageTest and used with branching logic.
Our lab for this section will demonstrate using all three window methods.
<HTML>
<HEAD>
<TITLE>Simple Form</TITLE>
</HEAD>
<BODY>
<FORM NAME="Form1">
Name: <INPUT TYPE="TEXT" NAME="Name"><BR>
<INPUT TYPE="Button" VALUE="Submit Info">
</FORM>
</BODY>
</HTML>
At this point the form will do nothing when the "Submit Info" button is pressed. What we will first do is
use the onClick event on the button to popup an alert message that says Hello "The name typed in"
followed by an exclamation mark.
Training & Development Division Page 218 of 282
HTML, DHTML & JavaScript
To make this button function we need to add the onClick event to our HTML page.
This says when the user clicks on the button, the browser will create an alert (the popup). Alert is a
method of the window object. In this case the string 'Hello ' will be concatenated with the data typed
in by the user in the textbox and concatenated with the exclamation mark. Single quotes are used to
delimit the strings in this example because the HTML code requires the double quotation marks as
delimiters of the attribute onClick. Remember our discussion of syntax; the JavaScript statement must
end with a semicolon.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function do_stuff() {
var flag=false, fullName;
fullName = prompt('Please enter your name','');
// If the user does not confirm that their name is correct the user if
// the user is given a chance to re-enter it.
if (flag == false) {
fullName = prompt('Please re-enter your name','');
}
}
}
//end hiding of JavaScript code -->
</SCRIPT>
</HEAD>
<BODY onload="do_stuff()">
<H1>Using Prompts, Confirms, and Alerts</H1>
</BODY>
</HTML>
Review Questions
1. What are the predefined, popup style, dialogue boxes we can use with JavaScript?
2. Which type of dialogue box would you use if you want the user to enter some information?
3. What is concatenation?
Summary
There are certain window class’s functions which are allowing us to show
alert, taking valuable opinion from users like Yes/No type question by using
Confirm and taking runtime data by using prompt messages. We can use
any one of these three methods to make our program more effective.
Objectives
• To create a FORM with an Active Cursor
• To understand FORM Checking for validation
• To Create a function
• To Test form validations
Many authors that create forms for use on the web would like to have the cursor placed and active in
the first input field. It would mean that a person browsing wouldn’t have to click in the field before
entering data; they could simply begin to type.
FORM elements of the type text, password, textarea and file upload support, not only events such as
onClick and onBlur but they also support the methods of "focus" and "blur". This means that you can tell
the cursor to be placed in the input field or that it can’t be placed in specified fields. If you combine
this feature with the pages onLoad event you can place the cursor in a designated field when the page
loads.
<HTML>
<HEAD>
<TITLE>Simple Form</TITLE>
</HEAD>
<BODY onLoad="document.CardForm.HoldersName.focus()">
<FORM NAME="CardForm" action="www.lntinfotech.com/UserCheck.html">
Enter Cardholders Name: <INPUT TYPE="TEXT" NAME="HoldersName">
<BR>
<INPUT TYPE="Submit" VALUE="Submit Info">
</FORM>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE>Simple Form</TITLE>
</HEAD>
<BODY onLoad="document.CardForm.HoldersName.focus()">
This form has, as much "checking" as there is available with HTML. The card number field is restricted
to 16 characters, but does not require 16 at this point. Our month and year fields are broken into two
text areas that will only allow two characters each, but do not require two.
1. To make sure a name is entered into the Cardholder's Name field. We will test this by making sure
the user has typed in at least one character.
2. To make sure the card number is 16 characters long, and is made up of only numbers. We will do
this by testing the length of the string typed in by user, and testing to make sure that it is only
made up of numbers.
3. To make sure the month and year are entered as numbers, and that they are valid. This means the
month must be between 1 and 12 and the year must be greater than or equal to this current year.
4. If any of these criteria are not met then an alert should notify the user of what is wrong, and the
information should not be sent to the server for processing.
Let’s start by adding your required script tags and comments; as well as, creating a new function called
checkform.
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function checkform()
{
}
//end hiding of JavaScript code
-->
</SCRIPT>
The function checkform() does not currently have any instructions to execute. We will add these
shortly. In order to call this function we will add the following onSubmit event to the FORM HTML tag.
onSubmit="return checkform();"
Now when someone clicks on the Submit Info button it will first execute the checkform() function
before sending the information to the web server for processing. Note that we are using the "return"
property, associated with the "checkform" function, which looks for a value of true or false from the
associated function. If checkform() returns a value of true, then the form contents will be submitted to
the Server side Script, on the server, for processing. If checkform() returns a value of false the
contents will not be submitted and some other action may be initiated such as an alert.
The next piece of code you will add is a string variable named "message" that will hold the contents of
the error message to be displayed to the user as an alert. You will also add an "if" structure that will
test for the length of the error message. If the "message" variable's length is greater than zero then an
alert message should be displayed, if it is zero then the information is correct and should be sent to
the server for processing.
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function checkform() {
var message = "";
if ( message.length > 0 ) {
alert( message );
return false;
}
else {
return true;
}
Now you have this structure in place, now you can create your first real test of your form. Lets check
to see if the length of the card holder's name is greater than zero.
if (document.CardForm.HoldersName.value.length == 0) {
message = message + "Please enter the name on the credit card!\n";
}
This statement appears complex at first, but lets step through it to see how it works. The "if" is testing
the value typed into the HoldersName field of your HTML FORM named CardForm that is in the
document. This accurately references the object’s value, the .length will return the length of the
number of characters in the string. If the length is equal to zero you know that the user has typed
nothing in, and you should create an error message. Creating the error message is the purpose of the
next line. The error message you want to display is "Please enter the name on the credit card!". The \n
at the end of the line will cause a carriage return and a linefeed so that the next error message will
display on a new line inside the same alert box. You know that you will be testing each field for a
correct value so we may have a different error message associated with each test. You add the current
value of the message variable using the (+) concatenation operator and store the result back in the
message variable using the (=) assignment operator.
You can now add the next three tests that are all the same structure.
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function checkform() {
var message = ""; // create error message string variable, with nothing in it
if (document.CardForm.HoldersName.value.length == 0) {
message = message + "Please enter the name on the credit card!\n";
}
if (document.CardForm.CardMonth.value.length < 2) {
message = message + "Please type in both digits of the expiry month!\n";
}
if (document.CardForm.CardYear.value.length < 2) {
message = message + "Please type in both digits of the expiry year!\n";
}
</SCRIPT>
Note: You will notice that we have added comments to some of the code. This is great for
remembering what something is doing down the road. Commenting also makes it easier for others to
understand your code.
if (document.CardForm.CardMonth.value.length < 2) {
// test to make sure two characters where entered
message = message + "Please type in both digits of the expiry month!\n";
}
else if (isNaN(document.CardForm.CardMonth.value)) {
// test for numeric digits only
message = message + "The Month value needs to be between 1 and 12\n";
}
The above code segment is built upon our length test. Now that you know you have two characters you
must check to see that they are numeric. Once that has been determined you need to check to make
sure the numeric values are within the range we are interested in.
We use a new function in the code segment; isNaN(), which means " is Not a Number". “isNaN()” will
return a value of true if the string being evaluated is not a number, or it will return a value of false if
the string being evaluated is made up of only numeric digits.
We use the operators < "less than", > "greater than", and || "or". So the last expression is read as
follows; "if the value is less than one or greater than 12 then display an error message."
Once you have added this code to your web page, you can test all of the conditions with the following
inputs: blank, aa, 1, -1, 13, and 06.
Then we add similar lines to setup the test for a valid year. Use 99, 98, 00 for test values. As you can
tell, your script is not year 2000 compliant.
Add the necessary lines to test for 16 digits in the card number. Test with the following inputs:
123456789abcdefg, 123456789, 1234567890123456.
Complete Script
<HTML>
<HEAD>
<TITLE>Simple Form</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function checkform() {
var message = ""; // create error message string variable, with nothing in it
// Test the Card Holder's Name Length
if (document.CardForm.HoldersName.value.length == 0) {
message = message + "Please enter the name on the credit card!\n";
}
else if (isNaN(document.CardForm.CardNumber.value)) {
// test for numeric digits only
message = message + "The Card Number must contain only numbers.\n";
}
document.CardForm.CardMonth.value > 12 ) {
// test the values to make sure they are between 1 and 12
message = message + "The Month value needs to be between 1 and 12\n";
}
</HEAD>
<BODY onLoad="document.CardForm.HoldersName.focus()">
</BODY>
</HTML>
Review Questions
1. What event was used to place the cursor in the first field of our FORM?
2. What did we test to see if the user had entered any information into any of the fields?
4. How do we get the next error message to appear on the next line down?
Summary
Objectives
• Understanding the image object
• Learning Mouse-over effects
• To create flexible functions
• Understand how to pre-load images
• To work with eval function
Image Object
When you add the HTML tag <IMG> to your web page you are creating an image object. For example:
<IMG SRC="gifs/mouse_out.gif">
The image objects on your page can be referenced as an array, where document.image[0] refers to the
first image on the page, and document.image[1] the second and so on. If you add the NAME attribute to
the <IMG> tag we can use the value of the NAME attribute to reference the image object. For example:
This image object can be referenced as document.image['mouse1']. Remember that JavaScript is case
sensitive and "mouse1" is different from "Mouse1" or "MOUSE1".
document.images['imagename'].property = newvalue;
border
This value can only be read, and is the width of the border around the image specified in pixels by the
BORDER attribute.
complete
This value can only be read, and is a Boolean value that will let you know if the image has completed
downloading (true) or not (false).
height
This is a read only value that specifies the height in pixels of image set by the HEIGHT attribute.
hspace
This is a read-only value, and refers to the space on the right and left of the image specified in pixels
by the HSPACE attribute.
lowsrc
This is a read/write string that specifies a URL of an alternate image. The image should be suitable for
display at low resolutions; it is specified by the LOWSRC attribute.
name
This is a read-only value, specified by the NAME attribute. As you will see it is a good idea to name your
images.
src
vspace
This is a read-only value, and refers to the space on the top and bottom of the image specified in pixels
by the VSPACE attribute.
width
Training & Development Division Page 233 of 282
HTML, DHTML & JavaScript
This is a read only value that specifies the width in pixels of image set by the WIDTH attribute.
Since we can read and write to the src property, we can change the image that is displayed in the
browser. This is what allows us to create mouse roll-over, sometimes called hover buttons, when used
in combination with the <A> element in creating links.
Mouse-over
In the mouse rollover script that we will create, we will be changing the src property of the
appropriate image object when the onMouseOver and onMouseOut events are triggered. We will start
with a very basic and simple implementation and then add to it to make it more flexible and powerful.
To create the effect we need two graphic images that are generally the same with a little bit of
difference for example mouse_out.gif and mouse_over.gif, both located in the \gifs subdirectory of
your student files.
The following HTML page codes with the addition of the JavaScript events will change the image when
the user positions their mouse over the image and change it back again when they move their mouse
off the image. The image is originally set to the mouse off image using the <IMG> tag.
<HTML>
<HEAD>
<TITLE>Mouse Over and Mouse Out</TITLE>
</HEAD>
<BODY>
<a href="http://www.lntinfotech.com/Projects/"
onMouseOver="mouse1.src='gifs/mouse_over.gif'; "
onMouseOut="mouse1.src='gifs/mouse_out.gif'; ">
<IMG name="mouse1" src="gifs/mouse_out.gif" border=0></A>
</BODY>
</HTML>
To improve our mouse over script we want to start by creating two functions. One that will be called
when the mouse is on the image, and one that is called when the mouse is off the image.
<HTML>
<HEAD>
<TITLE>Web Page containing JavaScript</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function MouseOn() {
document.images['mouse1'].src = "mouse_over.gif";
function MouseOff() {
document.images['mouse1'].src = "mouse_out.gif";
</SCRIPT>
</HEAD>
<BODY>
<a href=" http://www.lntinfotech.com/Projects/"
onMouseOver="MouseOn(); "
onMouseOut="MouseOff(); ">
As you can see in the above code you have added two functions that do the same thing as the inline
script did in the previous example, and you have changed the event triggers to call your new functions.
This provides you with the flexibility to apply your function to different images.
Next we want to add an argument to our functions so that they will accept the name of the image we
want to change. We will then combine the image name with a standard file extension to make our
function work for any number of buttons.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function MouseOn(imageName) {
document.images[imageName].src = "gifs/mouse_over.gif";
function MouseOff(imageName) {
document.images[imageName].src = "gifs/mouse_out.gif";
</SCRIPT>
</HEAD>
<BODY>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="MouseOn('mouse1'); "
onMouseOut="MouseOff('mouse1'); ">
<BR>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="MouseOn('mouse2'); "
onMouseOut="MouseOff('mouse2'); ">
</BODY>
</HTML>
In this example we pass the value "mouse1" or "mouse2" to our functions. This value in turn gets stored
in the variable "imageName". Next we want to focus our attention on the string that is equated to the
image name. The string "gifs/mouse_out.gif" is not very flexible. We need to express that as:
The line above will create the correct string value for each set of images to change.
At this point we will need four (4) graphic images; mouse1_over.gif, mouse1_out.gif, mouse2_out.gif
and mouse2_over.gif.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function MouseOn(imageName) {
function MouseOff(imageName) {
</SCRIPT>
</HEAD>
<BODY>
<a href="http://synergy.simplenet.com/simpsons/"
Training & Development Division Page 236 of 282
HTML, DHTML & JavaScript
onMouseOver="MouseOn('mouse1'); "
onMouseOut="MouseOff('mouse1'); ">
<BR>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="MouseOn('mouse2'); "
onMouseOut="MouseOff('mouse2'); ">
</BODY>
</HTML>
Although the above example will work and create the flexibility that you require, it is not optimized.
When the browser loads this page it only loads the two mouse out images. When the user positions the
mouse over the image for the first time the browser must download the mouse over image. This can be
slow and your effect will not display properly. The solution is to pre-load all of your images into the
browser's cache so that they can be accessed quickly.
Pre-loading Images
In previous example we had only two image objects mouse1, and mouse2 respectively. We are going to
create four more, and pre-load them into our browser's cache.
You can pre-load all four of your images files in to the browser's cache by creating four new objects
mouse1_on, mouse1_off, mouse2_on, mouse2_off. These image objects are not displayed in the
browser. You will be using them to hold the images so that you can quickly switch between them. Let's
look at an example of how to do this:
mouse1_off.src = "gifs/mouse1_out.gif";
mouse1_on.src = "gifs/mouse1_over.gif"
For each image file, we create a new image object, and set its src attribute to the appropriate
filename. In setting this property, the browser decides it needs to download the image file, at which
point it is stored in the cache for quick retrieval, when it is called for display.
Our page will now contain six image objects: mouse1, mouse1_on, mouse1_off, mouse2, mouse2_on,
and mouse2_off.
To make the image change in the browser you need to make the src attribute of the image object
created by the <IMG> tag in our case mouse1 or mouse2 equal to on objects src or the off objects src.
You can reference the two image objects created by the HTML <IMG> tag as follows:
document.images['mouse1'] or document.images['mouse2']
We want to be able to set those images src attribute equal to one of the other objects src attributes.
document.images['mouse1'].src = mouse1_on.src
or
document.images['mouse1'].src = mouse1_off.src
Notice in the above example, to make it work for mouse2 you would just have to substitute mouse2 for
mouse1. So for your function we will substitute the mouse1 reference with a variable called
imageName.
or
From earlier in the course you will know that JavaScript is going to try to concatenate (join) the string
value of the imageName variable with the other string component to form the object name
mouse1_on.src or mouse1_off.src.
If you tried to do it this way it wouldn't work because what the JavaScript interpreter would be trying
to make the src parameter equal to mouse1_on.src for example. This appears to sound ok, except the
src parameter is expecting a URL for the image, NOT a string. To get around this you will us a special
function in JavaScript called eval().
eval()
The order of operations that is followed this time is that the value of the imageName variable is
concatenated with the string, to form one string like mouse1_on.src. The eval function then converts
that to JavaScript code, meaning that it converts to the reference to the object we created in our pre-
loading phase and it's src parameter. This way we are making the src parameter of one object equal to
the src parameter of another image object. This effectively flips the object in the browser.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
mouse1_off.src = "gifs/mouse1_out.gif";
mouse1_on.src = "gifs/mouse1_over.gif"
mouse2_off.src = "gifs/mouse2_out.gif";
mouse2_on.src = "gifs/mouse2_over.gif"
function MouseOn(imageName) {
function MouseOff(imageName) {
</SCRIPT>
</HEAD>
<BODY>
<a href="http://project.lntinfotech.com/Category/"
onMouseOver="MouseOn('mouse1'); "
onMouseOut="MouseOff('mouse1'); ">
<BR>
<a href="http://project.lntinfotech.com/Category/"
onMouseOver="MouseOn('mouse2'); "
onMouseOut="MouseOff('mouse2'); ">
</BODY>
</HTML>
You should add two more pieces to your script, a test to make sure the image is completely
downloaded and to make sure that the browser supports the image object. You will start by testing for
completion.
function MouseOn(imageName) {
You want to use the image object's complete property to test to see that the image has been
completely downloaded before you try to change to it so the user will never see a partially loaded
image. Similar to the use of the eval in the previous section, here we want to combine the value of the
imageName variable with the string "_on.complete" to create the complete image name and property,
and have JavaScript act on the object instead of the string.
Next you will test for compatibility. You can do this very simply by testing the browser to see whether
it supports the image object. Earlier browsers like Microsoft Internet Explorer 3.0, and earlier did not
support this object. To make your code browser proof you will add this conditional statement to your
code.
…do stuff…
You need to add this to both of your functions, and to the pre-loading piece of your code.
Completed Script
<HTML>
<HEAD>
<TITLE>Web Page containing JavaScript</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
if (document.images) { // if browser supports images
//Preload our images
function MouseOn(imageName) {
if (document.images) { // if browser supports images
if( eval(imageName + "_on.complete") ) { //is the image completely downloaded
document.images[imageName].src = eval( imageName + "_on.src" );
function MouseOff(imageName) {
if (document.images) { // if browser supports images
if( eval(imageName + "_on.complete") ) { //is the image completely downloaded
document.images[imageName].src = eval( imageName + "_off.src" );
</SCRIPT>
</HEAD>
<BODY>
<a href="http://project.lntinfotech.com/Category/" onMouseOver="MouseOn('mouse1'); "
onMouseOut="MouseOff('mouse1'); ">
<IMG name="mouse1" src="gifs/mouse_out.gif" border=0></A>
<BR>
<a href="http://project.lntinfotech.com/Category/" onMouseOver="MouseOn('mouse2'); "
onMouseOut="MouseOff('mouse2'); ">
<IMG name="mouse2" src="gifs/mouse_out.gif" border=0></A>
</BODY>
</HTML>
Review Questions
1. What two events are used to create the mouse roll-over effect?
2. What properties of the image object can you read and write?
6. What would you need to add to our script to get it to work with more than two links?
Summary
We can use the image object to work with images inside javaScript
files. Use the onMouseOver, and onMouseOut events to do specific
operations. Here we can create a flexible mouse rollover function.
Pre-loading of our images is required so that after loading images thogh
there is no connection then we can still work with those images. The
eval function is used to evaluate arithmetic expressions. We have to
test for image download completion and browser compatibility so that
we can start working with Images.
Objectives
• To create Pop-up windows
o Using window.open method
o Using window.close method
• Explaining the window features
• To set the document colours
Pop-up Windows
In this chapter you are going to use the window object and the open and close methods. This particular
programming technique can be put to good use or it can be misused. A good use is to highlight a
product a customer may be interested in.
Arguments:
URL
Name
an optional string that specifies the name property that can be used with the target attribute.
Features
Replace
Optional boolean argument, that states weather the page that gets loaded gets added to the page
history in the browser. This argument was intended for use when changing the contents of a window.
window.close()
status (status bar): the line at the bottom of the browser that displays information. To display a
window with no status bar, set status=no.
location: shows the URL of the page you are looking at. To turn the location bar off, location=no.
toolbar: contains the buttons you use to move through history (back, and forward) to stop web page
loading, etc. To display a window with no toolbar, set toolbar=no
menubar: is the bar that has all of the drop down menus. To turn the menubar off, menubar=no.
scrollbars: are the sliders on the right hand side and bottom of a window that let you move up or down
and left or right. To turn off the scrollbars, scrollbars=no.
left, and screenX: control the window's position from the left of your screen in pixels. Left is used by
Internet Explorer and screenX is used by Navigator.
top, and screenY: control the windows position from the top of your screen in pixels. Top is used by
Internet Explorer and screenY is used by Navigator.
The following feature string sets the height to 500 pixels, width to 400, and turns off the menubar,
scrollbars, status line, and the toolbars, and positions the window at the top of the screen one hundred
pixels from the left of the screen.
It is very common to see popup windows displayed with all of the features turned off.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function popupwin() {
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="FORM1">
</FORM>
</BODY>
</HTML>
This line will create a new window, and load the file latestNews.html into that window. The name of
the window is set to "popup". The window will have the following features:
• no menubars
• the scrollbars
• a status line
• the toolbars
The window will also be located zero pixels from the top of the screen and 100 pixels from the left of
the screen. Remember, Microsoft Internet Explorer uses the left and top features, while Netscape
Navigator uses screenX and screenY.
If you open up the file latestNews.html you will notice that we used a similar structure to create a
close window button.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function closewin() {
window.close();
</SCRIPT>
</HEAD>
<BODY>
<H1>You called!</H2>
<IMG SRC="./gifs/teddy.jpg">
<FORM NAME="FORM1">
</FORM>
</BODY>
</HTML>
The first thing you need to modify is the window.open statement so that it does not load a particular
page. We can accomplish this by replacing the file 'latestNews.html' with a single double quote mark,
as illustrated:
winpopup = window.open('','popup','height=500,width=400,
menubar=no,scrollbars=no,status=no,toolbar=no,
screenX=100,screenY=0,left=100,top=0');
To create the actual HTML page that will appear in our pop-up window you need to use the
document.write() method. This method allows you to write text to the specified document. For
example:
winpopup.document.write('<HTML>\n<HEAD>\n');
This line will start the creation of your HTML document in the window identified by the winpopup
window object. You would need to create the whole HTML document like this. For example:
winpopup.document.write('<HTML>\n<HEAD>\n');
winpopup.document.write('<TITLE>This is a popup</TITLE>\n');
winpopup.document.write('</HEAD>\n');
winpopup.document.write('<BODY>\n');
winpopup.document.write('</BODY>\n</HTML>\n');
This will create an empty document in the new pop-up window. When you are finished writing
information to the new window you should let the browser know that nothing more is coming, you can
do that with the document.close() method which would be added after the lines above. Your code
should look like this:
function popupwin() {
winpopup.document.write('<HTML>\n<HEAD>\n');
winpopup.document.write('<TITLE>This is a popup</TITLE>\n');
winpopup.document.write('</HEAD>\n');
winpopup.document.write('<BODY>\n');
winpopup.document.write('</BODY>\n</HTML>\n');
Training & Development Division Page 248 of 282
HTML, DHTML & JavaScript
Now that you have the window opening and displaying an empty HTML page you should make it do
something a little more creative. You want your pop-up window to thank your customer for purchasing
a product. To start you need to add a text input field to your form.
<BODY>
<FORM NAME="FORM1">
</FORM>
</BODY>
To get "Mr. JavaScript" to display in your window you need to add the following line to your script:
This line will combine the strings with the value typed in by the user, and should be located in your
script between the lines that write the BODY tags.
You should also give the user, the ability to close this newly created pop-up window. To accomplish
this you will add the following lines after the one above.
winpopup.document.write('<FORM NAME="FORM1">\n');
winpopup.document.write('</FORM>\n');
This will create a button called "Close Window" that when clicked will close the current browser
window.
The background color can be changed at any time. This allows you to create some interesting effects in
your popup window. The text color can only be set once after the body tag has been written to the
document (see the completed code). An example of using these properties is below.
winpopup.document.fgColor = "#FFC814";
Complete Script
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function popupwin() {
winpopup.document.write('<HTML>\n<HEAD>\n');
winpopup.document.write('</HEAD>\n');
winpopup.document.write('<BODY>\n');
winpopup.document.bgColor = "#0000FF";
winpopup.document.fgColor = "#FFC814";
winpopup.document.write('<FORM NAME="FORM1">\n');
winpopup.document.write('</FORM>\n');
winpopup.document.write('</BODY>\n</HTML>\n');
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="FORM1">
</FORM>
</BODY>
</HTML>
Review Questions
1. What are the two methods used with popup windows?
3. (True or False) You can not control the size of a popup window.
4. (True or False) It is not common to see popup windows displayed with all of the features turned
off.
Summary
Objectives
• To understand cookie
• Understanding how to save a JavaScript cookie
• To Retrieve a JavaScript cookie
• Understanding how to delete cookies
Introduction to cookies
A cookie is simply a variable that your webpage can store on or retrieve from the user's computer.
The idea is that the next time the user arrives at your page, the value of the cookie can be read by
your page, and then used for whatever purpose you choose.
• First time the visitor arrives the name is entered. (for example "Sam Smith"). The username is
then stored in a cookie. Next time he arrives at your page, it writes something like:
"Welcome to my page Sam Smith!!
Good to see you again".
The name is simply retrieved from the stored cookie.
• First time the user arrives at your page she enters the desired language.
The chosen language is stored in a cookie.
Next time she visits your site, she will simply be taken to the pages in the desired language
without asking, since the desired language is retrieved from the cookie.
• First time the user arrives at your page he is asked to fill in a password.
The password is saved in a cookie.
Next time he arrives at your page, the password is retrieved from the cookie.
Cookie Limits
Users have good reason to be wary of force-fed cookies from strange servers.
It is important to note, however, that the potential for abuse is limited in the following ways:
• The file that maintains the cookie on the client machine may contain not more than 300
individual cookies.
• Whenever a new cookie is saved to a file that is at the 300-cookie limit, the least recently
accessed cookie is deleted.
• A single site may post not more than 20 cookies to any client’s file
• Individual cookies may be no larger than 4 kilobytes (including ID information placed in the
cookie by the browser).
A cookie is a small piece of information stored by the web browser on the client machine in a text
(.txt) file which can be retrieved later. A script/program either on server side or client side may
request the web browser to store a cookie. Cookie information is stored as a name value pairs.
JavaScript provides document.cookie property for manipulation of a client-side cookie. One can set the
cookie property at any time. Cookies can be very useful for -
• State Maintenance/Persistence across different pages of the site, for HTTP is a state less
protocol. In english, it means cookies can be used for "remembering" certain data specific to
the user (such as User ID) as he browses different pages of the site. Session variables used in
server side scripts such as ASP make use of cookies for this purpose.
As you must have noticed by now, the important steps in cookie manipulation are -
• Create A Cookie - Create or set a cookie on user machine having cookie name, cookie value
and the time when cookie should get deleted automatically (EXPIRES atribute, this is optional).
If this is not specified the cookie is called a session cookie and it expires (gets deleted) when
user's session ends, i.e. when the browser is closed. The additional information that can be
optionally stored in the cookie includes (1)Path, (2)Domain, (3)Secure. Secure is used only over
a secure communication channel ( currently only HTTPS).
• Read The Cookie - Read the stored cookie and extract its value. This requires only cookie
name. Remember that you can only read the cookie which is created by your script/program.
• Delete The Cookie - This may not be always done, as expires attribute takes care of it. To
delete a cookie set/create a cookie with the exactly same PATH (if any) and NAME values, and
an EXPIRES value which is in the past.
The JavaScript code here lets you manipulate cookies by using three functions to do above mentioned
tasks. For creating a cookie, for reading a cookie and for deleting a cookie. The function prototypes
and usage -
1. szExpires - A Date object specifying the date on which the cookie expires.
3. szDomain - A string argument specifying the domain attribute for this cookie.
4. bSecure - A boolean value (true/false), if this cookie is meant for communication over
a secure channel, for HTTPS cookies only.
This function creates a cookie string from the given arguments (by URL encoding name=value
attributes), and sets the cookie as -
document.cookie = szCookieText; //constructed cookie string
• function getCookie(szName) - To read the cookie set by setCokie(...) function. The only
argument which it takes is the cookie name szName, which is set by the previous function. This
function returns the cookie value read, which can be parsed if necessary, to get the required
data.
This function simply parses document.cookie for the given cookie name, and returns the
extracted cookie value in the original format (by URL decoding the value).
• function deleteCookie(szName) - You can use this function optionally to delete the cookie. It
takes only one parameter cookie name, szName and deletes the cookie immediately.
This function simply sets the same cookie with an expires attribute which is in the past, thus
deleting it immediately irrespective of the original expires attribute.
You can include these functions in your HTML file(s), to create and read cookies easily by calling these
functions without any modification.
<HEAD>
<TITLE>Cookies Demo</TITLE>
<SCRIPT language="JavaScript">
<!--
function getVal()
alert(szName);
alert(szCookieText)
document.cookie = szCookieText;
function getCookie(szName)
szValue = unescape(arr2[0]);
return szValue;
function deleteCookie(szName)
if(tmp)
{ setCookie(szName,tmp,(new Date(1))); }
-->
</SCRIPT>
Training & Development Division Page 259 of 282
HTML, DHTML & JavaScript
</HEAD>
<BODY>
<H2>Cookies Demo<H2>
<FORM NAME="FORM1">
onClick="setCookie('firstName','Sam',nextMonth);">
</FORM>
</BODY>
</HTML>
This will set a cookie named 'firstName' with value 'Sam' on the user machine which expires one month
after its creation. It uses only 3 arguments of the available 6 ones.
In this code snippet, the variable szName will contain the value of the cookie named 'firstName' which
has been set earlier. This variable can be later used as required.
In your case
It simply calls the deleteCookie() function with the cookie name 'firstName' to delete the cookie.
Although cookies are very useful for all these reasons and perhaps more, here are few things you should
know.
• The browser or user can delete cookies before it expires.
• Many people can share one machine and one person can use multiple machines, so cookies are
not always reliable completely.
• Do not rely only on cookies for state maintenance/persistence, support it with server side as
well.
Review Questions
1. A variable that your webpage can store on or retrieve from the user’s computer is known as
___?
a. Java
b. Cookie
c. Applet
7. The best time to read a cookie is
a. onBlur
b. onLoad
c. onSelect
d. onChange
8. The expiration date is stored in a cookie as
a. A GMT string
9. State True of False. Your JavaScript actually writes a cookie to a visitor’s hard disk if you set
an expiration date for the cookie.
a. True
b. False
a. Pair-name value
b. Pair-value name
c. Value-name pair
d. Name-value pair
Summary
A cookie is simply a variable that your webpage can store on or retrieve from the user's
computer. Cookies can be use in application like showing visitor counter, welcome user
based on previous visits, setting default language so that it will not ask next time. We
can have maximum 20 cookie pages on per client machine. The maximum size of
individual cookie file cannot exceed more than 4 Kilo Byte. After creating cookies
depends on requirements either you can read cookie values or can delete cookies. Its
advisable to create different functions to write cookie, read cookie and delete cookies.
Objectives
• To understand objects in Document Object Model
History Object
The History object is predefined object which can be accessed through the history property of the window.
The History object consists of an array of URLs. These URLs the user has visited within a browser window.
Properties
Syntax: history.Property_name
Property Description
length Returns the number of elements in the history
Methods
Syntax: history.Method_name()
Method Description
back() Loads the previous URL in the history list(same as clicking
The back button and to history. go (1)
forward() Loads the next URL in the history list (same as clicking the
Forward button and to history. go (1)
go(number/ “URL”) Loads a specified URL from the history list
Navigator Object
The Navigator object contains information about the client browser.
The Navigator object’s collection, properties and method are described below:
Collections
Collections Description
plugins[] Returns a reference to all embed object in the document
Properties
Syntax: object. Property_ name
Property Description
appCodName Returns the code name of the browser
appMinorVersion Returns the minor version of the browser
appName Returns the name of the browser
appVersion Returns the platform and version of the browser
browserLanguage Returns the current browser language
cookieEnabled Returns a Boolean value that specifies whether cookies are
enabled in the browser
cpuClass Returns the CPU class of the browser’s system
onLine Returns a Boolean value that specifies whether the system is
in offline mode (In 4+ the user can choose to work offline by
Selecting file/work offline in the browser. When work offline is
selected, the system enter an offline state, and content is
read from the cache)
platform Returns the operating system platform
systemLanguage Returns the default language used by the OS
userAgent Returns the value of the user-agent header sent by the client to
Methods
Syntax: object.method_name()
Method Description
javaEnabled() A Boolean value that specifies whether the browser has
Java enabled
taintEnabled() A Boolean value that specifies whether the browser has
data tainting enabled
Document Object
The Document object is used to access all elements in a page. The Document object’s collection,
Properties, methods, and events are described below:
Collection
Collection Description
anchors[] Returns a reference to all anchor object in the document
applets[] Returns a reference to all applet object in the document
attributes[]
childNodes
embeds[] Returns a reference to all embedded object in the document
forms[] Returns a reference to all from object in the document
images[] Returns a reference to all image object in the document
links[] Returns a reference to all Link object in the document
plugins[]
sylesheets[]
Properties
Syntax: document.Property_name
Property Description
alinkColor Sets or returns the color of the active link in the documents
bgColor Sets or returns the background-color of the documents
body Specifies the beginning and end of the documents body
cookie Sets or returns all cookies associated with the document
documentElement Returns a reference to the root node of the documents
domain Return the documents server’s domain name
fgColor Sets or returns the text-color of the document
lastModified Returns the date and time the document was last modified
linkColor Sets or returns the color of the links in the documents
referrer Return the URL of the document that loded the current
document
title Returns the title of the document (text inside the HTML
Title elements
URL Returns the URL of the current document
vlinkColor Sets or returns the color of the visited link in the document
Methods
Syntax: documents.Method_name()
Method Description
clear() Clears all elements in the document
close() Close the output stream and display the sent data
createAttribute(“name”) Creates an attribute with a specified name
createElement(“tag”) Creates an element
createTextNode(“txt”) Creates a text string
focus() Gives the document focus
getElementById(“id”) Returns a reference to the first object with specified ID
getElementsByName(“name”) Returns a collection of object with the specified NAME
getElementsByTagName(“tag”) Returns a collection of object with the specified TAGNAME
open(“mimetype”[,replace]) Open a document for writing. If a document exist in the targ-
Training & Development Division Page 266 of 282
HTML, DHTML & JavaScript
Events
Syntax: document.event-name=”someJavaScriptCode”
Event Description
onClick Executes some code when a click event occurs
onDblClick Executes some code when a Doubleclick event occurs
onFocus Executes some code when a focus event occurs
onKeyDown Executes some code when a Keydown event occurs
onKeyPress Executes some code when a KeyPress event occurs
onKeyUp Executes some code when a KeyUp event occurs
onMouseDown Executes some code when a Mousedown event occurs
onMouseMove Executes some code when a Mousemove event occurs
onMouseOut Executes some code when a Mouseout event occurs
onMouseOver Executes some code when a Mouseover event occurs
onMouseUp Executes some code when a Mouseup event occurs
onResize Executes some code when a Resize event occurs
Example:
<script language=”javascript”>
functions getElement ()
{
var x=document.getElementByld(“myHeader”);
alert(“I am “ + x.tagName + ”element”)
}
</script>
Window Object
The Window object corresponds to the browser window. A Window objects is created automatically with
every instance of a <body> or <frameset> tag
The Window object’s collection, object, properties, method, and events are described below:
N: Netscape (including Mozilla when N6 or higher), Internet Explorer
Collection Description
frames[] Returns all named in the window
Object
Object Description
clientInformation Contains information about the browser
document Represents the HTML document object in the window
event Represents the state of an event
external
history Contains the URL visited from the window.
location Contains the current URL of the window.
navigator Contains information about the browser.
screen Contains information about the client’s screen
Properties
Syntax: window.Property_name
Property Description
closed Returns a Boolean value that specifies whether the
Training & Development Division Page 267 of 282
HTML, DHTML & JavaScript
Methods
Syntax: window.Method_name()
Method Description
alert(“msg”) Displays an alert box with a massage and an OK button
attachEvent(“event”;pointer)
blur() Removes focus from the current window
clearInterval(ID) Cancels a timeabout that is set with the setInterval()
Method
clearTimeout(ID) Cancels a timeabout that is set with the setInterval()
Method
close() Closes the current window
confirm(“msg”) Displays a dialog box with a massage, a cancel, and an OK
Button
createPopup([args}) Creates a pop-up window
execsScript(“code”;”lang”) Executes a specified script. The arguments can take the
Following values:
showHelp(“URL”[,contextID]) Displays a Help file (must be of type .htm or chm). When using this
Method , a second Help box appears when pressing F1 OR when
clicking Help on the menu bar. To prevent the default help box from
appearing set return Value to false. The argument can take the
following values
URL Required. The URL of a Help file
contextID Optional A string or integer that specifies a context identifier
Fier in the Help file
showModelDialog(“URL”[, args, Loads a URL in a model dialog box. A model dialog box retain focus
“list”]) while open. The user CANOT switch windows until the dialog box is
closed. The argument can take the following values:
“list” –Optional. Specifies the windows ornaments for the dialog box,
Args – Optional. The argument to use when displaying the URL. Use
This parameter to pass a value of any type, including an array of
Values. The dialog box can extract the values from the dialog
Arguments property of the window object.
“list” – Optional. Specifies the window ornaments for the dialog box.
Events
Syntax: window.Event_name=”someJavaScriptCode”
Event Description
onBlur Executes some code when a Blur event occurs
onError Executes some code when an Error event occurs
onFocus Executes some code when a focus event occurs
onLoad Executes some code when an Load event occurs
onResize Executes some code when a Resize event occurs
onUnload Executes some code when an Unload event occurs
Examples of window Object
Ex.1:
<script language=”JavaScript”>
function timeout()
{
setTimeout(“alert(‘This alert box popped up 1 second after you clicked the button’)”,1000);
}
</script>
Ex.2:
<script language=”JavaScript”>
function timeout()
{
Training & Development Division Page 270 of 282
HTML, DHTML & JavaScript
window.setTimeout(“change_text(document.All(‘t’)”,3000);
}
function change_text(tid)
{
tid.style.color=”red”;
}
</script>
Form Object
From are used to prompt users for input. We may use form elements such as text fields, radio buttons,
check boxes and selection lists. The input data is normally posted to a server for processing.
The From Object’s collections, properties, method, and events are described below:
Collection
Collection Description
elements[] Returns an array containing each element in the form
Properties
Syntax: object.property_name
Property Description
acceptCharset Sets or returns a list of character encoding for form
data that must be accepted by the server processing the
form
action Sets or returns the URL of the input data will be
submitted
encoding Sets or returns the MIME encoding for the form
enctype Sets or returns the MIME encoding for the form
id Sets or returns the id of the form (In IE 4 this property
Is read-only)
length Returns the number of elements in form
method Sets or returns how form data is submitted to the server
(“get” or “post”)
name Sets or returns the name of the form
tabIndex Sets or returns the index that defines the tab order for
the form
target Sets or returns the target window of frame that respon-
ses are sent to after submission of a form
Methods
Syntax: object.method_name()
Method Description
reset() Resets the default values of elements in the
Form(same as clicking the Reset button)
submit() Submit the form (same as clicking the
Submit button)
Events
Syntax: object.event_name=”someJavaScriptCode”
Event Description
onReset Executes some code when a Reset event
occurs
Location Object
The Location object contains information about the current URL.
Note: The location object is not W3C standard.
The Location object’s properties and method are described below
Properties
Syntax: object.property_name
Property Description
hash Sets or returns the part of the href property
that follows the hash sign (#)
host Sets or returns the hostname and port number
of the location or URL
hostname Sets or returns the hostname of the location
or URL
href Sets or returns the entire URL
pathname Sets or returns the file name or path specified
By the location object
port Sets or returns the port number associated
With the URL
protocol Sets or returns the protocol part of the URL
search Sets or returns the part of the href property
that follows the question mark (?)
Methods
Syntax: object.method_name()
Method Description
assign(“URL”) Loads a new document
reload(false|true) Reloads the current document
replace(“URL”) Replaces the current document with the one
specified
Image Object
The image object represents an HTML img element.
For each instance of an HTML <img> tag in document an image object is created
The Image object’s properties and events are described below:
Properties
Syntax: object.property_name
Property Description
align Sets or returns how to align the image
According to the surrounding text
alt Sets or returns an alternate text to write if
The image cannot be displayed
border Sets or returns the width of the border of the
Image in pixels
complete Returns Boolean value that indicates whether
or not the browser is finished loading the
image
height Sets or returns the value of the height
attribute of the <img>tag in pixels
hspace Sets or returns the value of the hspace attribute
of the <img>tag in pixels
id Sets or returns the id of the image (In IE 4
This property is read-only)
isMap Sets or returns a Boolean value that specifies
If the image is a server side image map
longDesc Sets or returns URL for a long description of
The image
lowsrc Sets or returns a URL to low-resolution
Version of the image (for clients with low-
resolution
name Sets or returns the value of the name attribute
Of the <img>tag
src Sets or returns the URL of the image (This
Property can be change at any time. However,
,the new image is scaled to fit the height and
width attribute of the first image
Methods
Syntax: object.method_name()
Method Description
blur() Removes focus from the image
click() Simulates a mouse-click on the image
focus() Gives focus to the image
Events
Syntax: object.event_name=”someJavaScriptCode”
Event Description
onAbort Executes some code when a user abort the
download of an image
onBlur Executes some code when the image loses
focus
onClick Executes some code when an a user clicks
On the image
onError Executes some code when an Error occurs
onFocus Executes some code when the image gets
Focus
onLoad Executes some code when the image load
Ex:
<script language=”JavaScript”>
function setSrc()
{
var x=document.images;
x[0].src=”hackanm.gif”;
}
</script>
Array Object
The Array object is used to store a set of values in single variable name. Each value is an element of
the array and has an associated index number.
You create an instance of the Array object with the “new” keyword. The following example creates
two arrays, both of three elements each:
You can refer to a particular element in the array by using the name of the array and the index
number. The index number starts at 0.
If you create an array with a single numeric, you can assign data each of the elements in the array like
this:
family_names[0]=”Tove”;
family_names[1]=”Jani”;
family_names[2]=”Stale”;
And the data can be retrieved by using the index number of the particular array element you want, like
this:
mother=family_names[0];
Properties
Syntax: object.property_name
Property Description
constructor Contain the function that created an object’s
prototype
length Returns the number of elements in the array
prototype Allows you to add properties to an array
Methods
Syntax: object.property_name()
Method Description
concat() Joins two or more arrays and returns a new
array
join(delimiter) Puts all the elements of an array into a string
separated by a specified delimiter(comma is
default)
pop() Removes and returns the last element of an
array
push(“element1”,”element2”) Adds one or more elements to the end of an
array and returns the new length
reverse() Reverse the order of the elements in an array
shift() Removes and returns the first element of an
array
slice(begin[,end]) Create new array from a selected section of
an existing array
sort() Sort the elements of an array
splice(index,howmany[,e11,e12]) Adds and /or removes elements of an array
toSource() Returns a string that represent the source
code of the array
toString() Returns a string that represent the specified
array and its elements
unShift(“element1”,”element2”) Adds once or more elements to the beginning
of an array and returns the new length
valueOf() Returns the primitive value of an array
Example:
<html>
<body>
<script language=”JavaScript”>
var famname =new Array(3);
famname[0] =”Jani”;
famname[1] =”Tove”;
famname[2] =”Hege”;
document.write(famname.length +”<br>”);
document.write(famname.join(“.”) +”<br>”);
document.write(famname.reverse() + “<br>”);
document.write(famname.push(“Ola”,”Jon”) +”<br>”);
document.write(famname.pop() + “<br>”);
document.write(famname.shift() + ”<br>”);
</script>
</body>
</html>
Date Object
The Data object is used to work with date and time of client browser.
To create an instance of the Date object and assign it to variable called “d”, you have to do the
following declaration:
After creating an instance of the Date object, you can access all the methods of the date object from
the “d” variable.
To return the current day in a month (from 1-31) of a Date object, write the following:
d.getDate();
If you only use Date(), JavaScript creates an object for today’s date according to the time on the local
machine.
Here are some examples on how to create Date object:
var d=new Date(“October 12, 1988 13:14:00”)
var d=new Date (“October 12, 1988”)
var d=new Date(88, 09,12,13,14,00)
var d=new Deat(88, 09,12)
Properties
Syntax: object.property_name
Property Description
constructor Contain the function that created an object’s
prototype
prototype Allows addition of properties to a date
Methods
Syntax: object.method_name()
Method Description
Date() Returns a Date object
getDate() Returns the date of a Date object (from 1-31)
getDay() Returns the day of a Date object (from 0.6.
0=Sunday, 1=Monday, etc.)
getMonth() Returns the month of a Date object (from 0-
11. 0=January,1=February, etc.)
getFullYear() Returns the years of Date object(four digits)
getYear() Returns the year of a Date object (from 0-99).
Use getFullYear instead!!
getHours() Returns the hour of a Date object (from 0-23)
getMinutes() Returns the minute of a Date object (from 0-
59)
getSeconds() Returns the minute of a Date object (from 0-
59)
getMilliseconds() Returns the milliseconds of a Date
object(from 0-999)
getTime() Returns the number of milliseconds since
midnight 1st Jan. 1970
getTimezoneOffset() Returns the time difference between the
user’s computer and GMT
getUTCDate() Returns the date of Date object in
universal(UTC)time
getUTCDay() Returns the date of Date object in universal
time
getUTCMonth() Returns the date of Date object in universal
time
getUTCFullYear() Returns the four-digit year of a Date object in
universal time
getUTCHours() Returns the hours of Date object in universal
time
getUTCMinutes() Returns the minutes of a Date object in
universal time
getUTCSeconds() Returns the seconds of a Date object in
universal time
getUTCMilliseconds() Returns the milliseconds of a Date object in
universal time
parse() Return a string date value that holds the
number of milliseconds since January 01 170
00:00:00
setDate() Sets the date of the month in the Date
object(from 1-31)
setFullYear() Sets the year in the Date object(four digit)
setHours() Sets the hours in the Date object(from 0-23)
setMilliseconds() Sets the milliseconds in the Date object(from
Training & Development Division Page 277 of 282
HTML, DHTML & JavaScript
0-999)
setMinutes() Set the minute in the Date object (from 0-59)
setMonth() Sets the month in the Date object (from 0-11.
0=January, 1=February)
setSeconds() Sets the seconds in the Date object(from 0-59)
setTime() Sets the milliseconds after1/1-1970
setYear() Sets year in the Date object (00-99)
setUTCDate() Sets the date in the Date object, in universal
time (from 1-31)
setUTCDay() Sets the day in the Date object, in universal
time (from 0-6. Sundy=0, Monday=1, etc.)
setUTCMonth() Sets the month in the Date object,in universal
time (from 0-11. 0=January, 1=February)
setUTCFullYear() Sets the year in the Date object, in universal
time(four digits)
setUTCHours() Sets the hour in the Date object, in universal
time(from 0-23)
setUTCMinutes() Sets minutes in the Date object, in universal
time(from 0-59)
setUTCSeconds() Sets the seconds in the Date object, in
universal time(from 0-59)
setUTCMilliseconds() Sets the milliseconds in the date object, in
universal time (from 0-999)
toGMTString() Converts the Date object to a string, set to
GMT time zone
toLocaleString() Converts the Date object to a string, set to
the current time zone
toString() Converts the Date object to a string
Example:
<html>
<head>
<script language=”JavaScript”>
var timer=null;
function stop()
{
clearTimeout(timer);
}
function start()
{
var time = new Date();
var hours = time.getHours();
var minutes =time.getMinutes();
minutes=((minutes< 10)? “0” :””) + minutes;
var seconds =time.getSeconds();
seconds=((seconds< 10) ? “0” : “”) + seconds;
var clock =hours + ”:” + minutes + “:” + seconds;
document.forms[0].display.value = clock;
timer = setTimeout(“start()”,1000);
}
</script>
</head>
<body onload=”start()” onunload=”stop()”>
<form>
<input type=”text” name=”display” size=”20”>
</form>
Training & Development Division Page 278 of 282
HTML, DHTML & JavaScript
</body>
</html>
Math Object
The built-in Math object includes mathematical constants and functions. You do not need to create the
Math object before using it.
To store a random number between 0 and 1 in a variable called “r_number”:
r_number=Math.random();
To store the rounded number of 8.6 in a variable “r_number”:
r_number=Math.round(8.6)
Properties
Syntax: object.property_name
Property Description
E Returns the base of a natural logarithm
LN2 Returns the natural logarithm of 2
LN10 Returns the natural logarithm of 10
LOG2E Returns the base-2 logarithm of E
LOG10E Returns the base-10 logarithm of E
PI Returns PI
SQRT1_2 Returns 1 divided by the square root of 2
SQRT2 Returns the square root of 2
Methods
Syntax: object.method_name()
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x
asin(x) Return the arcsine of x
atan(x) Return the arctangent of x
atan2(y,x) Return the angle from the x axis to a point
ceil(x) Return the nearest integer greater than or
equal to x
cos(x0 Returns the cosine of x
exp(x) Returns the value of E raised to the power of
x
floor(x) Returns the nearest integer less than or equal
to x
log(x) Returns the natural log of x
max(x,y) Returns the number with the highest value of
x and y
min(x,y) Returns the number with the lowest value of x
and y
pow(x,y) Return the value of the number x raised to the
power of y
random() Returns a random number between 0and 1
round(x) Round x to the nearest integer
sin(x) Returns the sine of x
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of x
Example:
<html>
<body>
<script language=”JavaScript”>
document.write(Math.max(2,4))
</script>
</body>
</html>
Output:
4
String object
The String object is used to work with text/Strings.
The String object’s properties and method are described below:
Properties
Syntax: object.property_name
Property Description
constructor
length Returns the number of characters in a string
Methods
Syntax: object.method_name()
Method Description
anchor(“anchorname”) Returns a string as an anchor
big() Returns a string in big text
blink() Returns a string blinking
bold() Returns a string in bold
charAt(index) Returns the character at a specified position
charCodeat() Returns the Unicode of the character at a
specified position
concat() Returns two concatenated string
fixed() Returns a string as teletype
fontColor() Returns a string specified color
fontSize() Returns a string specified size
fromCharcode() Returns the character value of a Unicode
indexOf() Returns the position of the first occurrence of
a specified string inside another string.
Returns -1 if it never occurs
italics() Returns a string in italic
lastindexOf() Returns the position of the first occurrence of
specified string inside another string. Returns
-1 if it never occurs. Note: This method starts
from the right and moves left!
link() Returns a string as a hyperlink
match() Similer to indexOf and lastIndexOf, but this
method returns the specified string, or “null”,
instead of a numeric value
replace() Replaces some specified characters with some
new specified characters
search() Returns an integer if the string contain some
specified characters, if not it
returns -1
Training & Development Division Page 280 of 282
HTML, DHTML & JavaScript
Output: