Multimedia Web Design and Development
Multimedia Web Design and Development
AND DEVELOPMENT
LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED WARRANTY
By purchasing or using this book (the “Work”), you agree that this license grants
permission to use the contents contained herein, but does not give you the right
of ownership to any of the textual content in the book or ownership to any of the
information or products contained in it. This license does not permit uploading of the
Work onto the Internet or on a network (of any kind) without the written consent of
the Publisher. Duplication or dissemination of any text, code, simulations, images,
etc. contained herein is limited to and subject to licensing terms for the respective
products, and permission must be obtained from the Publisher or the owner of the
content, etc., in order to reproduce or network any portion of the textual material (in
any media) that is contained in the Work.
MERCURY LEARNING AND INFORMATION (“MLI” or “the Publisher”) and anyone involved
in the creation, writing, or production of the companion disc, accompanying algo-
rithms, code, or computer programs (“the software”), and any accompanying Web
site or software of the Work, cannot and do not warrant the performance or results
that might be obtained by using the contents of the Work. The author, developers,
and the Publisher have used their best efforts to insure the accuracy and functional-
ity of the textual material and/or programs contained in this package; we, however,
make no warranty of any kind, express or implied, regarding the performance of
these contents or programs. The Work is sold “as is” without warranty (except for
defective materials used in manufacturing the book or due to faulty workmanship).
The author, developers, and the publisher of any accompanying content, and anyone
involved in the composition, production, and manufacturing of this work will not be
liable for damages of any kind arising out of the use of (or the inability to use) the
algorithms, source code, computer programs, or textual material contained in this
publication. This includes, but is not limited to, loss of revenue or profit, or other
incidental, physical, or consequential damages arising out of the use of this Work.
The sole remedy in the event of a claim of any kind is expressly limited to replace-
ment of the book, and only at the discretion of the Publisher. The use of “implied
warranty” and certain “exclusions” vary from state to state, and might not apply to
the purchaser of this product.
MULTIMEDIA WEB DESIGN
AND DEVELOPMENT
Using Languages to
Build Dynamic Web Pages
Theodor Richardson
Charles Thies
Theodor Richardson and Charles Thies. Multimedia Web Design and Development.
ISBN: 978-1-936420-38-4
The publisher recognizes and respects all marks used by companies, manu-
facturers, and developers as a means to distinguish their products.
All brand names and product names mentioned in this book are
trademarks or service marks of their respective companies. Any omission
or misuse (of any kind) of service marks or trademarks, etc. is not an
attempt to infringe on the property of others.
131415 321
— Theodor Richardson
—Charles Thies
CONTENTS
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Chapter 1
WEB DESIGN BASICS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Chapter 2
SITE PLANNING AND PRODUCTION . . . . . . . . . . . . . . . . . 35
Contents — vii
2.3Professional HTML Authoring Tools ....................................... 45
2.3.1 Adobe Dreamweaver ..................................................46
2.3.2 Microsoft Expression Web .........................................48
2.3.3 Notepad++ ..................................................................49
Chapter Summary .....................................................................51
Chapter Knowledge Check........................................................51
Chapter Projects ........................................................................53
Chapter Exercises .....................................................................54
Chapter Review Questions........................................................55
Chapter 3
INTRODUCTION TO HTML . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Chapter 4
CSS3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.1 Introduction to Cascading Style Sheets ............................79
4.1.1 Invoking Styles in HTML ..........................................80
4.1.2 CSS Classes and Tags ................................................81
4.1.3 CSS IDs.......................................................................82
4.1.4 Pseudo-classes ............................................................83
4.1.5 Inheritance .................................................................84
4.2 Positioning and Layering ...................................................84
4.2.1 Element Position ........................................................85
4.2.2 Layers .........................................................................89
4.2.3 Height and Width.......................................................91
4.2.4 Margins and Padding.................................................94
4.3 Display Properties...................................................................... 97
4.3.1 Background Images ...................................................97
viii — Contents
Colors ..........................................................................99
4.3.2
Borders ..................................................................... 103
4.3.3
Shadows .................................................................... 104
4.3.4
Content Alignment................................................... 105
4.3.5
Text Modification ..................................................... 106
4.3.6
4.4 Reusing CSS Styles.................................................................. 108
Chapter Summary ................................................................... 110
Chapter Knowledge Check ..................................................... 116
Chapter Projects ..................................................................... 118
Chapter Exercises ................................................................... 118
Chapter Review Questions...................................................... 120
Chapter 5
HTML5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
5.1 Branding a Site ................................................................. 124
5.1.1 Planning for Content ............................................... 124
5.1.2 Creating a Site Map ................................................. 125
5.1.3 Hyperlinks ................................................................ 126
5.1.4 Image Links/Hotspots .............................................. 127
5.1.5 Meta Tags ................................................................. 130
5.1.6 Cloning Pages ........................................................... 131
5.1.7 Adding a Site Icon .................................................... 133
5.2 Adding Content ................................................................. 135
5.2.1 Using Paragraphs and Line Breaks ........................ 135
5.2.2 Ampersand Commands ............................................ 136
5.2.3 Adding Tables........................................................... 137
5.2.4 Adding Forms ........................................................... 141
5.2.5 Audio and Video ....................................................... 145
5.2.6 Embedded Code ........................................................ 146
Chapter Summary ................................................................... 148
Chapter Knowledge Check ..................................................... 148
Chapter Projects ...................................................................... 150
Chapter Exercises ................................................................... 151
Chapter Review Questions...................................................... 152
Chapter 6
JAVASCRIPT AND JQUERY. . . . . . . . . . . . . . . . . . . . . . . . . 155
6.1 JavaScript Basics ........................................................................ 155
6.1.1 Variable Declarations .............................................. 158
6.1.2 Assigning Values ...................................................... 159
6.1.3 Function Calls .......................................................... 161
6.1.4 Defining Functions................................................... 163
6.1.5 Conditional Statements ........................................... 165
Contents — ix
Looping ..................................................................... 168
6.1.6
6.2 Using JavaScript ...................................................................... 170
6.2.1 Using the alert() Function ....................................... 171
6.2.2 String Parsing and Form Validation ...................... 171
6.2.3 Dynamic Content ..................................................... 179
6.2.4 Events ....................................................................... 182
6.2.5 External JavaScript ................................................. 184
6.3 jQuery ........................................................................................ 185
6.3.1 Installing jQuery ...................................................... 186
6.3.2 jQuery Code and Use ............................................... 187
Chapter Summary .................................................................. 190
Chapter Knowledge Check...................................................... 190
Chapter Projects ...................................................................... 192
Chapter Exercises ................................................................... 193
Chapter Review Questions...................................................... 194
Chapter 7
PHP AND PERL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
7.1 Hosting a Web Site .................................................................. 197
7.2 PHP............................................................................................ 201
7.2.1 PHP Basics ............................................................... 202
7.2.2 Form Processing ....................................................... 204
7.2.3 E-mailing with PHP ................................................. 208
7.3 Perl .................................................................................... 210
7.3.1 Perl Basics ................................................................ 211
7.3.2 Form Processing ....................................................... 212
7.3.3 E-mailing with Perl.................................................. 216
Chapter Summary ................................................................... 219
Chapter Knowledge Check...................................................... 219
Chapter Projects ...................................................................... 221
Chapter Exercises ................................................................... 222
Chapter Review Questions...................................................... 223
Chapter 8
MYSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
8.1 MySQL ...................................................................................... 227
8.1.1 MySQL Data Types .................................................. 228
8.1.2 Creating a MySQL Database .................................. 230
8.2 Structured Query Language (SQL)........................................ 234
8.2.1 Select Queries........................................................... 234
x — Contents
Update Queries ........................................................ 235
8.2.2
Insert Queries .......................................................... 236
8.2.3
8.3 Using MySQL with PHP ......................................................... 236
8.3.1 Accessing a MySQL Database with PHP................ 237
8.3.2 Storing Data in a MySQL Database ....................... 239
8.3.3 Retrieving Data from a MySQL Database.............. 240
Chapter Summary ................................................................... 243
Chapter Knowledge Check...................................................... 243
Chapter Projects ...................................................................... 245
Chapter Exercises ................................................................... 246
Chapter Review Questions...................................................... 247
Appendix
SELECTED ANSWERS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Contents — xi
Introduction
This book is a complete guide to the concepts and practices of Web
design and development. It includes hands-on activities and profes-
sional advice for best practices in learning the procedures and prac-
tices of both design and development, allowing you to practice the
entire life cycle of a Web project. The material herein captures all of
the stages, from initial designs to back-end programming, of creating
complex Web applications. After completing this text, you will have
the ability to create dynamic, engaging Web sites with interactive
components and persistent styles. Each topic provides all of the neces-
sary instruction for getting started in that particular area.
The first five chapters of the book focus on the front-end design of a
Web site. This includes the use of HTML5 and CSS3 to create profes-
sional Web pages. This also includes guidelines for graphic design to
make the most of your pages using color, font, and style. The profes-
sional tools Adobe Dreamweaver and Microsoft Expression Web are
also introduced, with guidelines for their use in creating the case proj-
ect that continues throughout the text.
Chapter 6 focuses on the use of JavaScript for creating dynamic
elements and enabling interactions with the user. This also serves
as an introduction to the common syntax for conditional statements,
variable declarations, looping, and branching. This chapter completes
the front-end development of the Web site and transitions into con-
siderations for back-end Web application development. The jQuery
library of functions for creating complex JavaScript effects across
browsers is also introduced in this chapter, including instructions on
installing the library to a site, linking it to a page, and implementing
its functionality.
Chapter 7 introduces both PHP and Perl for developing back-end
code for Web applications. It gives an overview of both programming
languages, with the goal of focusing on common tasks needed for inter-
activity and processing user input through forms or JavaScript sub-
missions. This chapter includes instructions for emailing from both of
these server-side languages. In order to complete the activities for this
chapter, you will need Web hosting that supports one or both of them.
Ideally, the hosting solution you choose will also support MySQL for
completing the case project in its entirety. GoDaddy.com basic hosting
is recommended for this project, as it meets all of these criteria at a
relatively low cost.
Chapter 8 introduces MySQL, the most commonly used open
source database software, for data management and storage. This
includes an introduction to databases and the SQL database language.
The PHP toolkit is used for accessing, storing, and modifying data for
use in a Web application. The case project is completed in this chapter
with the storage and retrieval of information from the interactive form
developed for the site.
Chapter Structure
Each chapter is structured so as to provide you with an overview
and best practices for one component of creating a complete Web site
from the front-end design to the back-end programming. The chapters
contain hands-on activities both in the text and as standalone chal-
lenges to help you master the material. A case project is given as an
example for you to follow and expand on. Two additional projects are
presented to reinforce the material and allow you to practice it with
different objectives. A knowledge check is provided to allow you to test
your comprehension of the chapter. Answers to select odd-numbered
questions are provided at the back of the book. Additional exercises
and discussion questions are presented to help you further explore the
concepts in each chapter.
Code Notation
Some lines of code are longer than the lines of text in this book.
Whenever you see a symbol in the code, the line immediately follow-
ing it is a continuation that should be on the same line in your actual
code. In HTML this is not important but in formal languages it is
x i v — Introduction
necessary to keep all of the code on the same line. The code snippets
on the companion DVD contain the code in the correct lines for use.
Introduction — x v
Acknowledgments
Theodor Richardson:
I am very proud of the book that you now hold in your hands, and
I want to thank you for choosing it over others. Web design has been
a passion of mine and a profession for decades now, and I am pleased
to share what I have learned with you. This book is the result of the
combined creative forces of everyone who has worked to make it pos-
sible, and I want to offer my sincere thanks to them all, whether we
have met or not. I want to thank Katie Kennedy for her continued sup-
port, patience, and understanding as well as for her unprecedented
ability to make café lattes instantly as needed. I also want to thank
my grandparents, Leonard and Sylvia Ullom, and my parents, Dan
and Deborah Richardson, for giving me such a wonderful upbringing
and perpetual support and for helping me to capitalize on the oppor-
tunities that have led to my lifelong dream of seeing a book of my own
creation in print. I would like to thank my publisher, David Pallai,
and my co-author and friend, Charles Thies, for seeing another project
through to completion. Last, and certainly not least, I want to thank
you, dear reader, for your support.
Charles Thies:
I certainly have many people to thank who have made this project
possible. We have been writing now for a couple of years, and I would
like to thank my beautiful wife, Lea, and my sons, Matt and Will, for
their patience and support throughout. I would like to extend a special
thank you to my friend and co-author, Ted, for all of his guidance and
support throughout the project. A very special thank you to all of the
people we know worked to make this textbook possible but we never
met. Finally, a very special thank you to the students and professors
who have adopted this book; you are the reason we are always think-
ing about new ways to present material in the best format so that you
will be prepared in your field of study.
CHAPTER
1
Web Design Basics
I N T HI S CHAP T E R
A Web site is a collection of Web pages, documents, audio, and video that
is stored in a location such as a Web server and can be accessed by a unique
address determined by a Uniform Resource Locator (URL) value. DEFINITION
A Web server is a repository that contains all of the files and folders for a
Web site and provides remote access to them via various protocols such as
HTTP and File Transfer Protocol (FTP), over the Internet.
A Web browser is a software application used to search, navigate, and
retrieve information and data from the Web.
C h a pt e r 1 — We b D e s i g n B a s i c s — 3
1.1.1 Web Pages and Web Browsers
A Web page is a document designed for interpretation in a spe-
cialized application called a Web browser. Modern Web pages have
evolved from the simple concept of linking text documents to each
other via hyperlinks to an interrelated set of scripting and program-
ming languages that operate to provide a complex display capable of
providing rich, media-driven experiences for a user. Web pages use
a base language called Hypertext Markup Language (HTML), which
provides a means of complex media display and delivery along with
simple text inclusion. The file type of a Web page is .htm or .html.
A Web browser is a user application that retrieves Web pages and
interprets them for display on a user’s machine. The Web browser dis-
play is known as a WYSIWYG display, for “What You See Is What
You Get”; each Web browser will interpret the HTML code differently,
so content may not display the same way on different browsers. There
are a variety of Web browsers available for use.
Because of the differences in display, the World Wide Web Consortium (W3C)
has set standards of behavior and display for Web-based languages such
as HTML and Cascading Style Sheets (CSS). You should bookmark www.
NOTE
w3c.org on your most commonly used Web browser as a reference for
usage whenever you are in doubt about the behavior and application of a
Web-based language component.
The most common Web browsers in use today are Microsoft Inter-
net Explorer, Mozilla Firefox, Google Chrome, and Apple Safari. The
global statistics on browser use (as determined by statowl.com) can be
seen in Figure 1.1. The use of the different browsers varies by region.
Internet Explorer is the primary browser used in North America,
whereas Google Chrome has the largest use in Asia. Mozilla Firefox
is the most used browser in Europe. Apple Safari has seen increased
usage in recent years because of its integration with the Apple iPad.
have at least three of them installed on your computer for testing pur-
poses as you begin to design and develop more complex Web pages
and applications. The most common Web browsers can be downloaded
from the following sites:
C h a pt e r 1 — We b D e s i g n B a s i c s — 5
general use. IE can be downloaded from the Microsoft
homepage at www.microsoft.com.
• Mozilla Firefox: This browser is compatible with the Win-
dows, Mac OS, and Linux operating systems, as well as some
mobile devices (as an app). It can be downloaded from the
homepage www.firefox.com.
• Google Chrome: Chrome is a browser that has recently
gained market share. It is compatible with multiple
operating systems and integrates with Google’s other online
services, such as Google Docs. It can be downloaded from
www.google.com/chrome.
• Apple Safari: Safari is the default browser for Mac OS and is
directly integrated with Apple iOS devices, including the iPad.
A version of Safari is also available for Windows. You can
download Safari from www.apple.com/safari.
One of the browsers you should seriously consider having on your computer for
testing is Mozilla Firefox. It includes a Web Developer tool (accessible directly
from the Firefox main menu), which will assist you in evaluating your HTML
PROFESSIONAL
TIP code, CSS commands, and JavaScript execution. If you are unsure why your
page is not working or displaying properly, opening it in Firefox and using the
Web Developer tools Web Console and Error Console can save you a significant
amount of time debugging your page or application.
C h a pt e r 1 — We b D e s i g n B a s i c s — 7
HTML is case insensitive, so the tag <TiTLE> and the tag <title> will behave
in the same manner. But according to W3C, the HTML tag names should
always be in lowercase letters, so that is the convention you should adopt.
NOTE
C h a pt e r 1 — We b D e s i g n B a s i c s — 9
When there is no filename specified, the server will look for either
index.htm or index.html. For this reason, you should always name the
homepage of your site either index.htm or index.html so the server can
NOTE find it immediately with a reference to the containing folder. This will be reiter-
ated throughout the project planning, but you should make note of it now.
More complex word processing programs, like Microsoft Word, can create
HTML, but their use is not recommended. You must be careful with how you
save your files on these programs to avoid formatting code in your document
NOTE
in a language other than HTML and extraneous code added by the editor. You
should make sure that the Type field of the Save As dialog box says either
“Text” or “Plain Text” before you complete the save operation.
The head is signified by the <head> tag and closed by the </head>
tag. This section is used for configuration information and non-dis-
playing elements. The only portion of the head that displays in the
browser is the title. This is where you will place your CSS styles and
interlink external resources as you add complexity to your pages.
The body is signified by the <body> tag, which should be placed after
the closing </head> tag. The body is where all of the content should be
placed that you want to display in the browser window. The body must
also be closed with </body> before you close the HTML tag with </html>.
and create a template file for your HTML pages. First, choose a location on your
computer and create a new folder called “WebProjects” (with no spaces in the
name; you should not include spaces in any folder or filenames used for the Web).
You will create new folders inside of this folder for the activities and projects
throughout this text. Housing everything in the same folder structure will help you
when linking documents together and invoking resources within your pages.
Using the page outline given below, open a text editor and type the page struc-
ture into it, from the <html> tag to the </html> tag. You should save this file as
template.html inside the WebProjects folder. This will allow you to
create a new page by opening this file without the need to retype this structure.
You should follow along with the remaining parts of this chapter to expand your
template file to include the additional elements needed.
C h a pt e r 1 — We b D e s i g n B a s i c s — 11
The complete structure for an HTML page with the head and body
elements included is as follows:
<html>
<head>
</head>
<body>
</body>
</html>
You can use this as a guide for placing your content and resources.
There are additional elements that are common to all HTML pages
that you will explore in the next few sections. These include the docu-
ment type (doctype) declaration and page title.
1.2.1 The Doctype Declaration
A Doctype Declaration (DTD) is an instruction to the browser spec-
ifying the type of content the browser will encounter in the page. The
need for a DTD is based on the different versions of HTML that can
be used in a page and the widespread inclusion of XML documents on
the Web. A DTD tells the browser how to interpret what follows in the
page.
Some Web browsers are more forgiving of errors than others. For example, Firefox
allows you to open a page that does not include a DTD, but you should never
depend on this forgiveness, as it can cause compatibility issues in other browsers.
NOTE
There are a variety of DTD values that you may encounter, but
the two DTDs you will likely need to use most often are for HTML 5
and HTML 4.01. Eventually, you should construct all of your pages in
HTML 5. The command for a DTD is <!DOCTYPE>; this is in upper
case because it is a browser instruction, not an HTML tag.
</head>
<body>
</body>
</html>
C h a pt e r 1 — We b D e s i g n B a s i c s — 13
ACTIVITY 1.3 – ADDING DTDS TO THE TEMPLATE PAGE
For this activity, you should open template.html in the text editor of your
ACTIVITY choice and add a DTD declaration before the <html> tag. Be sure to save your
file when you are finished.
</body>
</html>
C h a pt e r 1 — We b D e s i g n B a s i c s — 15
FIGURE 1.4 Linked Text
In Firefox, you can select the Firefox menu, choose New Tab, and then
choose Open File to select an HTML file you want to open on your local
computer.
NOTE
The browser will interpret the page content for display and show
it in the browser window. You can see an example of this in Figure 1.5
for the hello.html page you have created through the activities in this
chapter. You should open this file in your own Web browser of choice
to see how the results of your work are interpreted.
C h a pt e r 1 — We b D e s i g n B a s i c s — 17
FIGURE 1.5 Testing an HTML Page
From the figure, you can see where the different elements of the
page translate in the browser. The title of the page will be located in
the top part of the browser interface. The main browser window is
where the body of the page is displayed. The address bar will display
the URL of the file. In this case, it will begin with file://C:, because
it is using local file access on the C drive of your machine. (A differ-
ent letter may display if you have selected a different default storage
drive.)
According to W3C, the common browser display size is now 1024 pixels by
768 pixels. This means you can plan a site for this size and assume that 98%
of your viewing audience will be able to see the site in a single window without
NOTE
scrolling.
C h a pt e r 1 — We b D e s i g n B a s i c s — 19
The other area of secondary real estate is from the bottom left-
hand corner of the browser window up to the primary real estate.
The entire left-hand side is not considered secondary real estate,
because part of it may not be visible without scrolling. When you
plan your site, you want to make sure any left-hand menu content
does not require the user to scroll down on the page, or they will
likely not see those menu items.
Users will not scroll a page unless they are vested in it by interest in some-
thing it contains. There is almost no possibility of their finding content
hidden past the standard browser size of the page unless it is related directly
PROFESSIONAL
TIP to content presented on the visible part of the page that prompts them to
explore further. You always want to make sure your menu and branding infor-
mation fit within the standard browser size, so you do not have to rely on user
scrolling and exploration for them to be able to navigate through your site.
C h a pt e r 1 — We b D e s i g n B a s i c s — 21
According to a study by CBS News (cbsnews.com), users spend an aver-
age of 33 seconds on a single Web page. They also form an opinion of the page
within approximately 8 seconds. That means you have approximately 8 seconds
PROFESSIONAL
TIP to entice them to stay and 33 seconds to interest them in your content. Your
design should be what gives them a favorable impression within the first 8 sec-
onds, and your content should be what retains them past 33 seconds.
The font is also determined by the size of the text. Most modern
fonts accommodate multiple sizes with the same display. A pixel is
the smallest unit of display on your computer monitor; the standard
resolution for a computer is 72 pixels per inch. In the world of type-
setting, there are 72 points per inch, meaning that a point is roughly
equivalent to a pixel on the screen. Therefore, a 12-point (abbreviated
12pt) font would occupy roughly 12 pixels of space on a digital display.
A less common measurement you may see is a pica; a pica is equiva-
C h a pt e r 1 — We b D e s i g n B a s i c s — 2 3
lent to 12 points. Pica rulers are most common in desktop publishing
applications.
There are two types of spacing available in the design of fonts:
monospacing and proportional spacing. In monospacing, all of the
characters in the font occupy the same horizontal width when typed;
this was the common case for most fonts in mechanical typewriters,
since the motion of the typing carriage was fixed. Proportional spac-
ing, on the other hand, allows letters to occupy only the space each one
needs to display.
The spacing between adjacent letters in a font is also established
by default, but you can adjust this manually; this process of adjust-
ment is called kerning. Adjusting the spacing between words is called
tracking. The spacing between lines (which is typically part of para-
graph formatting) is called leading. Most of these parameters can be
adjusted using style commands (via Cascading Style Sheets [CSS]).
The choice of font for a project varies greatly. With the variety of
fonts available from which to choose, it is a matter of creative choice.
However, as a general rule of design, you should have no more than
two fonts occupying the same page, a primary font and a secondary
font. More than this makes the arrangement look haphazard and
poorly planned. You can use different sizes of each font on the page to
add emphasis with size variation.
There are a variety of typefaces or fonts that come installed on any
modern computer system, but not all of these are common to every
machine. The Web browser uses the computer’s installed fonts to visu-
alize the page, so if a user does not have a font installed because it is
uncommon, your page will not look the way you designed it. It is pos-
sible (through style commands) to select multiple fonts, so you have
a backup if your first choice of font is not installed on the user’s com-
puter, but you should restrict your font choices to commonly installed
fonts like Arial, Helvetica, Times New Roman, and Courier New. If
you need a unique font to complete the look of your page, you should
consider placing it inside an image, so it remains constant whether
the font is installed on the user’s machine or not.
A good way to evaluate your color choice for a page is to view the colors adja-
cent to each other to test for contrast and conflict. As you become more profi-
cient with design, you can create a table and set the background color of each
PROFESSIONAL
cell to one of the colors you want to use and see how they interact. This will be TIP
revisited later, but it is something you should start to consider now.
FIGURE 1.8 The Color Wheel, with Complementary and Analogous Colors
C h a pt e r 1 — We b D e s i g n B a s i c s — 2 5
them is usually a safe way to construct your palette. You can also use
the Web to research standard color palettes, but you need to make
sure you have a limited number of colors, or your page will appear
cluttered and unorganized. You should make sure that any text you
include is readable above all else and that the tension between the col-
ors does not draw attention away from the content; you can lighten or
darken any of the colors to enhance or decrease the contrast presented.
Remember, the more contrast you have between your text and the
background, the clearer your text will be.
One color you should avoid is pure red; it is incredibly difficult for a person
to look at pure red on a computer screen for any sustained period of time. If
you want to verify this, you can open your template.html page and save it as
NOTE
red.html. Inside the body tag, add the attribute/value pair bgcolor=“red” and
change the title to “Red.” The code for the <body> tag should be the following:
<body bgcolor=”red”>
Now save the page and open it in a Web browser. How long can you look at the
page before you have to turn away or close it?
When choosing the colors for your pages or site, you should con-
sider the emotional association that people have with colors. There is
some variation in this in different cultures (such as traditional black
for mourning in the Western world and traditional white for mourn-
ing in the Eastern world), and context plays a significant role, but Fig-
ure 1.9 will give you a starting point to research the colors you want to
use and associate them with the message you want to convey.
C h a pt e r 1 — We b D e s i g n B a s i c s — 2 7
CHAPTER SUMMARY
This chapter introduced you to the fundamental structure and his-
tory of HTML, the language of the Web. HTML can be written in any
text editor, because it is a combination of plain text and formatting.
Every HTML page should contain a Doctype Declaration (DTD), a head,
and a body. The head of the page is used for configuration information
and references to external resources. The body of the page is what is
displayed in the Web browser when the page is accessed via its Uniform
Resource Locator (URL). The Web presents a unique environment that
can deliver rich and interactive media experiences. The fundamental
elements that should guide the development of Web pages are a clear
purpose and target audience. The tone of the site will be established
through font and color choices. The next chapter will cover site planning
and the professional HTML creation tools available on the market.
● A. head
● B. body
● C. title
● D. doctype
● E. None of the above
● A. Family, kerning
● B. Typeface, kerning
● C. Typeface, size
● D. Family, size
Which of the following retains the largest global market share of Web
5 browsers in use, according to research by statowl.com?
● A. Firefox
● B. Chrome
● C. Internet Explorer
● D. Safari
Which of the following is the native Web browser for Mac OS computers and
6 iOS devices?
● A. Firefox
● B. Chrome
● C. Internet Explorer
● D. Safari
What is the maximum number of fonts you should include on a single page?
7
● A. 5
● B. 2
● C. 3
● D. 1
● E. None of the above
C h a pt e r 1 — We b D e s i g n B a s i c s — 2 9
You should choose common fonts for your Web pages, because not all fonts
8 are installed on all users’ computers.
● A. True
● B. False
The two primary characteristics that should be determined for any Web design
9 project are:
The logo of a Web site should be placed in the primary real estate, which is
10 located ____________.
CHAPTER PROJECTS
These two projects will be used throughout the text. One is a per-
sonal project to develop your own Web site geared toward your own
career objective. The other is a sample Web site with five pages to
allow you to follow the design and development process from start to
finish. The sample site is designed to be a creative exercise, so you
should be as creative as you can in designing the content for it.
CHAPTER EXERCISES
1. Choose three travel Web sites (such as priceline.com and
travelocity.com) that offer similar travel options and evaluate
which of these sites you believe to have a better design
and adherence to purpose. List at least three factors that
influenced your decision.
C h a pt e r 1 — We b D e s i g n B a s i c s — 31
which of these sites you would be most likely to use for online
purchases. Give reasons for your answer.
10. You can nest HTML tags to add the effects of each tag to the
text inside the document. Create a new HTML file and save it
as nest.html. Add a line of text to the document, wrap the text
in the opening tags <b><i>, and end it with the tags </i></b>.
The tags should be closed in the reverse order from which they
were applied. Save and test your page when you are finished.
4. How would you describe the purpose of a news Web site? How
would you determine if the site was adhering to its purpose?
C h a pt e r 1 — We b D e s i g n B a s i c s — 3 3
6. When would you recommend using global referencing within
a Web site instead of local referencing? What is the benefit of
global referencing? What is the benefit of local referencing?
2
Site Planning and
Production
I N T HI S CHAP T E R
The process outlined in Figure 2.1 will allow you to move forward
in both design and development while integrating client feedback.
Everything stems from the initial client communication, in which you
3 6 — Multimedia Web Design
will ask the right questions to get the client to identify the essential
elements of the project. From there, you will distill the responses to
your questions to find out what is most important and begin planning
the site both visually and functionally. When you have created three
initial site designs for the client to review, you will present them as a
design set to the client for feedback. You should also transition from
the planned functionality to a solid plan for implementation, including
the languages and server-side resources you will need. Understanding
what resources to use will take time and practice, but this text will
guide you through planning a few sample projects to get a better idea
of what can be accomplished in each language.
After the client has chosen one of the designs, or preferred aspects
of the designs, you can create a revised design as a visual prototype
that you can use to start constructing your site. It is a good idea to
get a sign-off from the client on this visual prototype, to make sure it
is what he wants in the finished product. By working from this model
and integrating some amount of functionality (which may just consist
of hyperlinks at this point), you can create a functional prototype, on
which the final site will be based.
C h a pt e r 2 — S i t e P l a n n i n g a n d P r o d u c t i o n — 37
How often you communicate with the client for each level of imple-
mentation will vary depending upon the complexity of the site. If it is a
mostly static site presenting information, you may not need more than
one or two iterations to complete the site from the initial functional
prototype. For more complex and dynamic sites (such as e-commerce
sites or business applications), you may want more rounds of presen-
tation and refinement to make sure it is meeting the client’s business
needs. The back-end construction of the functionality will follow a
more traditional software development model than the visual front-
end construction, which requires more interaction with the client. Get-
ting the client sign-off on the model and any improvement notes or
changes at the end of each presentation will help you keep the project
on track and help protect you if there are any problems with the final
site implementation. Chapters 3 through 5 of this text focus on the
front-end characteristics of the site, and Chapters 7 and 8 focus on the
back-end functionality of the site. Chapter 6 presents the JavaScript
language (and its common library jQuery), which has applications to
both the front end and the back end of the site and can act as an effec-
tive bridge between the two pieces of the site itself.
2.1.2 Initial Client Communication
The goals of the initial client communication are to build the cli-
ent’s confidence in what you have to offer and to get a good understand-
ing of what the client expects. If possible, you should try to conduct
this meeting in person. This meeting is really not about you and your
accomplishments but about the client’s vision for the site.
One of the additional items you should know before ending the initial meeting
with the client is any existing branding the company or client is planning to use
on the site. You will have to work within the framework of this branding, such as
NOTE
the color scheme and visual style of what is required on the site. You can ask the
client if there is any flexibility on this or just what the required branding will be.
Two key elements you need to understand clearly when you leave
this meeting are the audience and the purpose of the site, which are
discussed in the next section. You should start by having the client
describe for you what his vision of the site is. Try to visualize it from
this description and imagine how it might look and feel.
on the visual aspect of the site and the overall vision of the client. Review your
list and determine whether or not any of the questions should be left for later, if
any of them pertain to development rather than planning, and whether they can
or should be addressed now. Combine or eliminate questions until you have five
questions that you feel will adequately capture everything you need to know
about the site to start drafting a visual prototype.
C h a pt e r 2 — S i t e P l a n n i n g a n d P r o d u c t i o n — 3 9
those will be handled in the next meeting, but what you really need as
a designer at this point is to understand the overall vision.
2.1.3 Establishing Purpose and Audience
This topic was briefly mentioned in the first chapter; it applies to
client-driven Web sites as well as to those you design for your own
needs. There are two aspects of a site that should guide every deci-
sion you make about what goes on every page: the audience and the
purpose. The audience of a site is the group of people for whom the
site is created. If the site is an entertainment site, the audience will
be fans of the group, movie, or whatever is being advertised, and it
should address their expectations and needs. If the site is a news site,
the audience will be people concerned with the topics on which you are
reporting. Determination of the audience should come primarily from
the client’s intention for the site. If you have enough time during the
design phase of the site, you can even interview or survey a sample
group to ask what they would want out of a site like the one you are
creating. The question to ask about the design elements for this aspect
is: do they serve the audience the site is targeting?
Purpose is the other key aspect to consider when planning a site.
The purpose of the site is the reason it even exists. The purpose of a
Web site may be advertising, information dissemination, information
gathering, or any number of other things. The purpose of the site will
again come from the client, who should have a clear mission for the
site and a reason to construct it.
The client is often not a Web designer or even familiar with the medium and
what it can do. Therefore, you cannot expect them to be completely articulate on
their vision of the site or its true purpose without some prompting. You may get
PROFESSIONAL
TIP answers like, “I was told it has to be constructed in conjunction with Project X.”
With answers like this, you can delve deeper by asking questions about that proj-
ect or asking the client why a certain thing is preferable. You should focus on this
in conversation until you feel you have elicited the real purpose of the site rather
than a superficial answer that will not get you far in constructing the design.
C h a pt e r 2 — S i t e P l a n n i n g a n d P r o d u c t i o n — 41
FIGURE 2.2 Different Emphases in Visual Design
You want to make sure that the elements important to the audi-
ence and purpose receive the most attention on the page. It can be dif-
ficult to map where your eye travels and what receives the emphasis.
In most Western civilizations, the eye is trained by reading to start at
the top left corner of the page and travel to the right and down. You
can test your design for emphasis by looking away and then glancing
quickly at your design to see where your eye stops on the page first.
You should use the visual elements of the page to create a map from
the highest-emphasis element to the lowest, which should guide the
design of your page (which is part of the branding, which will be dis-
cussed later). The eye naturally focuses on the area of highest contrast,
so you should make sure that area is where you want your emphasis
to be.
2.1.5 Creating a Design Set
When you have an understanding of what the client is expecting,
you should begin constructing the design set for the site. The design
set is typically three visual prototypes for the Web site. Remember
that two of these will be discarded, so you should design them in a
low-effort program like Microsoft PowerPoint to produce them effi-
ciently and work more on the layout and what to include rather than
the technical aspect of the site. Even if the elements are just mocked
up at this point, your job is to convey the overall look and feel of the
site in each of the visual prototypes. Each of the designs you create
should be unique but should convey the same information. Think of
it as three versions of the same exact Web page.) It is helpful to have
When you are creating a design set, you should work within the same color
palette for each visual prototype. Your client should be deciding between visual
nuances in the layout and look of the site rather than choosing between a blue
NOTE
site and a green site.
Creating the design set is one of the most difficult tasks for the
front end of a site. You can research similar sites or just review sites
that you like and dislike to get an idea of how the page should look. As
you progress through the text or your course, you should start to log
ten Web sites that work visually and ten Web sites that do not work
visually. These will help you to develop a more critical eye for site
design and give you a feel for how the user should respond to particu-
lar elements in a site.
sites that do not work well. You should confine this to the visual element for
now, as you begin to develop a critical eye for designing sites and understanding
user interfaces. You should create your journal in Microsoft Word. For each site
on your list (good and bad), list the URL and at least three reasons the site either
works well or does not work well visually. In Word 2010 or Word 2011, you can
insert a screenshot within the document while you have the site open in a Web
browser; this will help you later when you revisit your journal.
In all of your site designs, make sure to account for a menu, an area
for the menu to expand, and a place for the content to be displayed. The
designs you create should not be just a splash or landing page but rather
a complete map of what the interior of the site will be once the user gets
to the content. You can see an example design set in Figure 2.3.
C h a pt e r 2 — S i t e P l a n n i n g a n d P r o d u c t i o n — 4 3
FIGURE 2.3 Sample Design Set
The splash page (if there will be one) should be designed later,
after the content has already been established. You can label these
elements on your design for clarity if you do not know what the menu
items or content will be at the time you create the design set. Having
a clear design and distinct visual elements will help the client under-
stand what to expect in the site.
has already established. (More experienced graphic designers can use Adobe
InDesign or Adobe Photoshop, but these should still be throwaway designs.) You
should use the earth-tone color palette (greens, browns, and light blues) to con-
struct your design set. Remember that the color scheme should not be a primary
distinguishing factor among the different designs.
C h a pt e r 2 — S i t e P l a n n i n g a n d P r o d u c t i o n — 4 5
should consider purchasing a professional Web authoring tool. The
industry standard for Web development is Adobe Dreamweaver. This
is an expensive product; a cheaper alternative is Microsoft Expression
Web, which has the same overall functionality. Another tool that you
should consider downloading is Notepad++. This is a versatile text
editing program that can color-code text for a multitude of different
languages, including JavaScript, PERL, and PHP, which will be cov-
ered in later chapters. Keep in mind that HTML code is the same
regardless of the program that creates it, so you can open the same file
in any of the HTML editor programs listed.
C h a pt e r 2 — S i t e P l a n n i n g a n d P r o d u c t i o n — 47
2.3.2 Microsoft Expression Web
C h a pt e r 2 — S i t e P l a n n i n g a n d P r o d u c t i o n — 4 9
As soon as a file is saved through the program, the color coding will
be automatically activated for the type of text file it is (such as .html
for HTML files and .php for PHP). The color coding will change based
on the file type, but coding within an HTML page will register other
languages, such as JavaScript. This allows you to see scripts placed
within HTML pages as well as the HTML code itself.
● A. Visual prototype
● B. Functional prototype
● C. Design set
● D. All of the above
● E. None of the above
● A. Visual
● B. Functional
● C. Design
● D. None of the above
C h a pt e r 2 — S i t e P l a n n i n g a n d P r o d u c t i o n — 51
A ____ prototype will be iterated repeatedly with improvements until it is
3 handed to the client as a finished product.
● A. Visual
● B. Functional
● C. Design
● D. Throwaway
The process for designing and developing a Web site is the same for all
4 organizations and all developers.
● A. True
● B. False
Which of the following tools is the industry standard for Web site creation?
5
● A. Adobe Dreamweaver
● B. Microsoft Expression Web
● C. Notepad++
● D. None of the above
Which of the following is one of the essential items a designer must get from
6 the client before developing a design set?
● A. Audience
● B. Purpose
● C. Existing branding
● D. All of the above
● E. None of the above
The color scheme of a page should be one of the deciding factors between
7 different designs in a design set.
● A. True
● B. False
● A. True
● B. False
Deciding what content to showcase is the responsibility of the client and not
9 the designer.
● A. True
● B. False
A functional prototype should be shown to the client every time it is updated
10 to a new version.
● A. True
● B. False
CHAPTER PROJECTS
Project 1: Personal Web site
Using the color scheme you established in Chapter 1, create a
design set for your personal site. Remember to allocate enough space
in the visual design for content and a menu. Once you have created
your design set, review the designs and refine one of them into a visual
prototype. Keep all of your designs. You will use your final visual pro-
totype for implementation beginning in the next chapter.
C h a pt e r 2 — S i t e P l a n n i n g a n d P r o d u c t i o n — 5 3
CHAPTER EXERCISES
1. Visit three commercial Web sites that advertise products
(such as cocacola.com). How does each site make you feel
about the product? Which of these sites does the best job of
showcasing its product? What made you choose this site?
8. Using the design set you constructed for the case project,
explain how you would guide the design decision with the
client. Which design would you eliminate first and why? How
would you guide the discussion between the remaining two
designs?
9. Using the design set you constructed for the case project,
explain the transition process you used to get to the final
visual prototype. What aspects of the design(s) led to your
decision?
C h a pt e r 2 — S i t e P l a n n i n g a n d P r o d u c t i o n — 5 5
client? What factors will affect this schedule? What are the
drawbacks of showing the prototype to the client too often or
not often enough?
3
Introduction to HTML
I N T HI S CHAP T E R
C h a pt e r 3 — I n t r o d u c t i o n t o H T M L — 5 9
3.1.2 Structuring a Page
The default layout for HTML elements is to display each element
from the upper left corner going to the right and then moving down the
page once the right margin is reached. If you do not use any position-
ing style commands on your elements, this is the layout with which
you are stuck. Fortunately, the next chapter will cover how to change
this default behavior. For now, you should concentrate on getting the
elements of your site into the page. To begin, you should number each
of the sections in the order in which it is initially encountered from the
top left to the bottom right; this may not be an exact numbering since
there are objects that will overlap. Once again, you should omit the
background from this numbering. When you begin coding in the next
section, this will be the order in which you enter the elements. You can
see an example of this numbering for the sample layout in Figure 3.2.
There is another type of layout called frames that was used when Web sites
were first becoming popular. These are blocky and cumbersome; in modern
Web browsing there is no need for frames, and you should not consider them as
NOTE
an option for any layout.
C h a pt e r 3 — I n t r o d u c t i o n t o H T M L — 61
</head>
<body>
<div id=”banner” name=”banner”>Banner</div>
<div id=”logo” name=”logo”>Logo</div>
<div id=”menu” name=”menu”>Menu</div>
<div id=”cup” name=”cup”>Cup</div>
<div id=”content” name=”content”>Content</div>
<div id=”bottom” name=”bottom”>Bottom</div>
</body>
</html>
The code for the sample layout can be found in the WebProjects folder of the
companion DVD in the file layout.html.
ON THE DVD
As you will see in the coming sections, you can use one file with a
completed layout as a template for your entire site. This reduces the
overall effort of creating the pages and guarantees that the content on
the pages will be displayed the same way from page to page. You can
preview your page in a Web browser so you can see how the code posi-
tions the <div> elements naturally within the page.
You may wonder when an image should contain text. In most cases, it is better
for the display and better for the overall page to keep text out of images. The
exception to this is when the text must be in a particular font that is uncommon PROFESSIONAL
to most machines. For instance, the font used for the sample visual prototype for TIP
the case project is Bauhaus 93. If this were a real company and that were the
font the company used in its logo, it should be included in an image, since this
font is not as common as Arial or Times New Roman. If there is a choice of fonts,
though, you should opt to type the text in the HTML code and use formatting
instead of an image.
C h a pt e r 3 — I n t r o d u c t i o n t o H T M L — 6 3
Lossless describes a file format that does not lose pixel or
color information from the original image source. These tend to
be larger files than compressed, lossy formats.
DEFINITION
Lossy describes a file format that loses pixel or color
information from the original image source. These tend to be
compressed and have a smaller file size than lossless formats.
A palette is the range of colors that an image file format can
contain. Some formats, such as GIF, have a limited palette.
Most lossless formats allow a truecolor palette, which contains
16 million colors.
The file formats you should become familiar with for Web design
are the following:
• Bitmap and TIFF: These are lossless image formats. They
tend to have larger file sizes, but they retain all of the image
information. Their support for display on the Web is mostly
included for older pages of the Web, and these are not recom-
mended as the final format for your images. However, these
are great formats to use on a working copy of an image that
you are going to convert to a JPG or PNG.
• GIF: A GIF image is a limited-palette image that can support
256 colors per image. It is good for images with large areas of
the same color but performs poorly for images with gradients
and dithering. The GIF format allows image transparency
(where part of the image is empty space so the element behind
it in the page is visible in that space), and it has an animated
version that rotates through a sequence of GIF images using
the same color palette. Because of its limitations and the
restrictions on creating files in this format, it has largely dis-
appeared from modern Web sites. You should use this format
only if you have a specific need for lightweight animation;
otherwise you should use the PNG format for transparency.
• PNG: The PNG format was created as an open-source succes-
sor to the GIF format. The PNG format supports a truecolor
(16 million colors) palette and allows image transparency.
This is an excellent format for layering images, and it is fully
supported in modern browsers.
Google has developed the WebP (or WEBP) format, which is a lossy compression
designed to reduce file sizes for sharing photographs on the Web; so far, JPEG
images are still widely used as the standard.
NOTE
C h a pt e r 3 — I n t r o d u c t i o n t o H T M L — 6 5
If you are in the business of graphic design and are learning Web
design as a supplement to that, it is highly recommended that you
obtain a copy of this software. If you are approaching Web design from
the programming standpoint and are primarily concerned with the
back end of the process, the cheaper alternatives for image creation
will most likely suffice.
A free alternative to Adobe Photoshop is the Pixlr® Editor, an
online-only software package that provides a substantial subset
of the tools available in Photoshop. It can be accessed online at
http://pixlr.com/editor. This can be used to create transparent
PNG images and JPG images. You can see an example of the layout
of the Pixlr® Editor interface in Figure 3.4.
You can even use the Pixlr® Editor to import photos or images
from your desktop to edit online. If you are new to image creation,
this is a good alternative to Photoshop, since it has a more limited
scope of functionality. Additionally, the tools contained in the Pixlr®
Editor closely equate to those in Photoshop, meaning that you can
learn a tool for Pixlr® and use the same tool in Photoshop with mini-
mal effort.
This is the stage at which you want to spend the time on creation of profes-
sional-quality images for your site. These are the images that will go live in the
final product.
NOTE
To evaluate what images need to be created for your site, you can
start by going through your layout section by section to decide how to
build it in HTML. For the sample layout, the sections can be evaluated
as follows:
1. This is the banner section, which will require a background
image. Since the image shows the layers beneath it, it will need
to be transparent. The image file for this is called banner.png
within the WebProjects folder of the companion DVD. ON THE DVD
C h a pt e r 3 — I n t r o d u c t i o n t o H T M L — 6 7
When you are creating an image with transparency, you should place it over a
background as close to the color of the actual background as possible. You may
end up with outer pixels that reflect the background color of the original image,
NOTE
so it will look more integrated if this color looks natural on the real background
for which the image is intended.
3. The menu is a solid color. This effect can be achieved using CSS in
Chapter 4.
6. This is the bottom of the interface. Just like the top banner,
this layer needs to show the layers beneath it. This will also be
used for legal and disclaimer information, so the image created
will be used as a background. The image file for this is called
footer.png within the WebProjects folder of the companion
ON THE DVD
DVD.
To create the effect of the cup image in Pixlr, you can complete the following
steps. Create your initial drawing without adding the shadow effect in a photo
creation software system (Photoshop, Pixlr, Paint, or even PowerPoint) and save PROFESSIONAL
it as a Bitmap file. Open the Pixlr editor in a Web browser and choose the option TIP
Remember that the JPG format is lossy, so you should save your
image as a JPG file only one time. You should always have a working
copy saved as a PNG, Bitmap, or TIFF. Saving JPG files repeatedly
will cause them to lose clarity. You also want to be economical with
your file sizes; the larger your file size, the longer it takes to load your
page on a client’s machine. Too much wasted download time and the
C h a pt e r 3 — I n t r o d u c t i o n t o H T M L — 6 9
client will be off your page before even seeing it. To make sure the file
sizes are as small as possible, you should design your images to fit
exactly in the space for which they are intended using the sizing fea-
tures of the image creation tools. This way there is no wasted down-
load time fitting larger files into small spaces when smaller images
would serve the same purpose.
When you are using relative addressing, the character sequence “../” moves up
one directory. You can chain these together to move up multiple directories. The
character sequence “./” points to the current directory; this is often omitted and
NOTE
assumed (so src=“./logo.png” is equivalent to src=“logo.png”).
Some lines of code are longer than the lines of text in this book. Whenever you
see a symbol in the code, the line immediately following it is a continuation
that should be on the same line in your actual code. In HTML this is not impor-
NOTE
tant but in formal languages it is necessary to keep all of the code on the same
line. The code snippets on the companion DVD contain the code in the correct
lines for use.
C h a pt e r 3 — I n t r o d u c t i o n t o H T M L — 71
The banner and footer images will be used as background images,
so they will not be added until the next chapter. The logo and cup
images, however, will be used directly inside the <div> tag for those
elements and replace the text you added as a placeholder. The com-
pleted code for the added images inside the layout is as follows:
<!DOCTYPE html>
<html>
<head>
<title>Zippy Beans Coffee Co.</title>
</head>
<body>
<div id=”banner” name=”banner”>Banner</div>
<div id=”logo” name=”logo”><img id=”logo_img”
alt=”Zippy Beans Logo” src=”Media/logo.png” /></div>
<div id=”menu” name=”menu”>Menu</div>
<div id=”cup” name=”cup”><img id=”cup_img”
alt=”Zippy Beans Cup” src=”Media/cup.png” /></div>
<div id=”content” name=”content”>Content</div>
<div id=”bottom” name=”bottom”>Bottom</div>
</body>
</html>
Save your file as index.html in the project folder for the sample
site. You can test your code to make sure it works anytime in a Web
browser. If you have entered the code correctly and placed your images
in the Media folder, you should see two images and the text for the
remaining <div> elements.
C h a pt e r 3 — I n t r o d u c t i o n t o H T M L — 7 3
____ addressing is the use of the full URL for determining an image location
4 in the src attribute of the <img> tag.
● A. Uniform
● B. Relative
● C. Relational
● D. Absolute
● E. None of the above
● A. True
● B. False
GIF images are highly desirable for modern Web sites because of their
8 transparency and ability to show complex animations.
● A. True
● B. False
All image formats are supported by all major browsers, so which file format to
9 use is an individual choice.
● A. True
● B. False
● A. True
● B. False
CHAPTER PROJECTS
Project 1: Personal Web Site
For your project in this chapter, you will decompose your visual
prototype for your personal site into sections and create the index.
html page for your project based on the decomposition. You should
save this file in the project folder designated for your personal site.
Next, you will analyze the sections for which images need to be cre-
ated, create them, and save them to a Media folder within your project
folder. Finally, you will add the images into your HTML page using
the <img> tag.
CHAPTER EXERCISES
1. Choose three Web sites and look at how they layer images
within the site. For each site, list the URL and describe the
different visual layers used in its layout. Which of these sites
creates the most depth? Which of the sites uses images most
effectively?
C h a pt e r 3 — I n t r o d u c t i o n t o H T M L — 75
2. A <div> tag is a block layout element. Use the Web to
research what this means and define it in your own words.
What other HTML tags have this default property?
C h a pt e r 3 — I n t r o d u c t i o n t o H T M L — 7 7
5. Why should images be created more carefully in the final
design rather than using the images from the visual
prototype for the final product? Explain your answer.
4
CSS3
I N T HI S CHAP T E R
You can add comments to the styles using the character string
“/*”; this will comment out everything until the character string “*/” is
encountered. You can use this to describe the different styles or make
notes. You can see an example of this in the following:
<style type=”text/css”>
/* This is a comment. */
</style>
C h a pt e r 4 — C S S 3 — 81
For instance, you can define a logo class using the following:
<style type=”text/css”>
div {
/* The style property/value pairs go here. */
}
.logo {
width: 150px;
}
</style>
You can define multiple style sets and classes within the same set
of <style> tags. To invoke a class, you must call it within the tag to
which you want the style set to apply. To call the logo class, you would
use the following:
<img src=”Media/logo.png” class=”logo” … />
When calling a style class, you do not need the period before the class name.
This is necessary only when you define the class itself.
NOTE
In this example, the style set defined would apply only to the ele-
ment with the attribute id=“logo” within the page. The element id
must be unique for the page to work properly. There is no need to
invoke the style; it will be applied automatically.
4.1.4 Pseudo-classes
Another type of class within CSS is a pseudo-class. This type of
class is invoked depending on the state of the tag to which it is applied.
One of the most common applications of a pseudo-class is with hyper-
links, which you will see in Chapter 5. When a user hovers the mouse
over the hyperlink, the tag enters the state hover; you can use this
state to define a pseudo-class that will change the style properties
only while this state is active. The “hover” state would become inactive
when the mouse leaves the hyperlink element and the style set in the
pseudo-class would no longer apply. You can apply this pseudo-class
to other elements as well, particularly <div> tags.
The pseudo-class is a subclass of a tag, a class, or a tag id. You
define a hover pseudo-class for the logo class using the following code:
<style type=”text/css”>
.logo:hover {
width: 180px;
}
</style>
Now when a user hovers over the tag invoking the logo class, the
width of the tag will change to 180 pixels.
There are a number of available pseudo-classes, including hover,
visited, active, and focus. As you learn more about hyperlinks, you may
want to revisit this topic to determine how to tailor your link display
based on current or prior user actions. You will use the hover pseudo-
class to expand the menu in the sample layout in this chapter.
C h a pt e r 4 — C S S 3 — 8 3
4.1.5 Inheritance
CSS is designed to allow elements to inherit styles from their par-
ent tags (the tags that contain them). The simplest example of this is
that any text modifications defined for the <body> tag will apply to all
tags and elements within the <body> tag. This inheritance also allows
you to define certain styles once and then ignore that property later.
For instance, if you set the font for the <body> tag, you do not need to
set the font again unless you want a different font within a specific set
of tags or element.
In some browsers, <table> tags do not inherit from the <body> tag. This is also
true for form elements. You can force properties to be inherited by setting their
value to inherit in the style definitions for the tags that are not cooperating. This
NOTE
prevents you from having to define the same code multiple times, because it will
force changes in the <body> tag to apply to any tag whose value specifies that
it should inherit that property value.
The style commands that are closest to the actual element are
applied first for that element. This means that any style commands
for an invoked class will supersede style commands for the tag, which
will supersede style commands for the parent element. These inheri-
tance rules can be applied in interesting ways. An element can inherit
styles from a parent, a class, a tag, and an ID. You can also invoke
multiple classes in CSS and define classes for nested elements, but
this can be overwhelming when you are first getting started.
C h a pt e r 4 — C S S 3 — 8 5
}
</style>
Setting this value does not by itself alter the appearance of the
element at all. In order to do this, you must set an anchor point for
the element on the page. For this, you will typically use the top and
left properties (though combinations of the top, bottom, left, and right
elements can be used to define an anchor point at any of the corners
of the element).
The following is an example of this that will place the banner ele-
ment in the sample case project layout at the top left corner of the
browser window:
<style type=”text/css”>
#banner {
position: fixed;
top: 0px;
left: 0px;
}
</style>
If you cannot see the effect of this, you can make your browser win-
dow smaller until there is enough content to allow you to scroll the page.
C h a pt e r 4 — C S S 3 — 8 7
left: 0px;
}
#logo {
position: fixed;
top: 0px;
left: 0px;
}
#menu {
position: fixed;
top: 80px;
left: 220px;
}
#cup {
position: fixed;
top: 160px;
left: 0px;
}
#content {
position: absolute;
top: 140px;
left: 200px;
}
#bottom {
position: fixed;
bottom: 0px;
left: 0px;
}
</style>
Note the positioning of the bottom element. You can use per-
centages as well as exact pixel numbers for values. By setting
this bottom property value to 0, you keep it at the bottom of the
page no matter what size the browser window is. The value of the
4.2.2 Layers
Even after the positioning of the elements is set, two elements can-
not reside in the same space on the same layer. The CSS property
that governs the layer used is the z-index property. The value of this
property is a number representing the stack order from background to
foreground. The lowest number is furthest in the browser background,
and the highest number is closest in the foreground.
The depth distance (along the z-axis) between elements is not determined by
the relative values of the z-index property. A difference between 1 and 2 in
property values for two elements has no display effect compared to property
NOTE
values between 1 and 500 for two elements.
In order to set the stack order with z-index values, you need to
consider which element should be on the bottom of the stack and work
your way forward. A best practice is to set your <body> tag at z-index
C h a pt e r 4 — C S S 3 — 8 9
value 1 and build forward. For your convenience, you can increment
the z-index values by 5 or 10 to allow the addition of other elements
in a redesign later. With the analysis in the prior section on the <div>
elements in the page, the following is the updated style set:
<style type=”text/css”>
#banner {
position: fixed;
top: 0px;
left: 0px;
z-index: 30;
}
#logo {
position: fixed;
top: 0px;
left: 0px;
z-index: 40;
}
#menu {
position: fixed;
top: 80px;
left: 220px;
z-index: 20;
}
#cup {
position: fixed;
top: 160px;
left: 0px;
z-index: 10;
}
#content {
position: absolute;
top: 140px;
left: 200px;
}
For this part of the layout refinement, you should consider which
elements have to span the entire page, which elements should have a
fixed size, and which elements should be allowed to grow. In the exam-
ple below, the banner and footer should span the entire width of the
page. The content area should be allowed to grow vertically (but should
have a fixed width). The images should be fixed in size in both directions.
In addition to the <div> tags, you can use the height and width
properties to set the parameters for the images themselves within the
page. If these properties are left blank, the default behavior of the
<img> tag is to display the image at 100% of its height and width
according to the file size of the image. The height and width decisions
for the sample layout for the case project result in an update to the
C h a pt e r 4 — C S S 3 — 91
CSS style sets (and the inclusion of new style sets to define sizing):
<style type=”text/css”>
#banner {
position: fixed;
top: 0px;
left: 0px;
z-index: 30;
width: 100%;
height: 150px;
}
#logo {
position: fixed;
top: 0px;
left: 0px;
z-index: 40;
height: 175px;
width: 175px;
}
#logo_img {
height: 150px;
width: 150px;
}
#logo_img:hover {
height: 175px;
width: 175px;
}
#menu {
position: fixed;
top: 140px;
left: 220px;
z-index: 20;
width: 760px;
}
#cup {
When you are testing your layout as it develops, you can add a temporary class
to the <div> tag so you can see where the element sits on the page. The class
you should add is: PROFESSIONAL
TIP
div {
border-style: solid;
border-width: 5px;
border-color: red;
}
C h a pt e r 4 — C S S 3 — 9 3
You should make sure you remove the temporary style set (or the lines that
define the border, at least) once the layout adjustments are complete.
The example above includes CSS code for the hover pseudo-class
on the logo image; this will increase the size of the image whenever
the user hovers the mouse over it. This will be useful when the link to
the home page is added to this image. Any kind of effects like this that
you can add with CSS will maintain cross-compatibility and eliminate
the need for JavaScript coding, which tends to be more browser-spe-
cific and complex.
You can check the height and width of an image by clicking on the file in Win-
dows Explorer in Windows 7. If these values are not automatically displayed or
if you are using a different OS that does not include this functionality, you can
NOTE
right-click and select Properties to get this information.
#banner {
position: fixed;
top: 0px;
left: 0px;
z-index: 30;
width: 100%;
height: 130px;
padding-left: 200px;
padding-top: 10px;
padding-right: 10px;
}
#logo {
position: fixed;
top: 0px;
left: 0px;
z-index: 40;
height: 175px;
width: 175px;
margin-left: 20px;
}
#logo_img {
height: 150px;
width: 150px;
}
C h a pt e r 4 — C S S 3 — 9 5
#logo_img:hover {
height: 175px;
width: 175px;
}
#menu {
position: fixed;
top: 80px;
left: 220px;
z-index: 20;
width: 780px;
height: 60px;
padding-top: 20px;
}
#cup {
position: fixed;
top: 160px;
left: 0px;
z-index: 10;
}
#cup_img {
width: 220px;
height: 306px;
}
#content {
position: absolute;
top: 140px;
left: 200px;
width: 800px;
padding-left: 20px;
padding-right: 20px;
padding-top: 35px;
padding-bottom: 20px; }
#bottom {
ers, margins, padding, and height and width values for each
<div> tag and set the margins for the <body> tag. This will prepare your page
for the display property modifiers in the next section. Make sure to save your
changes and test your layout adjustments in a Web browser.
C h a pt e r 4 — C S S 3 — 9 7
CSS is located externally, as you will learn in the last part of this
chapter). In order for this to be used in CSS, you need to wrap the
path in a function to convert the text to a URL with url(‘./string
value’). An example of this is:
#banner {
…
background-image:url(‘./Media/banner.png’);
}
4.3.2 Colors
You can use CSS to define colors for use in backgrounds as well
as colors for the content (mostly the text that displays in an element).
The two properties for color are background-color and color. The back-
ground-color property is used to define the color behind the content;
this can be used in conjunction with a transparent background image
in most browsers, as long as the color is defined before the background
image. The color property is used to define the text and content fore-
ground color. You can see an example of this in the code:
#menu {
…
background-color: #3c3;
color: #efe;
}
C h a pt e r 4 — C S S 3 — 9 9
• Hexadecimal (hex): These values use a # mark to signify the
start of the code and use a #RedGreenBlue or #RGB format,
such as #0f0 for pure green. A more specialized form of this
uses two hexadecimal characters for each color instead of one.
This format allows you to specialize the color even more; an
example of this is #a347a3 for a specific shade of purple. The
three-character version of a hexadecimal code is shorthand
for both characters allocated for a single color being the same.
Each color in hexadecimal notation has a range of intensity
from 0 to 255 (or ff).
• Red Green Blue Alpha (RGBA): In this alternative format for
displaying color, the color values are represented in standard
integer values ranging from 0 to 255. The alpha value is used
to determine the transparency and ranges in decimal values
from 0 to 1, where 0 is completely transparent and 1 is fully
opaque. An example of this is rgba(0,255,0,1) for pure green
with full opacity. You can specify percentages for the color
values instead of integers (up to 100%). An alternative form of
this format omits the alpha value, as in rgb(0,255,0) for pure
green.
The W3Schools site maintains a color picker tool for choosing any color
and getting its hexadecimal representation. The address for this tool is
http://www.w3schools.com/tags/ref_colorpicker.asp.
NOTE
The CSS color codes for the different design elements in the
sample design layouts are as follows:
<style type=”text/css”>
C h a pt e r 4 — C S S 3 — 101
body {
height: 100%;
width: 100%;
background-color: #E0FFD1;
background-attachment: fixed;
background-repeat: no-repeat;
background-image: linear-gradient(left top,
#4BE60E 2%, #E0FFD1 65%);
background-image: -o-linear-gradient(left
top, #4BE60E 2%, #E0FFD1 65%);
background-image: -moz-linear-gradient(left
top, #4BE60E 2%, #E0FFD1 65%);
background-image: -webkit-linear-gradient
(left top, #4BE60E 2%, #E0FFD1 65%);
background-image: -ms-linear-gradient(left
top, #4BE60E 2%, #E0FFD1 65%);
background-image: -webkit-gradient(
linear,
left top,
right bottom,
color-stop(0.02, #4BE60E),
color-stop(0.65, #E0FFD1)
);
}
…
#banner {
…
color: #fff;
}
…
#menu {
…
background-color: #3c3;
color: #efe;
4.3.3 Borders
CSS allows you to set borders for your elements as well. You can
do this with the border-width, border-style, border-color, and border-
radius properties. The last of these can be used to establish custom
radii for each corner of the tag boundary. All of them are best used
in combination with the background-color or background-image prop-
erty. These properties take specific values:
• Border-width: This property uses either a percentage or a
measurement.
• Border-style: This uses a specific value, such as groove, solid,
dashed, or double; a complete list of these can be found at
http://www.w3schools.com/cssref/pr_border-style.asp.
• Border-color: This accepts the color formats discussed in the
previous section.
• Border-radius: This property accepts either a percentage or a
measurement.
The border-radius property has modifiers, which can specify the
corner to be changed. For example, the menu needs only rounded bot-
tom left and bottom right corners. The properties for this are border-
bottom-left-radius and border-bottom-right-radius. You can see the
C h a pt e r 4 — C S S 3 — 10 3
code for rounding the menu and content <div> tags for the example in
the following code:
<style type=”text/css”>
…
#menu {
…
border-bottom-left-radius: 16px;
border-bottom-right-radius: 16px;
}
…
#content {
…
border-radius: 16px;
}
</style>
4.3.4 Shadows
Another useful property in CSS is the box-shadow property. This
allows you to add shadows to layered content, which can add a sense
of depth and perspective to the layout of your page. The box-shadow
property is supported in most of the main modern browsers, but Safari
supports the -webkit-box-shadow property, which you should include
as a separate line in the CSS style set. The parameters (in this case a
set of values) for box-shadow are as follows:
• H-shadow: This is the horizontal distance by which the
shadow should be offset; this value is required.
• V-shadow: This is the vertical distance by which the shadow
should be offset; this value is required.
• Blur: This is the distance over which the shadow should be
blurred; this value is optional and defaults to 0.
• Spread: This is the distance over which the shadow should
spread; this value is optional and defaults to 0.
• Color: This is the color of the shadow; this value is optional
and defaults to pure black.
C h a pt e r 4 — C S S 3 — 10 5
4.3.6 Text Modification
There are a number of different properties that control the display
of text within an element. These are some of the simpler CSS com-
mands to use, and most of them have been around since CSS version 1.
The common text adjustment properties, their descriptions, and their
accepted values are as follows:
• Font-family: This property defines the order in which the
browser will seek fonts to render the contents of the tag. The
value for this is a comma-separated list of font names. It is a
good idea to end the list with either serif or sans-serif, which
are the default fonts for these categories in case no other font
in the list can be found. If there are spaces in the font name,
you have to add single quotation marks around the name of
the font or it will not read as a single font. An example of this
is font-family: Arial, Helvetica, sans-serif;
• Font-size: This defines the size of the font. (Remember that a
font is both a typeface and a size.) The value of this property
is a measurement, which can include traditional point (pt)
values for font size in addition to the other measurements dis-
cussed for placement. An example of this is font-size: 10pt;
• Font-weight: This describes whether text is normal or modi-
fied to be lighter or bolder. The common values for this are
normal (default) and bold (bold type). An example of this is
font-weight: bold;
• Font-style: This property is used to italicize text. The common
values for this are normal (default) and italic. An example of
this is font-style: italic;
• Text-decoration: This property is used to apply text decorations
such as strikethrough and underline. The common values for
this are none (default except for hyperlinks) and underline.
An example of this is text-decoration: none; (which actually
removes the underline from a hyperlink).
• Text-shadow: This is a unique property that allows you to
add a shadow to the text in an element. This property takes
a series of values: h-shadow, v-shadow, blur, and color. The
values h-shadow and v-shadow are required; they are the
offset distances in, respectively, the horizontal and the vertical
distance from the text. The values blur and color are optional.
The blur value is the distance over which the shadow blurs,
C h a pt e r 4 — C S S 3 — 10 7
ACTIVITY 4.3 – MODIFYING ELEMENT DISPLAY WITH CSS
For this activity, you will incorporate the display adjustment properties of CSS
ACTIVITY into your evolving style sheet for the index.html page of your case project.
You should not define new HTML elements to adjust your display at this time;
instead, you should focus on establishing the effects for your layout of using
CSS on the existing HTML tags and IDs, including the <body> tag. You can test
the results in a Web browser to be sure you have done this correctly. Feel free
to modify the CSS as needed until your page is displayed correctly. You should
test your result in at least two of the major browsers: Internet Explorer, Mozilla
Firefox, Apple Safari, and/or Google Chrome.
within your page with a <link> tag to the new style sheet you have created.
You should make sure to place your external style sheet in an Include folder
within your main project folder. The file extension for the external CSS file
should be .css. You can test the results in a Web browser to be sure you have
done this correctly.
C h a pt e r 4 — C S S 3 — 10 9
CHAPTER SUMMARY
In this chapter, you learned how to define style sets in CSS for tags,
classes, and IDs. You learned when each of these should be invoked
and how to reuse each. The standard format of CSS style commands
was covered and practiced, and you should now be able to read and
understand CSS code, as well as use the properties covered in this
chapter. If you have followed along with the sample layout code, your
page content should be as follows (prior to creation of the external
style sheet):
<!DOCTYPE html>
<html>
<head>
<title>Zippy Beans Coffee Co.</title>
<style type=”text/css”>
body {
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
margin-bottom: 0px;
height: 100%;
width: 100%;
background-color: #E0FFD1;
background-attachment: fixed;
background-repeat: no-repeat;
background-image: linear-
gradient(left top, #4BE60E 2%, #E0FFD1 65%);
background-image: -o-linear-
gradient(left top, #4BE60E 2%, #E0FFD1 65%);
background-image: -moz-linear-
gradient(left top, #4BE60E 2%, #E0FFD1 65%);
background-image: -webkit-
linear-gradient(left top, #4BE60E 2%, #E0FFD1 65%);
background-image: -ms-linear-
.grad {
background-image: linear-
gradient(left top, #4BE60E 2%, #E0FFD1 65%);
background-image: -o-linear-
gradient(left top, #4BE60E 2%, #E0FFD1 65%);
background-image: -moz-linear-
gradient(left top, #4BE60E 2%, #E0FFD1 65%);
background-image: -webkit-
linear-gradient(left top, #4BE60E 2%, #E0FFD1 65%);
background-image: -ms-linear-
gradient(left top, #4BE60E 2%, #E0FFD1 65%);
background-image: -webkit-
gradient(
linear,
left top,
right bottom,
color-stop(0.02, #4BE60E),
color-stop(0.65, #E0FFD1)
);
}
C h a pt e r 4 — C S S 3 — 111
#banner {
position: fixed;
top: 0px;
left: 0px;
z-index: 30;
width: 100%;
height: 130px;
padding-left: 200px;
padding-top: 10px;
padding-right: 10px;
background-image:url(‘./Media/
banner.png’);
background-repeat:no-repeat;
background-position: top;
background-size: 100% 130px;
color: #fff;
font-family: ‘Bauhaus 93’;
font-size: 36pt;
text-shadow: 2pt 2pt 4pt #020;
}
#logo {
position: fixed;
top: 0px;
left: 0px;
z-index: 40;
height: 175px;
width: 175px;
margin-left: 20px;
text-align: center;
}
#logo_img {
height: 150px;
width: 150px;
}
C h a pt e r 4 — C S S 3 — 113
#content {
position: absolute;
top: 140px;
left: 200px;
width: 800px;
background-color: #fff;
padding-left: 20px;
padding-right: 20px;
padding-top: 35px;
padding-bottom: 20px;
color: #010;
background-color: #fff;
border-radius: 16px;
text-shadow: 1px 1px 2px
rgba(0,10,0,0.2);;
}
#bottom {
position: fixed;
bottom: 0px;
left: 0px;
z-index: 30;
width: 100%;
height: 80px;
padding-left: 10px;
padding-right: 10px;
padding-top: 30px;
background-image:url(‘./Media/
footer.png’);
background-repeat:no-repeat;
background-size: 100% 80px;
background-position: bottom;
color: #fff;
}
</style>
FIGURE 4.1 Comparison of Initial Visual Prototype (top) and Implemented Results (bottom)
C h a pt e r 4 — C S S 3 — 115
You should take this time to create the external style sheet for your
projects so you have an easy place to refine elements as you complete
your front-end site design in the next chapter. That chapter will focus
on additional HTML elements to include in your page, content plan-
ning, and site finalization. The rest of the book (Chapters 6 through 8)
focuses on implementing dynamic content and handling user actions
on the site.
Which of the following values are not accepted by the position property?
3
● A. absolute
● B. relative
● C. inline
● D. static
● E. None of the above
The greater the difference in z-index values, the greater the visual depth of
4 the layers will become.
● A. True
● B. False
The _____ defines the distance between an element and its nearest allowed
6 neighbor.
● A. spacing
● B. padding
● C. margin
● D. buffer
The property background____ defines how the background tiles within the
7 boundaries of an element.
● A. width
● B. attachment
● C. repeat
● D. image
● E. All of the above
● F . None of the above
The style command nearest to the HTML tag takes precedence for display.
8
● A. True
● B. False
Which of the following properties governs the application of italic text?
9
● A. font-size
● B. font-weight
● C. text-style
● D. text-decoration
C h a pt e r 4 — C S S 3 — 117
Which of the following is an incorrect color declaration in CSS?
10
● A. #fef
● B. #ddffee
● C. rgb(1,1,10)
● D. rgba(10,10,10,0.5)
● E. All of the above
● F . None of the above
CHAPTER PROJECTS
Project 1: Personal Web Site
For your project in this chapter, you should construct the external
style sheet for your site to adjust the initial HTML so it is displayed
according to your visual prototype. While you have only one page now, it
will be imperative to have an external style sheet before the next chapter,
so you can adjust global settings and styles quickly and have them apply
to all pages. Make sure to save and test your work in a Web browser.
CHAPTER EXERCISES
1. Give an example of when you would use a style set on a
tag name, a class to be invoked, and a single ID within
a document. Explain the reason for this choice in each
circumstance.
C h a pt e r 4 — C S S 3 — 119
10. The use of the style attribute in HTML elements should
be limited to absolute necessity. Explain why using this
attribute undercuts some of the power and usefulness of CSS.
Justify your position.
C h a pt e r 4 — C S S 3 — 121
CHAPTER
5
HTML5
I N T HI S CHAP T E R
This chapter ends the design phase of the site and moves
into content creation and establishing functionality. As part
of this chapter, you will establish a firm site map so you
can plan the navigation correctly. You will also incorporate
hyperlinks for creating a fully connected and functional site.
This chapter also includes an expansion of the HTML tag
usage you have already learned to facilitate content creation
and presentation on the individual site pages using HTML
version 5 (or HTML5). Once you have completed this chapter,
you should be able to:
● Create a site map for a project and establish
consistent branding of pages
● A dd hyperlinks and image hotspots to establish
page connectivity
● A dd content to a page, including line breaks,
tables, and forms
● A dd multimedia elements to your site,
including video, audio, and plug-in content
5.1 BRANDING A SITE
One of the most important things on a Web site is consistency of
elements across all of the pages of the site. Maintaining this consis-
tency helps to establish the professionalism and credibility of your
site. This is an essential element of presentation on any site, and it is
one of the reasons the careful creation of a visual prototype is such a
worthwhile exercise. Establishing consistent navigation and making
sure you have working links is necessary for any site. Users are driven
away from any site with even a single broken link; this will destroy
any credibility on the site regardless of how much effort was put into
the display or the content.
5.1.1 Planning for Content
The next exercise that you need to complete as you move forward
in the visual presentation of the site is establishing the pages of con-
tent you will have. This will allow you to construct a consistent naviga-
tion strategy for your site so users can find content easily when they
go from page to page within the site. It is important to make sure the
content of a single page is all very closely related. Any content that
extends below the bottom of the screen (requiring the user to scroll)
should be structured so that the important information is listed at the
top and users are required to scroll down only if they are interested in
the content that is lower on the current page. You also want to make
sure that your Web pages are clearly identified and that the text link-
ing to the Web page is closely associated with the link text for clarity.
For this text, you will establish a consistent navigation strategy for your pages in
the project. In more advanced sites, you can dynamically generate the naviga-
tion text and even make it context sensitive. Doing this generally requires either
NOTE
JavaScript or a back-end server-side language like PHP or PERL.
for any of this, but context-sensitive menus and expanding menus are options
to reduce the number of clicks and still preserve a small navigation area on the
page. These are more advanced topics than introductory HTML and support-
ing languages. Courses or books on human-computer interface will help in this
regard.
You can use PowerPoint to create a site map, just as you did to cre-
ate your initial visual prototype. The rectangle shapes and the lines
you used then are good for constructing a map of content pages for
the site. You should start with the homepage (index.html) and expand
the content links from that. You can see an example of a site map in
Figure 5.1.
For the sample project, you will construct four pages, including the
homepage. The homepage will include the content about the company.
The additional pages will include a contact page, a menu of bever-
ages and/or food, and a page with directions and hours. For most sites,
the navigation system would be much more extensive than this and
C h a pt e r 5 — H T M L 5 — 12 5
FIGURE 5.1 Site Map for the Sample Project
would have different levels. The sample projects for this text while you
are getting started all have simple navigation with a small number of
pages.
5.1.3 Hyperlinks
One of the most essential tools for Web site construction is hyper-
links. A hyperlink in terms of Web pages is a connection between
resources, commonly used to link one page to another or to link sec-
tions within a page. The tags for this are the anchor tags, <a> and </
a>. There are two uses for a hyperlink: to link to a resource outside the
page (external referencing) and to provide a connection to a bookmark
within the same page (ID referencing). The href (or hyper-reference)
C h a pt e r 5 — H T M L 5 — 12 7
…
<div id=”logo” name=”logo”><a href=”
index.html”><img id=”logo_img” alt=”Zippy Beans
Logo” src=”Media/logo.png” /></a> </div>
<div id=”menu” name=”menu”><a href=”menu.
html”>Menu</a> | <a href=”direct.html”>Hours and
Directions</a> | <a href=”contact.html”>Contact
Us!</a></div>
…
</body>
When you view this in a browser, you will see that by default the
display of any hyperlinked text is to display as blue with an under-
line. Visited links by default display as underlined purple text. You
can change this appearance by creating a CSS command set for the
anchor tag that sets the color and text-decoration values.
You can also use hotspots to link pieces of an image. Hotspots are
clickable sections of an image defined through an image map; most
Web authoring tools have the ability to create these easily. This is use-
ful for large images that you want to map to multiple locations. The
most common types of hotspots are rectangles and circles, but it is also
possible to define your own custom hotspots point by point.
In some browsers, wrapping an image tag with anchor tags will cause the
image to have a border displayed around it. To eliminate this, you can add the
CSS command border: 0; to the style definition for the <img> tag.
NOTE
The common expectation in modern Web sites is to click the logo of the page to
return to the homepage of the site. You should make sure to provide this
functionality either by linking your entire logo image to the homepage or by
creating a hotspot within your banner to allow a user to go back to the start of PROFESSIONAL
TIP
the site.
With the Pictures tool active, you can simply draw the shape on
the image to create the hotspot. A series of prompts will appear, ask-
ing you to provide the link and alternative text information for each
hotspot you create. The code generated by this will look as follows:
<map name=”Map” id=”Map”>
<area shape=”circle” coords=”56,48,36” href=”index.
html” alt=”Home Page” />
</map>
You can create this code manually, but it requires knowing exactly
where you want the shape placed and the pixel coordinates of its ver-
tices and/or radius distance.
an image link around the logo to link to index.html. You should also add
links to the <div> tag for navigation to each of the pages in your site individu-
ally. Be sure to define a CSS style set for the anchor tag, so the hyperlink text
will be displayed correctly on your page. You can also adjust the width of the
menu element to account for the size of the navigation system.
C h a pt e r 5 — H T M L 5 — 12 9
5.1.5 Meta Tags
Another support tag that you should consider for your site is the
<meta> tag, which is used to provide information about the site. (meta
information is information about information.) These tags appear
inside the page header (between the <head> and </head> tags). The
common attributes used in a <meta> tag are name and content. The
name attribute specifies the type of <meta> tag, and the content attri-
bute specifies the value associated with the name attribute. An exam-
ple of this is:
<meta name=”author” content=”Dr. Theodor
Richardson”>
There are a number of common <meta> tags that can be used to
provide site information. Some of the common <meta> tag names are:
• description: The content item for this is a text description of
the page and its contents.
• author: The content item for this is the name of the page
author.
• keywords: The content item for this is a comma-separated list
of key terms by which the page should be identified by search
engines.
• robots: This is a de facto standard for whether pages will be
indexed by a search bot (like those used by Google) or whether
the links in the page will be followed for further site explora-
tion. The default value for this is “index, follow,” allowing
search bots to index the page and follow the links in it. To
disallow one or the other, just add no in front of the term. A
full exclusion would be “noindex, nofollow,” but you can also
specify these values independently (such as “index, nofollow”).
Remember that new tags should be introduced only for structural elements.
Since the subheading has to be formatted differently from the banner text and
the disclaimer has to be positioned within the footer, both of these additions fall
NOTE
into this category.
With the added <div> tags, CSS definitions, and content for these
common elements, the code for your index.html page should be:
<head>
<title>Zippy Beans Coffee Co.</title>
<style type=”text/css”>
…
a {
color: #fff;
text-decoration: none;
}
#menu a {
background-color: #3c3;
border-radius: 4px;
}
#disclaimer {
margin-top: 40px;
font-size: 8pt;
}
C h a pt e r 5 — H T M L 5 — 131
#subhead {
font-size: 22pt;
}
</style>
</head>
<body class=”grad”>
<div id=”banner” name=”banner”>Zippy Beans
Coffee Co.<div id=”subhead”>Totally Organic, Man!</
div></div>
…
<div id=”bottom” name=”bottom”><div id=
”disclaimer”>This is a fictional company. No coffee
beans were harmed in the making of this site.<div>
</div>
</body>
Figure 5.2 shows the result of adding these new <div> elements.
This should be your final index.html if you have followed along with
the examples so far.
You may notice the style entry for #menu a in the sample code in this sec-
tion. This is an example of a complex class that applies only to <a> tags within
the <div> tag with the ID value menu. This can be a powerful way to format PROFESSIONAL
elements within other elements without calling each of them by name or TIP
C h a pt e r 5 — H T M L 5 — 13 3
FIGURE 5.3 Sample favicon.ico for the Case Project
When you have finished your icon, make sure to save it as favi-
con.ico in the root folder (your project folder) for your site. You can do
this by selecting the Download Favicon link at the bottom of the icon
display. These icons may not be displayed when you are viewing your
local copy, but they should be displayed once your site is hosted on a
Web server.
C h a pt e r 5 — H T M L 5 — 13 5
Remember that you can control the behavior of the <p> tag with CSS com-
mands. This includes setting indents and margins for the text within the para-
graph tag wrapper.
NOTE
Unlike the case with HTML tags, capitalization does matter in ampersand com-
mands just as it does in simple text. There are diacritics marks which can apply
to either the lowercase or uppercase character and will need to be capitalized
NOTE
correctly to display the correct variant.
C h a pt e r 5 — H T M L 5 — 137
Just like <div> tags, <table> tags can be nested inside each other. To do this,
you just need to start and end the table inside a single table data cell of the
original table.
NOTE
A comment in HTML begins with <!-- and ends with -->. Anything between
these will be ignored by the browser but can still be seen by a user viewing the
source code for the page.
NOTE
You can control table display with CSS commands, just as you can
control the display of other elements. The CSS commands text-align
and vertical-align control the horizontal and vertical placement of con-
tent within <td> tags. Inside the <table> tag, you can place attributes
for cellpadding (the distance between cell walls and content) and cell-
C h a pt e r 5 — H T M L 5 — 13 9
spacing (the distance between cells). You can see these together in the
content for the menu.html page for the sample case project:
<div id=”content” name=”content”>
<table cellspacing=”0” cellpadding=”4”>
<tr>
<td></td>
<td>Mini-Large</td>
<td>Large</td>
<td>Gallons</td>
</tr>
<tr>
<td>Zippy Coffee</td>
<td>$3.50</td>
<td>$3.75</td>
<td>$15.50</td>
</tr>
<tr>
<td>Zippyccino</td>
<td>$4.50</td>
<td>$5.50</td>
<td>$27.50</td>
</tr>
<tr>
<td>Zippy Mochaccino</td>
<td>$5.50</td>
<td>$6.50</td>
<td>$29.50</td>
</tr>
<tr>
<td>Double Zippyspresso</td>
<td>$3.50</td>
<td>$4.50</td>
<td>$25.50</td>
You can use CSS commands to control the cellpadding and cellspacing
in a <table> tag, but this is one instance in which it is recommended that you
use the HTML attributes for formatting. The CSS alternative for cellspacing PROFESSIONAL
(the border-collapse command) is not well supported across browsers, TIP
and it will be overridden by the value of the HTML attribute anyway. The pad-
ding CSS command can be used in place of cellpadding tag attribute if you
are defining table styles already, but the padding style command should be
applied to the <tr> and <td> tags.
C h a pt e r 5 — H T M L 5 — 141
• method: This attribute has two common values, POST and
GET. POST submits the form data to the action destination
as a packet. GET places the information in the query string
after the action address in a URL; this is the less secure
and less common way to process forms.
C h a pt e r 5 — H T M L 5 — 14 3
The selection type for form input works differently from other form
input types. The listed items each have their own tag within a wrap-
per of <select> and </select>. The <select> tag just requires a name
attribute. Each possible value is wrapped in <option> and </option>
tags. The <option> tag has to have a value attribute which defines
the value of the selection when that option is chosen. You can add the
standalone attribute (one with no value pairing) selected to one of the
<option> tags to give it a default value. You can see an example of a
selection tag for salutations here:
<select name=”salutation”>
<option value=”Miss”>Miss</option>
<option value=”Mrs”>Mrs.</option>
<option value=”Ms”>Ms.</option>
<option value=”Mr”>Mr.</option>
<option value=”Dr” selected>Dr.</option>
<option value=”Sir”>Sir</option>
<option value=”Madam”>Madam</option>
</select>
To put all of this together, the code for the contact form (on the
contact.html page) for the sample case project should be:
<div id=”content” name=”content”>
<form name=”contact” action=”contact.php”
method=”POST”>
Name:
<select name=”salutation”>
<option value=”Miss”>Miss</option>
<option value=”Mrs”>Mrs.</option>
<option value=”Ms”>Ms.</option>
<option value=”Mr”>Mr.</option>
<option value=”Dr” selected>Dr.
</option>
<option value=”Sir”>Sir</option>
<option value=”Madam”>Madam</option>
If you preview the form with this code, everything will be displayed correctly,
but it will not be formatted nicely. In order to control the display of your form
elements, you should consider placing them in a table. This will allow for con- PROFESSIONAL
sistent spacing and alignment of the form entries and the descriptive text. It is TIP
a worthwhile practice exercise to convert the form for the sample project to a
table layout.
C h a pt e r 5 — H T M L 5 — 14 5
preferred format for video is MP4. Most audio and video construction
software packages support these formats. The source file for either an
audio or video element should be referenced for this tag using a single
<source> tag. You can see an example of these tags here:
<audio controls=”controls”>
<source src=”example.mp3” type=”audio/mp3” />
</audio>
Unless the site has a specific need for background audio, you should not add
this type of sound to your pages. Consider that it will play whenever a user
enters the page; it can get obnoxious quickly and will drive users away. With
NOTE
that said, there are sites for which this works, such as band Web sites and sites
for movies and games. In general, though, it should be avoided.
page you created to add to the project information. You can change any of the
information given for these pages, but you should be sure to practice using the
tags to create the specified content. Be sure to consider the display of your
content as well and add CSS style sets as needed to format your display. Be
sure to test your pages in multiple browsers.
C h a pt e r 5 — H T M L 5 — 147
CHAPTER SUMMARY
This chapter concluded the creation of the static content for your
site. This represents the initial functional prototype for the site. The
next step is to implement any dynamic content and the processing
of the form content that you have set up in this chapter. You may
have noticed that the form content directs users to a page that has not
been created. The next chapter will focus on the JavaScript language
and how it can be used to validate input and manipulate display ele-
ments. Chapter 7 focuses on form processing and directing content
using back-end languages like PHP and PERL. Finally, Chapter 8
covers the integration of MySQL for managing data on a Web site.
You should now have the tools to construct almost any page in HTML
and format it for display using CSS commands.
● A. border
● B. cellpadding
● C. cellspacing
● D. colspan
● E. None of the above
● A. rowspan
● B. colspan
● C. merge
● D. mergecells
● A. Rectangle
● B. Oval
● C. Circle
● D. Pentagon
● E. All of the above
● F. None of the above
Which of the following tags defines a table cell?
6
● A. <table>
● B. <td>
● C. <tc>
● D. <th>
● E. All of the above
● F. None of the above
C h a pt e r 5 — H T M L 5 — 14 9
Tables can be nested inside of other tables in a page, just as <div> tags can
7 be nested.
● A. True
● B. False
Input values outside of a form will not be processed when the form is
8 submitted.
● A. True
● B. False
Which of the following tags requires an end tag?
9
● A. <input>
● B. <img>
● C. <br>
● D. <textarea>
● E. None of the above
CHAPTER PROJECTS
Project 1: Personal Web Site
For this project, you should create a site map for your personal site.
You should plan pages for your site that are relevant and important
as individual topics. It is better to have more content on the homepage
than to create unnecessary pages. You should choose what to show-
case on your site and focus on that. Unnecessary pages will deter an
audience, so your site will not promote you as it should. You should
CHAPTER EXERCISES
1. Describe two cases in which you would want to use comments
in an HTML file. Should these comments ever be allowed to
remain in the HTML document even when the site is posted
live?
4. Give at least three possible uses for the hidden input type in
a form. With your examples, consider that a user can view
the content of these hidden items when viewing the page’s
source code.
C h a pt e r 5 — H T M L 5 — 151
not display correctly without the use of this special character
format?
6. Use the Web to find at least two <meta> tags that are not
mentioned in this chapter. Explain what information they
provide about the page and what their purpose is.
10. Use the Web to research the CSS commands to create a first-
line indentation for paragraphs. Construct the style set for
the <p> tag to enable this functionality.
6. The <th> tag can be used to provide a header row for a table.
Use the Web to research this tag and its application. What is
the benefit of using this tag? Is this required for formatting a
table correctly? Explain your answer.
10. The <object> and <embed> tags serve similar purposes for
adding non-standard content to an HTML document. Compare
these two tags and identify whether both are needed. Justify
your position.
C h a pt e r 5 — H T M L 5 — 15 3
CHAPTER
6
JavaScript and jQuery
I N T HI S CHAP T E R
</script>
…
</head>
<body>
…
</body>
</html>
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 15 7
use of this tag is optional and typically unnecessary. An example of
the use of the <noscript> tags follows:
<html>
<head>
<script type=”text/javascript”>
</script>
<noscript>Your browser does not support
JavaScript, so the content of this page may not
display as expected on your system.</noscript>
…
</head>
<body>
…
</body>
</html>
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 15 9
characters use single quotation marks and strings use double
quotation marks, but either is valid syntax in JavaScript.
• Strings: These are combinations of characters stored as a
single value. A string must be wrapped in quotation marks
(such as “Hello, World!”). By convention, strings are wrapped
in double quotation marks, but both double and single quota-
tion marks are valid syntax in JavaScript.
x = (x*4)/3 + y - 1;
s1 = s1 + “” + s2;
</script>
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 161
To call (or invoke) a function in JavaScript, you type the name of
the function (which must be defined in code prior to the function call),
followed by a left parenthesis, the arguments you wish to use accord-
ing to the function’s definition, a right parenthesis, and a semicolon.
The alert() function, for instance, has one parameter, which accepts
the text you wish to display as an alert. When you invoke the function
and assign a specific value to the parameter, the value is called an
argument. You can use literal values or variables as arguments when
you invoke a function in JavaScript. Parameters appear in function
definitions, and arguments appear in function calls. Function defini-
tions are covered in section 6.1.4.
The alert() function does not return a value, so you can call it with-
out storing the result in another variable. An example of using the
alert() function in JavaScript follows:
<script type=”text/javascript”>
alert(“Hello, World!”);
</script>
cript. Within the script tags, add the function call for the alert() function using
“Hello World!” as the argument. Save the page as jshello.html and test the
results in a Web browser. Explain why the alert() function would be useful in
a page. How could overuse of the alert() function be a detriment to the user
experience? Justify your answer with examples.
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 16 3
To call this function, you need to do something with the returned
value. You can set it to a new variable or assign the result to an exist-
ing variable. For trivial functions, it is better not to return anything,
since the value is meaningless; the return statement is included here
only for clarity of syntax. An example of the function definition and
call for the message_me() function is:
<script type=”text/javascript”>
functionmessage_me(param) {
alert(param);
return true;
}
function message_me2(param) {
alert(param);
var d = false; // This variable exists
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 16 5
For conditional expressions, the following symbols can be used to
evaluate comparisons of variables, functions, and literal values:
• > will evaluate to true if the left side of the statement is
greater than the right side; an example of this is (x > y)
• >= will evaluate to true if the left side of the statement is
greater than or equal to the right side ; an example of this is (x
>= y)
• < will evaluate to true if the left side of the statement is less
than the right side; an example of this is (x < y)
• <= will evaluate to true if the left side of the statement is less
than or equal to the right side; an example of this is (x <= y)
• == will evaluate to true only if both sides of the statement are
equal; an example of this is (x == y)
• != will evaluate to true only if both sides of the statement are
not equal; an example of this is (x != y)
Multiple values can be concatenated with logical operations
for the conditional statement as well:
• || represents an OR condition, which evaluates to true if
either side of the statement is true; an example of this is (x ||
y)
• && represents an AND condition, which evaluates to true only
if both sides of the statement are true; an example of this is (x
&& y)
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 16 7
// This will execute if the variable == ‘B’
break; // This stops execution from moving
to the next case default:
// This will execute if no other case
matches the variable
break; // This is not necessary, but it is
good coding practice
}
6.1.6 Looping
Looping is a repeated execution of the same set of statements. This
is incredibly helpful if an action needs to be repeated or if a similar
action needs to be performed repeatedly (such as counting from 1 to
5). There are three different basic types of loops that can be used in
JavaScript: for, while, and do/while. Each of these will continue to
operate while a condition is still valid.
It is possible to create loops that do not ever stop. This happens if the condition
for execution never becomes false; these are called infinite loops, and they
will crash the user’s browser. You must always make sure the loops you create
NOTE
will terminate.
There is also a for/in loop for working with arrays of data, but that is beyond the
scope of this text and represents one of the more advanced functionalities of the
JavaScript language.
NOTE
A while loop has a simpler structure than a for loop. One thing to
remember when using a while loop is to make sure the condition is
eventually updated to become false; this will prevent it from being an
infinite loop. An example of a while loop demonstrating such a struc-
ture is:
var x = 0;
while (x < 5) {
// These are statements that will execute when
the condition is true
alert(x + 1);
x = x + 1; // This is the statement to update the
condition
}
In this instance, the operation is the same as that in the for loop
outlined in the previous example. You should note where the state-
ments have been placed in the while loop. The only requirement for
the while loop is having a conditional statement to evaluate. The
last statement of the code block is there to make sure the while loop
will terminate, as well as setting the increment for the count. Most
for and while loops can be written interchangeably, but care must be
taken to make sure the operation is correct when converting between
them.
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 16 9
A do/while loop has a structure similar to that of a while loop, but
it forces execution of the loop once before testing the condition at all.
An example of a do/while loop showing the syntax is:
var x = 0;
do {
/* These are statements that will execute once
and will repeat if the condition is true */
alert(x + 1);
x = x + 1; // This is the statement to update the
condition
} while (x < 5); // This will determine the condi-
tion for continuation
Loop statements can also be nested to perform more complex com-
putations and functions. Loops are incredibly useful and very adapt-
able tools for coding in any language.
x = x*2 + y;
alert(x); // This will display the current value of x
x = x/3;
alert(x); // This will display the new value of x
</script>
It is important to remember to comment out or delete the alert()
functions used to debug your code prior to posting it live on your site.
6.2.2 String Parsing and Form Validation
One of the most useful applications of JavaScript since its inception
is to provide client-side form validation (making sure the user-entered
data in the form is correct). JavaScript has a library of functions for
use in parsing and comparing strings. These will be explored to con-
struct a form validation script for the case project. This will make sure
that each field in the contact form is completed correctly before it is
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 171
submitted to the destination identified in the action attribute of the
form.
Anything that comes from the client-side browser cannot be trusted, so form
validation needs to be done on both ends to verify the data before it is used in
a back-end application, where it could corrupt a database or cause problems in
PROFESSIONAL
TIP an online system if it is incorrect. Being aware of security is a responsibility of
developers as well as of security specialists.
There are several fields that need to be completed and some that
have data considerations, particularly the e-mail address for the user.
To begin, a function should be constructed to process the form data
before sending it to the back-end server (for repeat processing). Every-
thing in JavaScript is an object within a hierarchy on the page, so this
structure will be used to identify each piece of the form that will be
validated. This structure can take time to understand, so try to follow
each example closely and understand how the references work before
moving to the next. The JavaScript that will provide the form valida-
tion framework is:
<!DOCTYPE html>
<html>
<head>
…
<script type=”text/javascript”>
Function validateContact() {
// This will be the function body
return true;
}
</script>
</head>
<body>
…
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 17 3
if (document.contact.email.value.length<= 0) {
alert(“The email field cannot be empty.”);
return false;
}
if (document.contact.message.value.length<= 0) {
alert(“The message field cannot be
empty.”);
return false;
}
return true;
}
Note that each of these fields must be evaluated separately, so
each one requires a separate if statement to evaluate the length for
a potential problem. The issue with the code above is that once there
is a failure in the validation, it ends and returns false. It is better to
let the user know what all of the problems are with the form at once
rather than force them to resubmit for each one, so the false value will
be determined by a new variable called okay, which is initially set to
true (so the form will be submitted) and then set to false if there is a
problem. You can see this new code in action below:
function validateContact() {
var okay = true;
if (document.contact.myname.value.length<= 0) {
alert(“The name field cannot be empty.”);
okay = false;
}
if (document.contact.email.value.length<= 0) {
alert(“The email field cannot be empty.”);
okay = false;
}
if (document.contact.message.value.length<= 0) {
alert(“The message field cannot be empty.”);
The escape character (\) has to be used in strings and regular expressions
when you want to use a literal character in place of one that would otherwise
terminate the string or expression. For instance, to add a double quotation mark
NOTE
within a string, you have to escape the double quotation mark as follows:
“This string contains a \” mark” to make it a valid string in JavaScript.
Whenever you want to reference the escape character itself as a literal value,
you have to escape the escape character as follows: \\.
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 175
The code to perform the validation test described on the content of
myname is:
function validateContact() {
var okay = true;
…
var pattern = /;|’|”|&|\\/g;
if (pattern.test(document.contact.myname.value))
{
alert(“The name field contains invalid
characters. These include & ; ‘ \” and \\.”);
okay = false;
}
returnokay;
}
Note the use of the escape character in both the regular expression
and the string that is being used as the argument for the alert. The
test() function works only on regular expression objects like the one
defined for the pattern variable. Once again, this same test should be
applied to the e-mail and message fields as well.
While these tests are sufficient for the myname and message fields,
some additional tests need to be performed on the e-mail field to make
sure it at least has the necessary structure of an e-mail address. It
is almost impossible to truly validate an e-mail address, but the two
characteristics it must have are a single @ character and at least one
period after the @ with at least two characters after it. This test will
be performed to make sure the e-mail address fits the basic structure,
though the address may still be invalid.
To test for specific characters in an e-mail address or any string,
there are two methods within the string object that can be used:
indexOf() and lastIndexOf(). Both of these accept characters as argu-
ments and will return an integer value indicating where in the string
the character occurs. If the value returned is –1, then the character is
not located within the string. Note that the first character in a string
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 17 7
can be used to select them individually; the value of the field will not
work for this purpose. You should be familiar with using ID values in
tags now, so you can add the following code to create an ID for each
radio box:
*** INSERT CODE
<form name=”contact” action=”contact.php”
onsubmit=”return validateContact();” method=”POST”>
…
<input type=”radio” name=”preference” id=”pref_
email” value=”Email”>Email<br />
<input type=”radio” name=”preference” id=”pref_
phone” value=”Phone”>Phone<br />
…
</form>
You can now use JavaScript to test whether either of these is
selected. The method to find a tag by its ID value is getElementById().
This accepts a string value as an argument to reference the ID inside
the tag. The method for testing whether a radio button is selected is
called checked. The code to test whether either of the options is selected
is:
function validateContact() {
var okay = true;
…
if (!document.getElementById(“pref_email”).checked
&& !document.getElementById(“pref_phone”).checked) {
alert(“A preferred method of contact must be
selected.”);
okay = false;
}
return okay;
}
This code will generate an error if both “E-mail” and “Phone”
remain unselected. This is accomplished by inverting the result of the
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 17 9
<input type=”checkbox” name=”subscribe”
value=”Yes”> Subscribe to the Zippy Beans
newsletter!<br />
<div id=”message_err”></div>
Message:<br/>
<textarea name=”message” rows=”4” cols=”50”>
</textarea> <br/>
<input type=”submit” value=”Submit!”>
</form>
You can test this in a browser to see that the empty <div>tags do
not change the display at all. You can add style classes to these ele-
ments so they are displayed in red text to alert the user to the content.
The means to access the contents of an HTML tag as a JavaScript
object within a page is called innerHTML. This value can be retrieved
as a string or set to a new string value. An example of this for the first
error in the name value is:
function validateContact() {
…
if (document.contact.myname.value.length <= 0) {
document.getElementById(“name_err”).
innerHTML = “The name field cannot be empty.”;
okay = false;
}
…
}
Try to submit the form with an empty name value to see this effect
in action. All of the remaining alerts will still generate pop-ups, but
the name length error will show up in the page.
Adding this code to each of the errors would be cumbersome, so
it will be easier to create a new function that will perform this task.
You can then reference the function for each of the errors generated. A
sample function to perform this task is:
functionerrDisplay(elementID,message) {
functionvalidateContact() {
…
}
You can now replace the alerts with calls to the new function, such
as:
function validateContact() {
…
if (document.contact.myname.value.length<= 0) {
errDisplay(“name_err”,”The name field
cannot be empty.”);
okay = false;
}
…
}
The final step is to clear the error values whenever the form is
submitted. This can be accomplished using the same function already
defined:
function validateContact() {
var okay = true;
errDisplay(“name_err”,””);
errDisplay(“email_err”,””);
errDisplay(“method_err”,””);
errDisplay(“message_err”,””);
…
}
You can see an example of this functionality in Figure 6.1.
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 181
FIGURE 6.1 Sample Functionality of Dynamic Form Content
</form>
Finally, the event code that will call the function whenever the
radio button selection is changed is:
<form name=”contact” action=”contact.
php” onsubmit=”return validateContact();”
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 18 3
method=”POST”>
…
<input type=”radio” name=”preference” id=”pref_
email” onchange=”phoneDisplay()”value=”Email”>Email
<br />
<input type=”radio” name=”preference” id=”pref_
phone” onchange=”phoneDisplay()”value=”Phone”>
Phone<br />
…
</form>
This is just one example of an event in JavaScript. These can be
added to almost any tag that allows user interaction and can be coded
to react to the user’s exploration of the page.
contact.js. Briefly describe what JavaScript content was moved out of the
HTML page and what was left in the page. What are the benefits of using exter-
nal files for JavaScript? Is it important to use external JavaScript for a single
page in the site, as in the example here? Justify your answer.
6.3 JQUERY
As it has developed, JavaScript has been modified with function-
ality that applies only to specific browsers. A notable example of this
is separate functionality on Internet Explorer and Mozilla Firefox.
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 18 5
While this is not part of the core functionality of JavaScript, it can
be used to provide significant enhancements to a user’s experience. It
can be used for effects such as repositioning elements on the screen
or creating dynamic tooltips. To get around the browser differences
and take advantage of this functionality, developers have to write code
that identifies the browser and then operates based on the specific
browser’s format.
Libraries have been developed to simplify this type of coding across
browsers and generally make it easier for developers to use the more
advanced features of JavaScript. One of the most popular and compre-
hensive of these libraries is jQuery, which is available for free down-
load at http://jquery.com. This library allows you to create dynamic
pop-ups, add drag-and-drop functionality, and perform a myriad of
other tasks with simplified coding. The remainder of this chapter will
provide a brief introduction to using jQuery, but this is an extensive
library that, like JavaScript itself, would take more than one chapter
to fully explore.
6.3.1 Installing jQuery
From the jQuery Web site (jquery.com), there are two options for
the code you wish to download, Development and Production. The
Development selection is the more straightforward, but it has a larger
file size; this is uncompressed code that will be either displayed in the
browser or downloaded to your machine. If the code is displayed in
your browser, you can copy the page (use Select All if necessary) and
save the results as jquery.js. If you download the file to your machine,
you can rename the file jquery.js or use the original file name in your
source path.
The Production (compressed) file for the jQuery library has a different nam-
ing convention. The Development version is used in this chapter for clarity and
simplicity. The Development version makes the jQuery library readable should
NOTE
you wish to explore how any of its functions work.
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 18 7
.myphone {
display: none;
}
.show {
display: block;
}
You also need to adjust the structure of the <div> tags that contain
the phone number. This involves adding a class to hide the entry and
adding the form field itself within the structure of the page. The code
for this is:
*** INSERT CODE
<form …>
…
Preferred Method of Contact: <br/>
<input type=”radio” name=”preference”
id=”pref_email” onchange=”phoneDisplay()”
value=”Email”>Email<br />
<input type=”radio” name=”preference”
id=”pref_phone” onchange=”phoneDisplay()”
value=”Phone”>Phone<br />
<div id=”phone_div” class=”myphone”>Phone
Number: <input type=text name=”phone”></div>
<input type=”checkbox” name=”subscribe”
value=”Yes”> Subscribe to the Zippy Beans
newsletter!<br />
…
</form>
You also need to add the jQuery library to your contact.html page,
using the instructions in the previous section. With this enabled, you
can take advantage of the addClass() function in jQuery to dynami-
cally adjust the CSS of an element within the page. The similar func-
tion removeClass() will take away a class from a tag. Both of these
take a string argument that references a CSS class defined in the
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 18 9
CHAPTER SUMMARY
This chapter showcased JavaScript and its ability to create
dynamic content within a page and alter the display of a single page
based on user interaction. This is an incredibly powerful language
that can be added seamlessly into HTML documents across all mod-
ern browsers, from desktops to mobile devices. The jQuery library was
also introduced, with instructions for its inclusion in Web sites and its
practical use. JavaScript is a client-side language, so all of the content
created up to this point can be tested on a local browser. The remaining
two chapters of this text focus on server-side languages, which require
Web hosting in order to test and use them, since the server compiles
the code before delivering the result to the client browser. The next
chapter introduces you to two server-side scripting languages and
gives a brief overview of Web hosting.
● A. True
● B. False
Which of the following is a valid variable declaration in JavaScript?
4
● A. var a; b
● B. var a = This text;
● C. var a = true
● D. var a, b;
● E. None of the above
● A. default
● B. case
● C. break
● D. do
● E. All of the above
● F. None of the above
The type of data stored in a JavaScript variable does not have to be specified
7 when the variable is declared.
● A. True
● B. False
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 191
jQuery is a separate programming language that interacts with JavaScript
8 inside an HTML page.
● A. True
● B. False
A coding library is a ____________.
9
● A. complete syntax for a scripting or programming
language.
● B. method for defining an external file containing
code.
● C. collection of functions that can be reused in
code.
● D. All of the above
● E. None of the above
A value can be assigned to a variable in JavaScript at the time it is defined.
10
● A. True
● B. False
CHAPTER PROJECTS
Project 1: Personal Web Site
For this project, you should create the validation for the contact
page on your site. This should do a first pass on the data entered to
make sure it is valid. Document your code with comments to explain
the process of validation that is being performed. Be sure to add the
structural elements to your HTML to allow reporting of any errors
within the fields themselves.
CHAPTER EXERCISES
1. Describe the two formats for comments in JavaScript. Give
two examples for cases in which each would be useful in code.
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 19 3
8. Can any if-else statement be converted to a switch statement
in JavaScript? Can any switch statement be converted into
an if-else statement? Give examples to explain your answer.
C h a pt e r 6 — J ava S c r i pt a n d j Q u e r y — 19 5
CHAPTER
7
PHP and Perl
I N T HI S CHAP T E R
C h a pt e r 7 — P H P a n d Pe r l — 19 9
• Traffic/bandwidth limitations: This is the amount of traffic
that your site will be allowed to use each month. This may be
tracked in terms of concurrent connections to the site or over-
all volume of data downloaded. You should carefully review
what happens if this limit is exceeded; this can cause the host
to suspend your site (which is bad for viewers), slow down
traffic to your site, or charge you for the overage incurred. The
purpose and audience size for the site should determine this
metric. You should also research your ability to change this
bandwidth based on traffic patterns once your site is live; it is
typically easier to increase bandwidth on a plan than it is to
reduce it. Higher bandwidth often costs more money.
• Languages supported: This is the listing of server-side program-
ming languages that are supported by the hosting option. For
the purpose of this text, you should look for hosting options
that support PHP and/or Perl as well as MySQL for data stor-
age (which will be covered in the next chapter). There are other
popular server-side languages, such as JSP, ASP, and Ruby on
Rails, that you may wish to learn once you are familiar with the
concepts of front-end and back-end programming on the Web.
There are a myriad of different Web sites that offer hosting solutions and ser-
vices. Some of these sites are safe, and some of them will take your personal
information to sell. You have to be very careful with what you give to any Web
PROFESSIONAL
TIP site, especially your credit card information. You should always look at cus-
tomer reviews for the service before you share any information with the site. If
you have to enter any information to get the prices or product information, you
should generally avoid that site. Any reputable Web hosting service will offer its
service details up front without requiring any information from you.
The author of this text has consistently used GoDaddy® (www.godaddy.com)
as a hosting company for several years without any significant issues. Overall, it
has been a reliable and cost-effective solution that supports most of the major
languages used for programming on the Web. If you are looking for a hosting
solution that is safe and reliable, the author recommends GoDaddy as a starting
point.
and allowed traffic/bandwidth per month and on the languages supported. You
should generally consider only hosting options that support PHP and/or Perl as
well as MySQL unless you have experience with another server-side program-
ming language. Write a short report on the hosting option you will use. If you
are using this text independent of a college or university that provides you with
server space, you should consider purchasing at least short-term hosting to test
the results of your code for the case project and assignments within this chapter
and the next chapter. The basic hosting plan from GoDaddy meets these general
criteria.
7.2 PHP
PHP is a recursive acronym that stands for Hypertext Preproces-
sor. Like that of Perl, though, the reality of this acronym is up for
debate; the original author of the toolset that would become PHP, Ras-
mus Lerdorf, named his toolkit Personal Home Page Tools, or PHP
Tools. PHP is one of the most common server-side languages in use
today. It is a very powerful language, and it embeds easily into any
HTML document. PHP documents can reside anywhere within a Web
site and use the extension .php. When a server is configured with it,
PHP will automatically process the page on the server before sending
the result to the client machine when it encounters this file type. Host-
ing options that offer PHP typically require little to no configuration
from the user before using PHP within the server pages.
Because server-side languages process their output before sending the results
to the client machine, they are not interactive. The results of the code will be
processed linearly and send to the client; any content changes or dynamic inter-
NOTE
action on the page will require that the results be sent back to the server for it to
re-process the results. Client-side languages like JavaScript can bridge the gap
in interactivity and minimize the number of times the server must be invoked to
produce new content.
C h a pt e r 7 — P H P a n d Pe r l — 2 01
7.2.1 PHP Basics
PHP code can be embedded directly into an HTML document,
allowing you to establish the framework and structure of the page and
to provide data processing and dynamic content. This is ideal if you
are learning HTML and CSS for the first time, because it allows you
to utilize what you already know and build an additional language
into the structure. PHP is inserted as tags into a page, just like other
HTML elements. The tags for PHP are <?php to open the PHP code
and ?> to close the PHP code. Any text that exists between these tags
will be treated as code.
PHP must be installed on the server in order for PHP pages to compile. If it is not
installed, the source code itself will be displayed without processing on most
browsers, which will treat the PHP tag indicators as unknown tags; other
NOTE browsers will produce an error. PHP is free to install, but you must have
administrative rights on the server to do so. The best option for beginners is to
select hosting that includes PHP on the server already.
The function echo is used to print code to the browser. This will
display content on the user’s machine after the server processes the
page. You can see an example of this here:
<!DOCTYPE html>
<html>
<head>
<title>My PHP Page</title>
</head>
<body>
<?php
echo”Hello, PHP!”;
?>
</body>
</html>
As in the example, each line of PHP ends with a semicolon, just
as it does for JavaScript. In fact, all of the concepts used in
C h a pt e r 7 — P H P a n d Pe r l — 2 0 3
?>
</body>
</html>
C h a pt e r 7 — P H P a n d Pe r l — 2 0 5
$_POST[“myname”] = substr($_POST[“myname”], 0, 50);
The parameters in this case specify the string value to use, the
starting value, and the number of characters to include beginning
with the starting value. Here, 0 is used as the starting value, because
the string starts counting with 0 as the first character. The length
value of 50 will take 50 characters from the starting value 0.
You can test the length of a string in PHP by using the function strlen, which
takes the string data as its only parameter and returns the number of characters
found in the string.
NOTE
contact.php page to perform these tasks as needed for every field in the
form. The page should display the content that the user submitted. As a chal-
lenge, you should display it in a format that will show the meaning of the con-
tent. Save your work as part of the case project. If you have a hosting solution
already, you should test this page on the server to make sure it works correctly.
C h a pt e r 7 — P H P a n d Pe r l — 2 0 7
7.2.3 E-mailing with PHP
Now that you are able to access and manipulate the data from
the form, you can apply it to a useful purpose. For a contact page, it
is ideal to e-mail the contact information to an administrator who can
then return the contact if needed or log and process the information.
The mail command in PHP can be used to send e-mail from the server
to any valid address.
Not all hosting options allow you to set the e-mail addresses of the sender and
receiver. This is a limitation you should investigate with the host prior to select-
ing your plan. The risk of this functionality is that a Web application may be
NOTE
used for generating unwanted spam, so some hosts either charge a premium
rate for this functionality or disable it.
echo $_POST[“myname”];
C h a pt e r 7 — P H P a n d Pe r l — 2 0 9
ever.com>’ . ‘\r\n’;
$mailme = mail(‘[email protected]’,
‘Contact Entry Information’, ‘The name field is ‘ .
$_POST[“myname”], $headers);
?>
</body>
</html>
Note the concatenation to include the form field value of myname.
You should expand this example to include all of the form fields in both
the form processing and the e-mail body to provide a more complete
form-processing solution. The next chapter will explore how to use
this data to populate a database.
7.3 PERL
Perl has famously been called the “the duct tape of the Internet” by
Hassan Schroeder. It is a language that was intended to combine the
convenience of shell scripting with the more robust features of full lan-
guages like C and C++. It is one of the most commonly used and well-
supported server-side languages, as well as one of the oldest in use on
the Web. Even when other server-side languages are not supported
on a server, Perl is typically available for use. It is not as convenient
to use as PHP, and it requires specific invocation of the Perl binary
executable file in order to work correctly. Perl is also not as forgiving
The path given is the most common path to the Perl executable, but this value
must match the location of the Perl binary file on the specific server, so there
may be instances where this path will not work and you will have to investigate
NOTE
where the binary executable files are stored for the specific server. Hosting
solutions will typically provide you with a path if they support Perl.
C h a pt e r 7 — P H P a n d Pe r l — 211
following code would be used:
#!/usr/bin/perl
print “Hello, Perl!”;
This is the function you will use to write HTML to the browser
from a Perl file. For the case project, you could use the following code
in Perl to produce a page similar to the example for PHP:
#!/usr/bin/perl
C h a pt e r 7 — P H P a n d Pe r l — 213
hex($1))/eg;
$FORM{$name} = $value;
}
This is complex code beyond the scope of beginner programming;
for now it is best for you to copy the code and evaluate its meaning as
you become more advanced with the language and its use.
Perl can be a difficult language, especially when you are attempting to configure
it on a new server. However, Perl’s strength is its wide net of availability and its
consistency. The code may take time to get right, but it will work anywhere with
PROFESSIONAL
TIP minor adjustments of paths from that point forward. The learning curve of Perl is
more like that of a true programming language that takes patience and time.
The net result of this code is the ability to refer to the form field
through the $FORM variable. An example of this is shown for refer-
encing the myname field in the form from contact.html:
$FORM{‘myname’}
The code for making sure the format of the data in the form fields
is suitable for use in the Web application is also more complex in Perl.
To limit the length of the myname field to 50 characters, you can use
the substr operator similarly to the way it was used in PHP:
$FORM{‘myname’} = substr($FORM{‘myname’},0,50);
To remove unsafe characters, the code uses the substitution oper-
ator for regular expressions and an empty substitution string as a
replacement. This uses the regular expression list from JavaScript as
a basis for removing these unsafe characters:
$FORM{‘myname’}=~ s/;|’|”|&|\\//g;
Finally, to eliminate HTML or XML tags from the form data, you
can use another regular expression that identifies tag formatting and
replaces it with an empty string. An example of this is:
$FORM{‘myname’}=~ s/<!--(.|\n)*-->//g;
The elimination of unsafe characters and HTML/XML tags can be
done inside the main code to produce the $FORM variable. Putting all
C h a pt e r 7 — P H P a n d Pe r l — 215
7.3.3 E-mailing with Perl
E-mailing information with Perl uses the same print function that
is used to write output to the browser. Instead of using the default
action, though, you will specify an output stream on which to write the
content. The wrapper for this structure is:
open (MAIL, “|/usr/sbin/sendmail to.address@wher-
ever.com”);
print MAIL “This is the email content...”;
Here the open function is used to create a new stream of informa-
tion; in this case it is opening a path to the e-mail executable on the
server. The second part of the string identifying the e-mail path is
the address to which the e-mail will be sent. The common path to the
e-mail executable sendmail is:
/usr/sbin/sendmail
However, just as with the Perl executable, you must specify the
specific path to the sendmail executable on the server itself, which
may vary from server to server.
Just as you used the print function to build the HTML page, you
will use it here to build the e-mail headers and message. This should
include the From and Subject lines. After the header, be sure to indi-
cate a double new line character (\n\n); this will signify to the e-mail
processor that it is has moved from the header to the body of the mes-
sage. You can see an example of this here:
print MAIL “Reply-to: [email protected]\n”;
print MAIL “From: [email protected]\n”;
print MAIL “Subject: This is the subject line\n\n”;
print MAIL “This is the message body.”;
Finally, when the content of the e-mail is complete, you will close
the stream, which will send the e-mail message and continue with the
execution of the rest of the Perl code. An example of this is:
close (MAIL);
C h a pt e r 7 — P H P a n d Pe r l — 217
print “<!DOCTYPE html>”;
print “<html>”;
print “<head>”;
print “<title>My Perl Page</title>”;
print “</head>”;
print “<body>”;
print$FORM{‘myname’};
print “</body>”;
print “</html>”;
C h a pt e r 7 — P H P a n d Pe r l — 219
Server-side languages process their results when invoked; this means they
2 are not interactive to the client without the client’s sending another request to
the server.
● A. True
● B. False
PHP code can be embedded into any HTML page and will work without
3 changing the file extension of the page.
● A. True
● B. False
The exact path to the binary executable file for PHP must be included in every
4 page that uses the language.
● A. True
● B. False
PHP code must be written as a standalone file, with no HTML elements
5 included.
● A. True
● B. False
Variables in both PHP and Perl are signified by the dollar sign ($) before the
6 actual variable name.
● A. True
● B. False
Which of the following functions is used to produce output to the browser in
7 Perl?
● A. open
● B. echo
● C. print
● D. All of the above
● E. None of the above
● A. True
● B. False
The ‘at’ symbol (@) must be used to denote an array in both PHP and Perl.
9
● A. True
● B. False
Which of the following represents the new line character in both PHP and
10 Perl?
● A. \r
● B. \n
● C. \g
● D. \s
● E. None of the above
CHAPTER PROJECTS
Project 1: Personal Web Site
For this project, you should create a form processing solution for
the contact page of your site. It should test the input sent by the user
and make sure it will not harm the server. This test should be per-
formed on the client side and again on the server side. The results
should be sent to your e-mail address after the form is processed. Find
hosting for your site and test the code to process the contact form.
C h a pt e r 7 — P H P a n d Pe r l — 2 21
CHAPTER EXERCISES
1. Since the server-side languages execute linearly, is there
a need to define functions in these languages, or should
everything be written to execute once as the code is
interpreted or compiled? Use examples to justify your answer.
10. Compare the syntax of PHP to that of either ASP or JSP for
embedding code in an HTML document. What is the benefit
of being able to embed dynamic content in a page? Explain
your answer using examples.
C h a pt e r 7 — P H P a n d Pe r l — 2 2 3
your answer and give two examples of when this would be
useful or necessary.
7. Briefly explain the reason that languages like PHP and Perl
can be used to send e-mail from a server to a computer but
JavaScript is not capable of generating and sending e-mail on
the client side. What effect would it have if JavaScript had
that capability?
C h a pt e r 7 — P H P a n d Pe r l — 2 2 5
CHAPTER
8
MySQL
I N T HI S CHAP T E R
8.1 MYSQL
MySQL (www.mysql.com) is currently the most popular open
source database software used in Web sites. Adding MySQL to a
server or choosing a hosting service with MySQL installed will allow
you to create and manage databases from the server-side languages
you learned about in the previous chapter. PHP in particular has a
very simple interface for accessing a MySQL database. The construc-
tion of databases is a complex process that is beyond the scope of this
book, so this chapter will focus on a specific example for the case proj-
ect that can be adapted for more complex situations as you learn more
in the field of database design and practice with the other Web lan-
guages for creating more complex Web applications.
MySQL is one of the component software pieces associated with the common
LAMP server configuration, which stands for Linux, Apache™, MySQL, and PHP/
Perl. The configuration of the Apache server is a separate topic, but you should
NOTE
have the tools and skills to develop Web sites for a LAMP server when you have
completed all of the objectives in this text.
C h a pt e r 8 — M y S Q L — 2 2 9
ber of characters allowed is specified as n. The data type
CHAR(n) will allow only fixed-length strings with n char-
acters; if the stored value is smaller than the fixed value,
it will be right-padded with spaces. The more versatile
VARCHAR(n) allows strings of variable length up to length
n; this is the most common storage mechanism for text fields,
such as the contact entries you will record in the sample
database. For longer text, you can specify a TEXT(n) field,
which has a higher storage capacity: up to 65,535 characters,
compared to the VARCHAR maximum of 255. Using TEXT
as a data type can be wasteful, though, if it is not needed.
Other variations of text, such as BLOB, also exist in MySQL
for more specialized purposes.
Other data types exist in MySQL; the list here represents only
the most commonly used types you are likely to encounter as you
begin your work as a Web developer. For instance, there are data
types for DATE and TIME to record these specific data values,
which can be recorded as either strings or numbers. This list is
enough to get you started with using MySQL, but it is nowhere
near a complete listing of all of the available options. Whenever
you create a database, you need to consider the data storage
carefully.
8.1.2 Creating a MySQL Database
Most hosting solutions will offer you a graphical user Interface
(GUI) for creating and modifying MySQL tables. The example shown
in this chapter is from GoDaddy.com, which provides a GUI from
Starfield® Technologies, Inc. Other solutions may be text-based,
which would give you an input/output stream that would allow you
to configure MySQL directly. For this reason, both the graphic form
of the table and the SQL code will be presented, so you can perform
this task in either environment. Regardless of the means of creating
the table, the most important consideration is the names and types
of the fields you will include in your table.
and use the data from the user. This has to be enforced on the front end (with
JavaScript error detection) and strictly enforced on the server side (with PHP
or Perl); values with a higher length than the allowed storage limit must be
either rejected with no storage or truncated to fit within the size allowed by the
database.
For the contact.html form in the case project, the following fields
should be stored in the database:
• E-mail: This is the e-mail entry on the form; it will always be
text. A rough size of 50 would be a starting point for allocating
this field. It should be given the data type VARCHAR(50).
• Salutation: This is the greeting given along with the name.
The maximum length of the preset options for this field is
currently 4, but this may not be an exhaustive list for interna-
tional users. Therefore, this will be allocated as VARCHAR(5)
to allow for any unknown additions needed later. This is fine
here, since the database size will remain small, but it may be
a consideration when the records will number into the hun-
dreds or thousands.
• Name: Since this field contains a first and a last name (which
is typically not recommended, since they are distinct data ele-
ments), the length of 50 should account for most names. This
will be allocated as VARCHAR(50); the testing is already in
place to be certain of this limit in the PHP and Perl examples
from the previous chapter.
• Method: There are only two options for this field, and both
contain 5 letters. Therefore, this field should be allocated as
VARCHAR(5).
• Phone: The variation in formatting of phone numbers in differ-
ent countries means there should be extra space allocated for
international numbers and hyphens. A rough size of 15 char-
acters should suffice for most of these variations. This size can
be adjusted later, but it can only contract and not expand from
the values already stored in the table.
C h a pt e r 8 — M y S Q L — 2 31
• Subscribe: This is a simple yes-or-no item based on whether
the box is checked or not. Therefore, it is a good candidate for
BOOL, where TRUE means the subscribe box was checked
and FALSE means it was not.
• Message: This represents the full text of the message the
customer wants to send. It will therefore be the longest field
in the contact entry. It is a good candidate for the TEXT data
type, though it is wise to limit its size in the form processing
stage in both JavaScript and the server-side language.
Figure 8.1 shows the result of creating this table. Note that the
SQL statement that created the table is shown above the structure
information for the table itself.
FIGURE 8.1 Sample Table for the Zippy Beans Contact Form
One final element that is required for any MySQL table is a pri-
mary key. This is a means of organizing the information in a table and
referring to a specific record. The selection of a primary key is typically
a complicated process. In this instance, there are no good candidates
from the existing data for creating a primary key. Therefore, another
field is needed for this table, to complement the record and create a
primary key. The combination of the submission date/time and the
e-mail information makes a unique identifier for this information.
The submission date should be added to the table as the field sub-
mission and stored as VARCHAR(25). Most date formats are not 25
There are DATETIME, DATE, and TIME data types available in MySQL
for storing date and time information, but converting between these data types
and the server-side languages can be a complex process. For that reason, a NOTE
The primary key can be added visually using the GUI or via SQL
with the following statement:
ALTER TABLE ‘zippy’ ADD PRIMARY KEY ( ‘submission’ ,
‘email’ )
Now that these steps are completed, the table is ready for use. In
order to use this table for data storage and retrieval, you will need to
understand the syntax of SQL queries and the means of calling the
database in the server-side language.
C h a pt e r 8 — M y S Q L — 2 3 3
ACTIVITY 8.1 – CREATING A MYSQL TABLE
For this activity, you will use the hosting service you selected to create a MySQL
ACTIVITY table for storing the form data from the contact.html page. You should
name the table zippy and follow the examples above for allocating the data
types and lengths for the table structure. Your hosting provider should have
tutorials or technical support available for you if you need help in setting up your
MySQL account or even creating a table for the first time. You should take the
time to get this set up now, so you can proceed with the use of this table in the
later activities of the chapter. The basic hosting plan from GoDaddy meets the
general criteria for MySQL with a GUI option for creating tables (under infor-
mation_schema in the PHP administrator screen for database manage-
ment).
Multiple fields can be selected in a single select query by separating the field
names with commas. Similarly, multiple clauses can be added to a WHERE
clause; each condition must be joined with either AND or OR. Parentheses
NOTE
must be used to create complex conditions.
C h a pt e r 8 — M y S Q L — 2 3 5
8.2.3 Insert Queries
The insert query is used to add a new record in an existing table.
This will be the type of query you will use to store new records from
the contact form in the database. The structure of an insert query in
SQL is:
INSERT INTO y (x) VALUES (v)
In this example, y is the table name, x is the field (or list of fields
separated by commas), and v is the value (or list of respective values
separated by commas). In this format, the number of entries in x and
in v must be identical for the query to be processed without an error.
An example of this for storing a new name in the database would be:
INSERT INTO zippy (submission, email, name) VALUES
(‘12/12/12’,’[email protected]’,’Bob’)
The values listed will be stored in the same order as the names of
the specified fields.
The primary key must be included for an INSERT statement in SQL to work.
In the sample case, every record added must include an e-mail address and a
date of submission.
NOTE
C h a pt e r 8 — M y S Q L — 2 37
You can add simple validation code to determine if the link was a
success or a failure based on the returned value. One possible solution
for this is:
$hostaddress = “hostaddress”;
$username = “username”;
$password = “password”;
$link = mysql_connect($hostaddress, $username,
$password);
if (!$link) {
// This is the fail case for the connection...
}
Here, the value of $link is inverted, so the conditional statement
will execute to account for the error only if $link is false.
The remaining step is to select the database within the account
after the connection is established. Most of the time, you will create
a new database for each project unless a limit on databases or tables
is imposed by the hosting provider. If you are using shared database
hosting, this may be just the account name. If you have multiple data-
bases, then you should select the one that is used for the relevant proj-
ect. Note that this is the name of the overall database and not a single
table within the database. The command in PHP to select a MySQL
database is:
mysql_select_db(“database_name”);
Here, database_name is just the actual name of the database you
are selecting for the PHP page to use. If you invoke this function when
the MySQL connection attempt has failed, it will generate an error.
Once the connection has been established and the database has
been selected, you can run queries against the database as often as
needed during the execution of the page. Every new invocation of the
page (or any other page on the site) will require a new connection to
the database. When you are finished with the connection, you should
close it with the function:
mysql_close($link);
database you constructed in Activity 8.1. You should test this connection by sub-
mitting form data through the contact.html page and viewing the output.
Be sure to include the verification testing for the connection with a visual output
showing that the connection attempt has failed. Be sure to close the connection
when you are done.
C h a pt e r 8 — M y S Q L — 2 3 9
$query = “INSERT INTO zippy (submission, email, sal-
utation, name, method, phone, message) VALUES (‘” .
$submission_date . “’,’” . $_POST[‘email’]) .”’,’”
. $_POST[‘salutation’] . “’,’” .
$_POST[‘name’] . “’,’” . $_POST[‘preference’] .
“’,’” .
$_POST[‘phone’] . “’,’” . $_POST[‘message’] . “’)”;
$result = mysql_query($query);
The values entered are all strings, so they need to be surrounded
with single quotation marks, since the overall query string is sur-
rounded with double quotation marks. Note the use of concatenation
on the overall string to get the variable data from PHP. It is advis-
able to use a conditional evaluation to test whether the query was
successful.
$result = mysql_query($query);
The variable $result now contains all of the returned records or the
FALSE result if the query failed. It is always advisable to test for the
FALSE case when you run a SQL query.
In order to process the results, you must first extract each record
from the returned set. This is accomplished using the mysql_fetch_
array function, which returns an array of strings matching the order
of the parameters given in the select query. Every time this function is
called, it will pull out the first available record and remove it from the
set. An example of this is:
$submission_date = date(“m/d/y H:i:s”);
$query = “SELECT name, message FROM zippy WHERE sub-
mission = ‘” . $submission_date . “’ AND email = ‘”
. $_POST[‘email’]) .”’”;
$result = mysql_query($query);
$row = mysql_fetch_array($result);
C h a pt e r 8 — M y S Q L — 2 41
If this code executes and successfully returns a record, $row is now
an array in which $row[0] contains the name and $row[1] contains the
message.
If there are no records returned, it is imperative that this be deter-
mined before use of any of the array values. Using an array value if
the record is empty will cause an error in the PHP application. The
conditional evaluation isset can be used to determine whether the
variable contains data (in this circumstance and others). One test for
the successful extraction of a record in such a case is:
$submission_date = date(“m/d/y H:i:s”);
$query = “SELECT name, message FROM zippy WHERE sub-
mission = ‘” . $submission_date . “’ AND email = ‘”
. $_POST[‘email’] .”’”;
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if (isset($row)) {
// The record is present and can be used...
} else {
// The record is not present and the row is empty...
}
You should plan a fail case for the application if the SQL queries
do not work, since any part of the application that depends on the
result will not work properly.
C h a pt e r 8 — M y S Q L — 2 4 3
Which of the following is not a reserved word in SQL?
2
● A. SELECT
● B. FROM
● C. WHERE
● D. INSERT
● E. All of the above
● F. None of the above
Multiple fields can be selected in a single SQL query by separating the values
3 with a ____.
● A. comma
● B. period
● C. semicolon
● D. slash
The numerical value in a MySQL data type declaration specifies the number of
4 characters or digits that can be stored in the field.
● A. True
● B. False
Data values specified in a SQL insert query are all specified as strings,
5 regardless of how they are stored in the database.
● A. True
● B. False
The ___ clause specifies the conditions for identifying a record in SQL.
6
● A. SELECT
● B. WHERE
● C. FROM
● D. WHILE
● E. None of the above
● A. True
● B. False
Which of the following is not a valid PHP function for working with MySQL?
8
● A. mysql_query
● B. mysql_close
● C. mysql_connect
● D. All of the above
● E. None of the above
The conditional isset is used in PHP to determine whether a variable has been
9 assigned data by returning TRUE or FALSE.
● A. True
● B. False
A SQL query can return multiple records at the same time.
10
● A. True
● B. False
CHAPTER PROJECTS
Project 1: Personal Web Site
For this project, you should create a database table to store the
contact information from the contact form and process that form using
PHP. The data results should be e-mailed to your e-mail address and
stored in the database for later use. Document your code to indicate
the actions taken in PHP. Test and verify your solution.
C h a pt e r 8 — M y S Q L — 2 4 5
stored in the database for later use. Document your code to indi-
cate the actions taken in PHP. Test and verify your solution.
CHAPTER EXERCISES
1. What is the benefit of creating the database access code
as a separate PHP page? Research the inclusion of PHP
pages in other pages and convert the database access code
to its own page. If this included page is used to initiate a
connection to the database, where should the database be
closed in the code?
C h a pt e r 8 — M y S Q L — 2 47
2. Briefly explain the main components of a LAMP stack as a
server configuration. What is the purpose of each component,
and how do they represent a complete Web application
environment when combined?
C h a pt e r 8 — M y S Q L — 2 4 9
APPENDIX
A
Selected Answers
Chapter 1
Chapter Knowledge Check
1. d
3. c
5. c
7. b
9. b
Chapter 2
Chapter Knowledge Check
1. c
3. b
5. a
7. b
9. b
Chapter 3
Chapter Knowledge Check
1. e
3. b
5. c
7. a
9. b
Appendix — 2 5 3
Chapter 4
Chapter Knowledge Check
1. d
3. c
5. e
7. c
9. c
Chapter 6
Chapter Knowledge Check
1. d
3. a
Appendix — 2 5 5
5. d
7. a
9. c
Chapter 7
Chapter Knowledge Check
1. b
3. b
5. b
7. c
9. b
Chapter 8
Chapter Knowledge Check
1. f
3. a
5. a
7. a
9. a
Appendix — 2 5 7
would need specific code depending upon the type of database
to which they are connected, which would increase develop-
ment cost and limit flexibility.
5. Using SQL queries to create database tables within Web appli-
cations could cause multiple duplicate tables to be created or
even a new table for each use of the application. This is a poor
decision for design and it would make managing the database
incredibly difficult. The system would likely become unstable
as a result.
7. There are a variety of additional uses for isset in a Web appli-
cation aside from testing whether a record is present in a
MySQL result. These include testing for the presence of a vari-
able within a form or as output from a function. This is often
essential to test before using a variable that does not exist,
which would cause an error on the page.
A Styles panel, 47
Active Server Pages use of, 60
(ASP), 197, 200 character entity in HTML, 136
Adobe Dreamweaver, cloning of pages, 131–133
35, 46–47, 138 color choice in a page, 25–26
Adobe Flash® object, 146 computational complexity, 156
alert() function, 171 conditional statements, 165–168
alt attribute, 71
ampersand command, D
136–137
anchor point, 86 database, 228
AND operator, 179 decomposing the prototype, 58–59
Apple Safari, 6 default statement, 167
argument, 162 design set for the site, 42–44
Arial, 22 of Zippy Beans Coffee
Company, case project, 45
digital typography, 22–23
B display-oriented CSS
back-end languages, 197–198 background images, 97–99
Bitmap (BMP), 63 colors property, 99–103
break statement, 167 content alignment, 104
setting borders, 103–104
C shadows property, 104–105
text modification, 106–107
Cascading Style Sheets (CSS) Doctype Declaration (DTD), 12–13
classes and tags, 81–82 dollar ($) sign, 189
CSS3, 80 Domain name registration,
defined, 79 198–199
display properties, 97–107 Domain Name Service (DNS), 199
height and width properties, do/while loop, 170
91–94 dynamic content, 179–182
IDs, 82–83
inheritance, 84 E
invoking styles in HTML,
elastic measurement, 91
80–81 e-mail accounts, 199
layering, 89–91 e-mailing
margins, 94–97 JavaScript, 173, 175–178
padding, 94–97 Perl, 216–218
positioning, 84–89 PHP, 208–209
pseudo-classes, 83 embedded code, 146–147
reusing of styles, 108–109 entry, 228
style command, 80 equals sign (=) syntax, 160
Styles Panel, 49 escape character (), 175
Inde x — 2 5 9
event in JavaScript, 182–184 forms, adding, 141–145
exercises/review questions, hyperlinks, creating, 126–127
chapter, 31–34, 54–56, image links/hotspots, creating,
75–78, 118–120, 151–153, 127–129
193–195, 222–225, 246–249 incorporation of audio and
external JavaScript, 184–185 video on Web pages,
145–146
F less than () or greater than ()
field, 228 characters, 136
File menu, 46, 48 meta tags, 130–131
fonts, 23–24 paragraphs and line breaks,
footer.png, 69 135–136
for loop, 168–169 planning for content, 124
frames, 61 rowspan attribute, 139
function, 161–162 site icon, adding, 133–134
site map, creating, 125–126
G tables, adding, 137–141
global referencing, 16 text-align and vertical-align
GoDaddy®, 198, 200 control, 139
Google Chrome, 6 value attribute, 142–143
Google Maps™ hyperlink, 126–127
application, 147 hyper-reference property, 109
Graphics Interchange Hypertext Markup Language
Format (GIF), 63 (HTML), 4, 6–7
add a hyperlink, 15–16
images, creating, 63–72
H page construction, 10–18
height and width CSS page testing, 17–18
properties, 91–94 site layout,
hotspots, 127–129
creating, 57–62
href attribute, 16, 127
HTML authoring tools
Adobe Dreamweaver, 46–47 I
Microsoft Expression Web, id attribute, 71
48–49 if statements, 166–167, 174
Notepad++, 49–50 images, creating
HTML version 5 (HTML5) banner and footer images, 72
ampersand command, 136–137 banner section, 67
branding a site, 124–134 formats, 63–65
capitalization, issues with, 137 in Pixlr, 69
cellpadding and cellspacing, for sites, 67–70
139–140 software for, 65–67
cloning of pages, 131–133 tag for inserting, 70–72
colspan attribute, 139 inheritance of style, 84
content, adding, 135–147 innerHTML, 180
copyright symbol, creating, 137 Insert menu, 46, 48
2 6 0 — Inde x
Internet Assigned Numbers validateContact() function, 173
Authority (IANA), 199 value property, 173
Internet Corporation for variable declarations, 158–159
Assigned Names and Java Server Pages (JSP), 197, 200
Numbers (ICANN), 199 JPEG (Joint Photographic
Internet Explorer, 185 Experts Group) File
Internet Protocol version Interchange Format, 63, 67, 69
4 (IPv4), 199 jQuery library
Internet Protocol version addClass() function, 188
6 (IPv6), 199 code, 187–189
installation of, 186–187
J removeClass() function, 188
JavaScript, 49–50, 61
alert() function, 162, 171 K
assigning values, 159–161
kerning, 24
client-side nature of, 157
knowledge check, chapter,
comments in, 160 28–30, 51–53, 73–74,
conditional statements in, 116–118, 148–150, 190–
165–168 192, 219–220, 243–244
declaring variables, 159–160
defining functions, 163–164
dynamic content of, L
179–182 layering in CSS, 89–91
e-mail and message fields, 173, leading, 24
175–178 library, 161–162
events, 182–184 looping, 168–170
external, 184–185
form validation, 172–179 M
function calls, 161–162
getElementById() function, 178 margins, 94–97
meta tags, 130–131
in HTML, 157–158
Microsoft Expression
indexOf() function, 176 Web, 48–49, 138
lastIndexOf() function, 176 Microsoft Internet
length property, 173 Explorer (IE), 5–6
looping, 168–170 monospacing, 23
mathematical operations Mozilla Firefox, 6, 185
using, 161 MySQL
message_me() function, 164 accessing a, 228
multiple values in, 161 accessing database of,
parsing and comparing strings, 237–239
171–179 Boolean specification in, 229
rules for naming functions, 163 characters and strings in,
symbols of variables, 166 229–230
test() function, 175 creating a databse, 230–234
using, 170–185 data types, 228–230
Inde x — 2 61
date and time in, 229–230 position property of CSS, 84–89
decimal data type in, 229 element position, 85–89
graphical user Interface (GUI) setting positioning and anchor
for, 230 points, 87–89
integer specification in, 229 values, 85
retrieving data from database, PowerPoint, 125
240–242 programming language, 156
storing data in database, projects, chapter, 30–31,
239–240 53, 75, 118, 150–151,
192–193, 221, 245–246
using with PHP, 236–242
R
N relational database, 228
Notepad++, 49–50, 108 relational database management
system (RDMS), 228
relationship property, 108
P relative referencing, 16
padding, 94–97 Ruby on Rails, 200
page testing, 17–18
parameter, 162
PERL, 46 S
Perl sans-serif, 23
basics, 211–212 scope of a variable, 164
e-mailing with, scripting language, 156
216–218 serif, 23
form processing, 212–215 server-side language, 156
PHP, 46, 228 server-side languages, 198
basics, 202–203 server-side programming
e-mailing with, 208–209 languages, 200
server space, 199
form processing, 204–207
site icon, adding, 133–134
MySQL with, 236–242 site layout
pipe character (|), 175
decomposing a design, 58–59
pixel, 23
pixels, 86 planning of functionality, 58
planning of Web site site layout in HTML
audience, 40–41 method for constructing
design and development layouts, 60–62
process, 36–38 structuring a page, 60
design set for the site, 42–44 using HTML text, 60–62
site map, creating, 125–126
emphasizing and showcasing
src attribute, 70–71, 127
content, 41–42 Stanford Web Credibility
initial client communication, Project, 21
38–40 Structured Query Language
purpose, 40–41 (SQL), 227
Portable Network Graphic insert queries, 236
(PNG), 63, 67, 69 select queries, 234–235
2 6 2 — Inde x
update queries, 235 common, 5–6
style commands, 80, 84 Webmonkey Web site
switch statement, 167 Web page, 4–6
Web pages, principles of
color choice, 25–26
T
considering purpose and
table, 229 audience, 21
Tag Image File Format (TIFF), 63 evaluation of page, 27
text adjustment properties
page layout and real estate,
font-family, 106
19–20
font-size, 106
typography and font selection,
font-style, 106
22–24
font-weight, 106 Web server, 3
text-decoration, 106 Web site, 3
text-shadow, 106–107 hosting a, 197–200
Times New Roman, 22 planning of. see planning of
tracking, 24
Web site
type attribute, 157
typefaces, 22 traffic patterns, 200
What You See Is What You Get
(WYSIWYG) view, 47
U while loop, 169
Uniform Resource Locator WHOIS database, 199
(URL), 1, 8–9 World Wide Web Consortium
(W3C), 4, 8, 19
World Wide Web (WWW), 1–3
V W3Schools, 80
values in JavaScript WYSIWYG display, 4
Boolean values, 159
character values, 159–160 Y
integer and decimal values, You Tube®, 147
159
string values, 160
variable, 156 Z
View Selection, 47 z-index property, 89–90
W
Web browser, 3–6, 24, 62
Inde x — 2 6 3