JavaScript for Programmers 1st Edition Paul J. Deitel instant download
JavaScript for Programmers 1st Edition Paul J. Deitel instant download
https://ebookgate.com/product/javascript-for-programmers-1st-
edition-paul-j-deitel/
https://ebookgate.com/product/c-20-for-programmers-3rd-edition-p-
deitel/
ebookgate.com
https://ebookgate.com/product/javascript-for-impatient-programmers-
es2020-edition-dr-axel-rauschmayer/
ebookgate.com
https://ebookgate.com/product/c-how-to-program-7th-edition-paul-j-
deitel/
ebookgate.com
https://ebookgate.com/product/herding-cats-a-primer-for-programmers-
who-lead-programmers-1st-edition-j-hank-rainwater/
ebookgate.com
C How to Program 6th Edition Paul Deitel
https://ebookgate.com/product/c-how-to-program-6th-edition-paul-
deitel/
ebookgate.com
https://ebookgate.com/product/android-how-to-program-2nd-edition-paul-
deitel/
ebookgate.com
https://ebookgate.com/product/c-how-to-program-9e-9th-edition-paul-
deitel/
ebookgate.com
https://ebookgate.com/product/learning-the-ios-4-sdk-for-javascript-
programmers-create-native-apps-with-objective-c-and-xcode-1st-edition-
goodman/
ebookgate.com
JAVASCRIPT™
FOR PROGRAMMERS
DEITEL® DEVELOPER SERIES
De i te l ® Se r
How to Program Series
Java How to Program, 7/E
C++ How to Program, 6/E
Visual C++® 2008 How to Program, 2/E
C How to Program, 5/E
Internet & World Wide Web How to Program, 4/E
Visual Basic® 2008 How to Program
Visual C#® 2008 How to Program, 3/E
Small Java™ How to Program, 6/E
Small C++ How to Program, 5/E
Simply Series
Simply C++: An Application-Driven Simply C#: An Application-Driven
Tutorial Approach Tutorial Approach
Simply Java™ Programming: An Simply Visual Basic® 2008, 3/E: An
Application-Driven Tutorial Application-Driven Tutorial
Approach Approach
To follow the Deitel publishing program, please register for the free Deitel® Buzz
Online e-mail newsletter at:
www.deitel.com/newsletter/subscribe.html
or write to
deitel@deitel.com
Check out our Resource Centers for valuable web resources that will help you master
Visual C#, other important programming languages, software and Internet- and web-
related topics:
www.deitel.com/ResourceCenters.html
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks.
Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have
been printed with initial capital letters or in all capitals.
The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty
of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential
damages in connection with or arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales,
which may include electronic versions and/or custom covers and content particular to your business, training goals,
marketing focus, and branding interests. For more information, please contact:
U. S. Corporate and Government Sales
(800) 382-3419
corpsales@pearsontechgroup.com
For sales outside the U. S., please contact:
International Sales
international@pearsoned.com
Visit us on the Web: www.phptr.com
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission
must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission
in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding
permissions, write to:
Text printed in the United States on recycled paper at R.R . Donnelley in Crawfordsville, Indiana.
First printing, February 2009
JAVASCRIPT™ FOR
PROGRAMMERS
DEITEL® DEVELOPER SERIES
Paul J. Deitel
Deitel & Associates, Inc.
Harvey M. Deitel
Deitel & Associates, Inc.
Throughout this book, trademarks are used. Rather than put a trademark symbol in every occurrence of
a trademarked name, we state that we are using the names in an editorial fashion only and to the benefit
of the trademark owner, with no intention of infringement of the trademark.
To Brendan Eich:
For creating the JavaScript language while at
Netscape Communications Corporation.
Preface xv
1 Introduction 1
1.1 Introduction 2
1.2 History of the Internet and World Wide Web 3
1.3 World Wide Web Consortium (W3C) 5
1.4 Web 2.0 5
1.5 Key Software Trend: Object Technology 7
1.6 JavaScript: Object-Based Scripting for the Web 8
1.7 Browser Portability 9
1.8 Web Resources 9
2 Introduction to XHTML 10
2.1 Introduction 11
2.2 Editing XHTML 12
2.3 First XHTML Example 12
2.4 W3C XHTML Validation Service 15
2.5 Headings 15
2.6 Linking 16
2.7 Images 19
2.8 Special Characters and Horizontal Rules 22
2.9 Lists 24
2.10 Tables 27
2.11 Forms 31
2.12 Internal Linking 38
2.13 meta Elements 40
2.14 Web Resources 42
Index 395
This page intentionally left blank
Preface
… the challenges are for the designers of these applications: to forget what we think we know
about the limitations of the Web, and begin to imagine a wider, richer range of possibilities. It’s
going to be fun.
—Jesse James Garrett, Adaptive Path
“Ajax: A New Approach to Web Applications”
(adaptivepath.com/ideas/essays/archives/000385.php)
Introduction
Welcome to JavaScript for Programmers! We’ve worked hard to create what we hope you’ll
find to be an informative, entertaining and challenging learning experience. At Deitel & As-
sociates, we write programming language professional books and textbooks for Prentice
Hall, deliver corporate training at organizations worldwide and develop Internet businesses.
This book reflects the client side of today’s Web 2.0, Ajax-based, Rich Internet Appli-
cation-development methodologies. The technologies you’ll learn here are appropriate for
experienced professionals who build substantial web-based applications. You’ll find “indus-
trial-strength” code examples that are clear, straightforward and promote best practices.
Today’s users are accustomed to desktop applications with rich graphical user inter-
faces (GUIs), such as those used on Apple’s Mac OS X systems, Microsoft Windows sys-
tems, various Linux systems and others. Users want applications that can run on the
Internet and the web and communicate with other applications. Users want to apply data-
base technologies for storing and manipulating their business and personal data. They
want applications that are not limited to the desktop or even to some local computer net-
work, but that can integrate Internet and web components, and remote databases. Pro-
grammers want to use all these capabilities in a truly portable manner so that applications
will run without modification on a variety of platforms.
We focus on the client side of web-based applications (i.e., the portions that typically
run in web browsers such as Mozilla’s Firefox, Microsoft’s Internet Explorer, Apple’s
Safari, Opera, Google’s Chrome and other web browsers), using technologies such as
XHTML, JavaScript, CSS, Extensible Markup Language (XML) the DOM (Document
Object Model) and Ajax (Asynchronous JavaScript and XML).
This book was extracted from the front half our Prentice Hall textbook Internet &
World Wide Web How to Program, 4/e. That book also provides substantial treatments of
key Rich Internet Applications development server-side technologies, including web
servers, database, PHP, Ruby on Rails, ASP.NET/ASP.NET Ajax, JavaServer Faces and
web services.
Perhaps most important, this book presents over 100 working code examples and
shows the outputs produced when these examples are rendered in browsers. We present all
xvi Preface
concepts in the context of complete working programs. We call this the “live-code
approach.” All of the source code is available for download from
www.deitel.com/books/jsfp/
Please see the Before You Begin section following the Preface for details on downloading
these examples.
If you have questions as you read this book, send an e-mail to deitel@deitel.com—
we’ll respond promptly. For updates on the book and the status of all supporting software,
and for the latest news on Deitel publications and services, visit www.deitel.com. Sign up
at www.deitel.com/newsletter/subscribe.html for the free Deitel® Buzz Online e-mail
newsletter and check out www.deitel.com/ResourceCenters.html for our growing list of
Internet and web programming, Internet business, Web 2.0 and related Resource Centers.
Each week we announce our latest Resource Centers in the newsletter.
Key Features
Here’s some of the key features of JavaScript for Programmers:
• Reflects the client side of today’s Web 2.0, Ajax-based, Rich Internet Applica-
tion-development methodologies in which you create web applications with the
interactivity of desktop applications.
• Covers the two leading web browsers—Internet Explorer and Firefox. All client-
side applications in the book run correctly on both browsers.
• Focuses on Web 2.0 technologies and concepts.
• Chapter on building Ajax-enabled web applications with “raw” Ajax and with the
Dojo JavaScript libraries. Applications in this chapter demonstrate core Web 2.0
capabilities—partial-page updates and type-ahead.
• Significant treatment of client-side scripting with JavaScript.
• Significant treatments of XHTML DOM manipulation and JavaScript events.
• Significant treatment of XML DOM manipulation with JavaScript.
• Client-side case studies that enable you to interact with preimplemented server-
side applications and web services that we host at test.deitel.com.
• Case studies including Deitel Cover Viewer (JavaScript/DOM), Address Book
(Ajax) and Calendar (Ajax with the Dojo Toolkit).
All of this has been carefully reviewed distinguished industry developers and academics.
Markup Intro
1. Introduction
2. Introduction to XHTML
3. Cascading Style Sheets™ (CSS)
Chrome, but may not work on earlier browsers. Microsoft Windows users of this book
should use Internet Explorer 7 or Firefox 3; readers who have other operating systems
should install Firefox 3. Firefox 2 will also work with this book.
The third part of the book, Chapters 4–11, presents an eight-chapter treatment of
JavaScript, including an introduction followed by control statements, functions, arrays
and objects. Chapter 10 focuses on the objects and collections that enable you to manip-
ulate web page elements from JavaScript. Chapter 11 demonstrates event handling in
JavaScript, which enables you to respond to user interaction with web page elements.
Chapters 4–11 depend on the XHTML and CSS concepts presented in Chapters 2–3.
The fourth part of the book, Chapter 12, presents XML and RSS—two technologies
used frequently in Web 2.0 applications to transmit data between servers and clients.
Finally, our presentation concludes with Chapter 13’s treatment of Ajax development.
Ajax is not a new technology—we’ve been writing about all but one of its component tech-
nologies since the first edition of our book Internet & World Wide Web How to Program in
1999, and many of the technologies existed before that. However, Ajax is one of the key
technologies of Web 2.0 and RIAs. The chapter starts with “raw” Ajax development then
discusses “encapsulated” Ajax development with the Dojo libraries. Chapters 12–13
depend on the concepts presented in Chapters 2–11.
Teaching Approach
JavaScript for Programmers contains a rich collection of examples. The book concentrates
on the principles of good software engineering and stresses program clarity. We are edu-
cators who teach leading-edge topics in industry classrooms worldwide. The Deitels have
taught courses at all levels to government, industry, military and academic clients of Deitel
& Associates, Inc.
xviii Preface
Code Highlighting. We place white rectangles around each program’s key code segments.
Using Fonts for Emphasis. We place the key terms and the index’s page reference for each
defining occurrence in bold italic text for easier reference. We emphasize on-screen com-
ponents in the bold Helvetica font (e.g., the File menu) and emphasize program text in the
Lucida font (e.g., int x = 5).
Web Access. All of the source-code examples for JavaScript for Programmers are available for
download from:
www.deitel.com/books/jsfp/
Site registration is quick, easy and free. Download all the examples, then run each program
in a browser as you read the corresponding text discussions. Making changes to the exam-
ples and seeing the effects of those changes is a great way to enhance your Internet and web
programming learning experience.
Objectives. Each chapter begins with a statement of objectives. This lets you know what
to expect and gives you an opportunity to determine if you have met these goals after read-
ing the chapter.
Quotations. The objectives are followed by quotations. Some are humorous, some are
philosophical, others offer interesting insights. We hope that you enjoy relating the quo-
tations to the chapter material.
Outline. The chapter outline helps you approach the material in a top-down fashion, so
you can anticipate what is to come and set a comfortable learning pace.
Illustrations/Figures. Abundant charts, tables, line drawings, programs and program out-
put are included.
Programming Tips. We include programming tips to help you focus on important aspects
of program development. These tips and practices represent the best we have gleaned from
a combined seven decades of programming and teaching experience. One of our readers
told us that she feels this approach is like the highlighting of axioms, theorems and corol-
laries in mathematics books—it provides a basis on which to build good software.
Deitel® Buzz Online Free E-mail Newsletter xix
Performance Tips
These tips highlight opportunities for making your programs run faster or minimizing the
amount of memory that they occupy.
Portability Tips
We include Portability Tips to help you write code that will run on a variety of platforms, and
to explain how to achieve a high degree of portability.
crucial to the production of the book. Many people at Deitel & Associates, Inc. devoted
long hours to this project—thanks especially to Abbey Deitel and Barbara Deitel.
We’d also like to thank the participants in our Honors Internship program who con-
tributed to this publication—Ilana Segall, a mathematical and computational science
major at Stanford University; Scott Wehrwein, a computer science major at Middlebury
College; and Mark Kagan, a computer science, economics and math major at Brandeis
University.
We are fortunate to have worked on this project with the talented and dedicated team
of publishing professionals at Prentice Hall. We appreciate the extraordinary efforts of
Mark Taub, Editor-in-Chief of Prentice Hall Professional; John Fuller, Managing Editor
of Prentice Hall Professional and Marcia Horton, Editorial Director of Prentice Hall’s
Engineering and Computer Science Division. Carole Snyder and Dolores Mars did a
remarkable job recruiting the book’s review team and managing the review process. Sandra
Schroeder and Chuti Prasertsith did a wonderful job designing the book’s cover. Bob
Engelhardt and Scott Disanno did a marvelous job managing the book’s production.
This book was adapted from our book Internet & World Wide Web How to Program,
4/e. We wish to acknowledge the efforts of our reviewers on that book who worked on the
corresponding chapters. Adhering to a tight time schedule, they scrutinized the text and
the programs, providing countless suggestions for improving the accuracy and complete-
ness of the presentation.
Reviewers
Umachitra Damodaran (Sun Microsystems), Vadiraj Deshpande (Sun Microsystems),
Molly E. Holtzschlag (W3C), Ralph Hooper (University of Alabama, Tuscaloosa), John-
vey Hwang (Splunk, Inc.), Eric Lawrence (Microsoft), Billy B. L. Lim (Illinois State Uni-
versity), Shobana Mahadevan (Sun Microsystems), Anand Narayanaswamy (Microsoft),
John Peterson (Insync and V.I.O., Inc.), Jennifer Powers (University of Albany), José An-
tonio González Seco (Parlamento de Andalucia), Dr. George Semeczko (Royal & SunAl-
liance Insurance Canada), Steven Shaffer (Penn State University), Karen Tegtmeyer
(Model Technologies, Inc.), Eric M. Wendelin (Auto-trol Technology Corporation), Ray-
mond F. Wisman (Indiana University) and Daniel Zappala (Brigham Young University).
We hope you enjoy this look at the exciting world of JavaScript-based, client-side web
applications development. As you read the book, we’d sincerely appreciate your com-
ments, criticisms, corrections and suggestions for improving the text. Please address all
correspondence to deitel@deitel.com. We’ll respond promptly, and post corrections
and clarifications at www.deitel.com/books/jsfp/. We hope you enjoy reading
JavaScript for Programmers as much as we enjoyed writing it!
Paul J. Deitel
Dr. Harvey M. Deitel
Maynard, Massachusetts
ates, Inc., he has delivered web programming, Java, C#, Visual Basic, C++ and C courses
to industry clients, including Cisco, IBM, Sun Microsystems, Dell, Lucent Technologies,
Fidelity, NASA at the Kennedy Space Center, White Sands Missile Range, the National
Severe Storm Laboratory, Rogue Wave Software, Boeing, Stratus, Hyperion Software,
Adra Systems, Entergy, CableData Systems, Nortel Networks, Puma, iRobot, Invensys
and many more. He holds the Sun Certified Java Programmer and Java Developer certifi-
cations and has been designated by Sun Microsystems as a Java Champion. He has lec-
tured on Java and C++ for the Boston Chapter of the Association for Computing
Machinery. He and his father, Dr. Harvey M. Deitel, are the world’s best-selling program-
ming-language textbook authors.
Dr. Harvey M. Deitel, Chairman and Chief Strategy Officer of Deitel & Associates,
Inc., earned B.S. and M.S. degrees from MIT and a Ph.D. from Boston University. He
earned tenure and served as the Chairman of the Computer Science Department at Boston
College before founding Deitel & Associates, Inc., with his son, Paul J. Deitel. Harvey and
Paul are the co-authors of dozens of books and multimedia packages and they are writing
many more. The Deitels’ texts have earned international recognition with translations
published in Japanese, German, Russian, Spanish, Traditional Chinese, Simplified Chi-
nese, Korean, French, Polish, Italian, Portuguese, Greek, Urdu and Turkish. Dr. Deitel
has delivered hundreds of professional seminars to major corporations, academic institu-
tions, government organizations and the military.
To learn more about Deitel & Associates, Inc., its publications and its worldwide
Dive Into® Series Corporate Training curriculum, visit:
www.deitel.com/training/
and subscribe to the free Deitel® Buzz Online e-mail newsletter at:
www.deitel.com/newsletter/subscribe.html
The publisher offers discounts on this book when ordered in quantity for bulk pur-
chases or special sales, which may include electronic versions and/or custom covers and
content particular to your business, training goals, marketing focus, and branding inter-
ests. For more information, please contact:
U. S. Corporate and Government Sales
(800) 382-3419
corpsales@pearsontechgroup.com
Please follow these instructions to download the book’s examples and ensure you have a
current web browser before you begin using this book.
You are now ready to begin reading JavaScript for Programmers. We hope you enjoy
the book! If you have any questions, please e-mail us at deitel@deitel.com. We’ll
respond promptly.
This page intentionally left blank
1
Introduction
1.1 Introduction
Welcome to Internet and World Wide Web programming and Web 2.0! We’ve worked
hard to create what we hope you’ll find to be an informative, entertaining and challenging
learning experience. As you read this book, you may want to refer to
www.deitel.com/books/jsfp/
To keep up to date with Internet and web programming developments, and the latest
information on JavaScript for Programmers at Deitel & Associates, please register for our
free e-mail newsletter, the Deitel® Buzz Online, at
www.deitel.com/newsletter/subscribe.html
Please check out our growing list of Internet and web programming, and Internet business
Resource Centers at
www.deitel.com/resourcecenters.html
Each week, we announce our latest Resource Centers in the newsletter. A list of Deitel Re-
source Centers at the time of this writing is located in the first few pages of the book. The
Resource Centers include links to, and descriptions of, key tutorials, demos, free software
tools, articles, e-books, white papers, videos, podcasts, blogs, RSS feeds and more that will
help you deepen your knowledge of most of the subjects we discuss in this book.
Errata and updates for the book are posted at
www.deitel.com/books/jsfp/
You’re embarking on a challenging and rewarding path. We hope that you’ll enjoy
JavaScript for Programmers. As you proceed, if you have any questions, send e-mail to
deitel@deitel.com
short) was the key early benefit of the ARPANET. This is true even today on the Internet,
as e-mail and instant messaging facilitates communications of all kinds among more than
a billion people worldwide.
cades ago, the web is a relatively recent creation. In 1989, Tim Berners-Lee of CERN (the
European Organization for Nuclear Research) began to develop a technology for sharing
information via hyperlinked text documents. Berners-Lee called his invention the Hyper-
Text Markup Language (HTML). He also wrote communication protocols to form the
backbone of his new information system, which he called the World Wide Web. In par-
ticular, he wrote the Hypertext Transfer Protocol (HTTP)—a communications protocol
for sending information over the web. Web use exploded with the availability in 1993 of
the Mosaic browser, which featured a user-friendly graphical interface. Marc Andreessen,
whose team at NCSA (the University of Illinois’ National Center for Supercomputing Ap-
plications) developed Mosaic, went on to found Netscape®, the company that many peo-
ple credit with initiating the explosive Internet economy of the late 1990s. Netscape’s
version of the Mosaic browser has been evolved by the Mozilla Corporation into the enor-
mously popular open source Mozilla Firefox browser.
1. O’Reilly, T. “What is Web 2.0: Design Patterns and Business Models for the Next Generation
of Software.” September 2005 <http://www.oreillynet.com/pub/a/oreilly/tim/news/2005/
09/30/what-is-web-20.html?page=1>.
6 Chapter 1 Introduction
word, few people really know what Web 2.0 means. Generally, Web 2.0 companies use
the web as a platform to create collaborative, community-based sites (e.g., social network-
ing sites, blogs, wikis, etc.).
Web 1.0
Web 1.0 (the state of the web through the 1990s and early 2000s) was focused on a rela-
tively small number of companies and advertisers producing content for users to access
(some people called it the “brochure web”). Web 2.0 involves the user—not only is the
content often created by the users, but users help organize it, share it, remix it, critique it,
update it, etc. One way to look at Web 1.0 is as a lecture, a small number of professors
informing a large audience of students. In comparison, Web 2.0 is a conversation, with ev-
eryone having the opportunity to speak and share views.
Architecture of Participation
Web 2.0 is providing new opportunities and connecting people and content in unique
ways. Web 2.0 embraces an architecture of participation—a design that encourages user
interaction and community contributions. You, the user, are the most important aspect of
Web 2.0—so important, in fact, that in 2006, TIME Magazine’s “Person of the Year” was
“you.”2 The article recognized the social phenomenon of Web 2.0—the shift away from
a powerful few to an empowered many. Several popular blogs now compete with tradi-
tional media powerhouses, and many Web 2.0 companies are built almost entirely on user-
generated content. For websites like MySpace®, Facebook®, Flickr™, YouTube, eBay®
and Wikipedia®, users create the content, while the companies provide the platforms.
These companies trust their users—without such trust, users cannot make significant con-
tributions to the sites.
Collective Intelligence
The architecture of participation has influenced software development as well. Open
source software is available for anyone to use and modify with few or no restrictions. Using
collective intelligence—the concept that a large diverse group of people will create smart
ideas—communities collaborate to develop software that many people believe is better and
more robust than proprietary software. Rich Internet Applications (RIAs) are being devel-
oped using technologies (such as Ajax) that have the look and feel of desktop software, en-
hancing a user’s overall experience. Software as a Service (SaaS)—software that runs on a
server instead of a local computer—has also gained prominence because of sophisticated
new technologies and increased broadband Internet access.
Search engines, including Google™, Yahoo!®, MSN®, Ask™, and many more, have
become essential to sorting through the massive amount of content on the web. Social
bookmarking sites such as del.icio.us and Ma.gnolia allow users to share their favorite sites
with others. Social media sites such as Digg™, Spotplex™ and Netscape enable the com-
munity to decide which news articles are the most significant. The way we find the infor-
mation on these sites is also changing—people are tagging (i.e., labeling) web content by
subject or keyword in a way that helps anyone locate information more effectively.
2. Grossman, L. “TIME’s Person of the Year: You.” TIME, December 2006 <http://
www.time.com/time/magazine/article/0,9171,1569514,00.html>.
1.5 Key Software Trend: Object Technology 7
Web Services
Web services have emerged and, in the process, have inspired the creation of many Web
2.0 businesses. Web services allow you to incorporate functionality from existing applica-
tions and websites into your own web applications quickly and easily. For example, using
Amazon Web Services™, you can create a specialty bookstore to run your website and
earn revenues through the Amazon Associates Program; or, using Google™ Maps web ser-
vices with eBay web services, you can build location-based “mashup” applications to find
auction items in certain geographical areas. Web services, inexpensive computers, abun-
dant high-speed Internet access, open source software and many other elements have in-
spired new, exciting, lightweight business models that people can launch with only a
small investment. Some types of websites with rich and robust functionality that might
have required hundreds of thousands or even millions of dollars to build in the 1990s can
now be built for nominal amounts of money.
Semantic Web
In the future, we’ll see computers learn to understand the meaning of the data on the
web—the beginnings of the Semantic Web are already appearing. Continual improve-
ments in hardware, software and communications technologies will enable exciting new
types of applications.
See our Web 2.0 Resource Center at www.deitel.com/web2.0/ for more information
on the major characteristics and technologies of Web 2.0, key Web 2.0 companies and
Web 2.0 Internet business and monetization models. The Resource Center also includes
information on user-generated content, blogging, content networks, social networking,
location-based services and more. We have separate Resource Centers on many Web 2.0
concepts and technologies. You can view a list of our Resource Centers in the first few
pages of this book and at www.deitel.com/ResourceCenters.html.
We live in a world of objects. Just look around you. There are cars, planes, people,
animals, buildings, traffic lights, elevators and the like. Before object-oriented languages
appeared, procedural programming languages (such as Fortran, COBOL, Pascal, BASIC
and C) were focused on actions (verbs) rather than on things or objects (nouns). Program-
mers living in a world of objects programmed primarily using verbs. This made it awkward
to write programs. Now, with the availability of popular object-oriented languages, such
as C++, Java, Visual Basic and C#, programmers continue to live in an object-oriented
world and can program in an object-oriented manner. This is a more natural process than
procedural programming and has resulted in significant productivity gains.
A key problem with procedural programming is that the program units do not effec-
tively mirror real-world entities, so these units are not particularly reusable. It’s not
unusual for programmers to “start fresh” on each new project and have to write similar
software “from scratch.” This wastes time and money, as people repeatedly “reinvent the
wheel.” With object technology, the software entities created (called classes), if properly
designed, tend to be reusable on future projects. Using libraries of reusable componentry
can greatly reduce effort required to implement certain kinds of systems (compared to the
effort that would be required to reinvent these capabilities on new projects).
Software Engineering Observation 1.1
Extensive class libraries of reusable software components are available on the Internet. Many of
these libraries are free.
Although it is easier to write portable programs in JavaScript than in many other programming
languages, differences among interpreters and browsers make portability difficult to achieve.
Simply writing programs in JavaScript does not guarantee portability. You’ll occasionally need
to research platform variations and write your code accordingly.
2.1 Introduction
Welcome to the world of opportunity created by the World Wide Web. The Internet is
almost four decades old, but it wasn’t until the web’s growth in popularity in the 1990s
and the recent start of the Web 2.0 era that the explosion of opportunity we are experienc-
ing began. Exciting new developments occur almost daily—the pace of innovation is un-
precedented. In this chapter, you’ll develop your own web pages. As the book proceeds,
you’ll create increasingly appealing and powerful web pages.
This chapter begins unlocking the power of web-based application development with
XHTML—the Extensible HyperText Markup Language. Later in the chapter, we intro-
duce more sophisticated XHTML techniques such as internal linking for easier page nav-
igation, forms for collecting information from a web-page visitor and tables, which are
particularly useful for structuring information from databases (i.e., software that stores
structured sets of data). In the next chapter, we discuss a technology called Cascading Style
Sheets™ (CSS), a technology that makes web pages more visually appealing.
Unlike procedural programming languages such as C, C++, or Java, XHTML is a
markup language that specifies the format of the text that is displayed in a web browser
such as Microsoft’s Internet Explorer or Mozilla Firefox.
One key issue when using XHTML is the separation of the presentation of a docu-
ment (i.e., the document’s appearance when rendered by a browser) from the structure of
the document’s information. XHTML is based on HTML (HyperText Markup Lan-
guage)—a legacy technology of the World Wide Web Consortium (W3C). In HTML, it
was common to specify both the document’s structure and its formatting. Formatting
might specify where the browser placed an element in a web page or the fonts and colors
used to display an element. The XHTML 1.0 Strict recommendation (the version of
XHTML that we use in this book) allows only a document’s structure to appear in a valid
XHTML document, and not its formatting. Normally, such formatting is specified with
Cascading Style Sheets (Chapter 3). All our examples in this chapter are based on the
XHTML 1.0 Strict Recommendation.
12 Chapter 2 Introduction to XHTML
Lines 1–3 are required in XHTML documents to conform with proper XHTML
syntax. For now, copy and paste these lines into each XHTML document you create. The
meaning of these lines is discussed in detail in Chapter 12.
Lines 5–6 are XHTML comments. XHTML document creators insert comments to
improve markup readability and describe the content of a document. Comments also help
other people read and understand an XHTML document’s markup and content. Com-
ments do not cause the browser to perform any action when the user loads the XHTML
document into the web browser to view it. XHTML comments always start with <!-- and
end with -->. Each of our XHTML examples includes comments that specify the figure
number and filename and provide a brief description of the example’s purpose. Subse-
quent examples include comments in the markup, especially to highlight new features.
Good Programming Practice 2.2
Place comments throughout your markup. Comments help other programmers understand the
markup, assist in debugging and list useful information that you do not want the browser to ren-
der. Comments also help you understand your own markup when you revisit a document to mod-
ify or update it in the future.
XHTML markup contains text that represents the content of a document and ele-
ments that specify a document’s structure. Some important elements of an XHTML doc-
ument are the html element, the head element and the body element. The html element
encloses the head section (represented by the head element) and the body section (repre-
sented by the body element). The head section contains information about the XHTML
document, such as its title. The head section also can contain special document formatting
instructions called style sheets and client-side programs called scripts for creating dynamic
web pages. (We introduce style sheets in Chapter 3 and scripting with JavaScript in
Chapter 4.) The body section contains the page’s content that the browser displays when
the user visits the web page.
XHTML documents delimit an element with start and end tags. A start tag consists
of the element name in angle brackets (e.g., <html>). An end tag consists of the element
name preceded by a forward slash (/) in angle brackets (e.g., </html>). In this example,
lines 7 and 15 define the start and end of the html element. Note that the end tag in line
15 has the same name as the start tag, but is preceded by a / inside the angle brackets.
Many start tags have attributes that provide additional information about an element.
Browsers can use this additional information to determine how to process the element.
Each attribute has a name and a value separated by an equals sign (=). Line 7 specifies a
required attribute (xmlns) and value (http://www.w3.org/1999/xhtml) for the html ele-
14 Chapter 2 Introduction to XHTML
ment in an XHTML document. For now, simply copy and paste the html element start
tag in line 7 into your XHTML documents. We discuss the details of the xmlns attribute
in Chapter 12.
default web browser. At this point your browser window should appear similar to the
sample screen capture shown in Fig. 2.1. (Note that we resized the browser window to save
space in the book.)
2.5 Headings
Some text in an XHTML document may be more important than other text. For example,
the text in this section is considered more important than a footnote. XHTML provides
six headings, called heading elements, for specifying the relative importance of informa-
tion. Figure 2.2 demonstrates these elements (h1 through h6). Heading element h1 (line
13) is considered the most significant heading and is typically rendered in a larger font
than the other five headings (lines 14–18). Each successive heading element (i.e., h2, h3,
etc.) is typically rendered in a progressively smaller font.
2.6 Linking
One of the most important XHTML features is the hyperlink, which references (or links
to) other resources, such as XHTML documents and images. When a user clicks a hyper-
link, the browser tries to execute an action associated with it (e.g., navigate to a URL, open
an e-mail client, etc.). In XHTML, both text and images can act as hyperlinks. Web
browsers typically underline text hyperlinks and color their text blue by default, so that
users can distinguish hyperlinks from plain text. In Fig. 2.3, we create text hyperlinks to
four different websites.
Line 14 introduces the strong element, which indicates that its contents has high
importance. Browsers typically display such text in a bold font.
Links are created using the a (anchor) element. Line 17 defines a hyperlink to the
URL assigned to attribute href, which specifies the location of a linked resource, such as
2.6 Linking 17
a web page, a file or an e-mail address. This particular anchor element links the text Deitel
to a web page located at http://www.deitel.com. When a URL does not indicate a spe-
cific document on the website, the web server returns a default web page. This page is often
called index.html; however, most web servers can be configured to use any file as the
default web page for the site. If the web server cannot locate a requested document, it
returns an error indication to the web browser, and the browser displays a web page con-
taining an error message to the user.
18 Chapter 2 Introduction to XHTML
2.7 Images
The examples discussed so far demonstrate how to mark up documents that contain only
text. However, most web pages contain both text and images. In fact, images are an equally
important, if not essential, part of web-page design. The three most popular image formats
used by web developers are Graphics Interchange Format (GIF), Joint Photographic Ex-
perts Group (JPEG) and Portable Network Graphics (PNG) images. Users can create im-
ages using specialized software, such as Adobe Photoshop Elements (www.adobe.com),
G.I.M.P. (http://www.gimp.org) and Inkscape (http://www.inkscape.org). Images
may also be acquired from various websites. Figure 2.5 demonstrates how to incorporate
images into web pages.
Lines 14–15 use an img element to insert an image in the document. The image file’s
location is specified with the img element’s src attribute. This image is located in the same
directory as the XHTML document, so only the image’s filename is required. Optional
attributes width and height specify the image’s width and height, respectively. You can
scale an image by increasing or decreasing the values of the image width and height attri-
butes. If these attributes are omitted, the browser uses the image’s actual width and height.
Images are measured in pixels (“picture elements”), which represent dots of color on the
screen. Any image-editing program will have a feature that displays the dimensions, in
pixels, of an image. The image in Fig. 2.5 is 92 pixels wide and 120 pixels high.
ebookgate.com