This document is the table of contents for the book "Advanced JavaScript Second Edition" by Chuck Easttom. It contains 35 chapters that cover topics like JavaScript fundamentals, object-oriented programming, functions, operators, events, arrays, dates, forms, cookies, images and more. The book is published by Wordware Publishing, Inc. and is intended to teach programmers advanced JavaScript skills.
27. Acknowledgments
Writing a book is a daunting task, and it is never the work of a single person. I would
like to take the time to thank several people who were indispensable in making this
project happen:
Tomer and Yehuda Shiran, who wrote the first edition of this book. They gave me a
fabulous foundation to work with for this second edition.
Jim Hill and Wes Beckwith, the wonderful people at Wordware Publishing who labored
through this with me.
Derick Richards, who did a technical review of this book.
Last but not at all least, my wife, Misty, who did not complain at all when I was spend-
ing hours in my den typing away.
xxvi n Acknowledgments
28. Introduction
Prerequisites
JavaScript is a scripting language designed to be used within HTML documents. For
this reason a basic working knowledge of HTML is required before you can learn or
use JavaScript. For those readers either lacking this basic knowledge or requiring a
refresher course, Chapter 2 is a basic HTML primer that will teach you all of the skills
you will need.
A Programming Refresher
Chapter 3 is a brief crash course in basic JavaScript to help readers with no prior
knowledge of JavaScript as well as those who require a brief refresher. This chapter
covers all the fundamental elements of JavaScript and will prepare the reader to con-
tinue on with the material in this book.
How to Read This Book
As the title suggests, this book is geared towards advanced JavaScript programming
and has the experienced JavaScript programmer in mind. However, the first few chap-
ters do provide basic primers on both HTML and JavaScript. Those with limited
JavaScript experience should carefully study the first few chapters, while more experi-
enced programmers may want to skim these chapters or skip them entirely.
The Structure of This Book
It’s important to understand how the book is structured so you can plan your learning
experience in the best possible way. The table of contents lists the chapters by name.
If you are an experienced JavaScript programmer just looking for a reference on a par-
ticular subject, feel free to skip directly to the relevant chapter.
JavaScript is a viable scripting language for both Netscape and Internet Explorer, so I
will use examples from both browsers and will point out any differences. If you have
the latest version of either Netscape or Internet Explorer, then virtually all the
Introduction n xxvii
29. examples should work fine for you. Older versions of both browsers, particularly 3.0
and earlier, lacked support for some JavaScript features.
Programming Style
As both an aid to the reader and to illustrate good programming practices, I use a uni-
form style throughout this entire text and in all the sample code you will find on the
companion CD. For example, all variables are in Hungarian notation, meaning the vari-
able is preceded by one to three letters designating the type of variable it is. For
example, an integer being used as a loop counter might be named intcounter, and a
float that holds an account balance might be named fltbalance. I also have a tendency
to comment very heavily, some would say too much. This comes from teaching and
creating code samples for students. I hope you will find this helpful:
for (var intcounter = 0; intcounter < 10; ++intcounter)
{
[JavaScript statements]
}// end of for loop
Some JavaScript scripters prefer to use a different style:
for (var num = 0; num < 10; ++num){
[JavaScript statements]
}
A lot of my style preferences are just that, preferences. It is hard to call one style right
and another wrong. However, I strongly suggest that when you are writing code you
consider the fact that other programmers will probably need to read your code at some
point. They will have absolutely no idea what you were thinking when you wrote your
code. I try to write code in such a way that even a novice programmer with no prior
knowledge of the project at hand could easily deduce the intended purpose of the code.
Reading Examples
It seems obvious but read the examples thoroughly. Make sure you have a firm under-
standing of how and why they work. It is also helpful to actually run them. If you don’t
wish to run them, at least read them thoroughly and make certain that you fully under-
stand every line of code and what it does.
Encouragement for Nonprogrammers
Learning a scripting language is a lot easier than learning a full programming language
such as Java or C++. Fortunately, JavaScript is enough like Java that you will find it
relatively easy to leverage your JavaScript skills into Java programming as well. Just
remember that computers do exactly what we tell them to do, which may not always
be exactly what we intended them to do. Most programming errors (called “bugs”)
stem from simple mistakes. I have an axiom that I believe is true: “Any error that
xxviii n Introduction
30. takes more than 15 minutes to find will turn out to be something simple.” In my expe-
rience, complex or fundamental errors are easy to find, though they may be quite hard
to fix. Errors that take a long time to find are almost invariably simple mistakes.
Warning for Programmers
If your programming experience has been in strictly procedural languages such as C
and Pascal, hold on tight. JavaScript, like Java, is object oriented. This will be a whole
new approach to programming for you. But not to worry—this book will walk you
through it step by step. However, if you are an experienced object-oriented program-
mer, especially a C++ or Java programmer, then this book should be a pretty easy
read for you.
Introduction n xxix
31. Chapter 1
Introduction to JavaScript
The World Wide Web
It may be hard for some readers to recall a time when the web was not a part of our
day-to-day lives. However, it was not until the early ’90s that the web became a seri-
ous medium for communication. Prior to that, the major uses of the Internet were
simply e-mail and file transfer. This is not to say that web pages did not exist before
then; it’s simply that they were not a widespread communication tool. By the early
21st century, however, there were millions of web sites from major corporations and
government agencies to 10-year-olds putting up web sites extolling the virtues of
their favorite cartoon. It is hard to imagine conducting business today without some
web presence, whether it’s a small web site that gives the essentials of your business
or a full blown e-commerce site.
This spread of the web has also lead to greater expectations from web pages. Ori-
ginally, simply putting up some well-organized text was enough to give you a
successful web site. But soon, web surfers became accustomed to graphics, anima-
tions, sounds, and more. All of this could be accomplished with successive versions of
HTML. Modern web users, however, expect a higher level of functionality from web
sites.
Competition on the Web
Site popularity is usually measured by the number of visits, or “hits,” a web site
receives. Major sites such as www.yahoo.com can receive tens of thousands of hits per
day. Less popular sites may only receive a few hundred hits a day, while personal web
pages may only receive a few hits per week or month. The competition to get visitors
to sites is becoming quite fierce. In fact, advertising dollars are now pouring in to sites
that can attract a significant number of visitors. The most common way to get visitors
to a site is to add content, both informational/functional and purely decorative. This is
an area for which JavaScript is ideally suited.
The World Wide Web (WWW) is constantly growing as new web servers and pages are
connected. It is estimated that over 15,000 domain names (such as netscent.com) are
Introduction to JavaScript n 1
32. registered daily. Each domain name is eventually associated with a web server or a vir-
tual server. Your web site is truly useless if people do not visit it. There are several
ways to attract web surfers to a site:
n Advertising. You can advertise your web site on pages that belong to other com-
panies or individuals by placing some text or images on their page. The user loads
the page and sees a banner at the top of the page; when he or she clicks the ban-
ner, the advertiser’s site is loaded. Many large companies also tend to advertise
via traditional methods such as newspapers, magazines, television, and radio.
Although this method is somewhat less efficient, it works surprisingly well for
well-established companies.
n Submission. Once you have a web site, people should know that it exists. Most
people and small businesses do not have enough resources to advertise via ban-
ners that can cost up to tens of thousands of dollars a month. The most common
free promotion method is to submit the URL and description of a web page to
search engines and directories. Those services provide an easy way of retrieving
desired web pages. For example, a search engine returns URLs of pages that are
related to a specific topic that the user searched for. AltaVista, Excite, and Lycos
are just some examples of such search engines; there are hundreds available on
the web. Directories such as Yahoo! gather web pages by subject so the user can
find pages related to a given subject.
n Attractive site. The most important way to attract users to your site is by creat-
ing an engaging site. Most web surfers tend to stick to sites that they have visited
before and where they have found interesting, new material every visit. The most
“effective” way to deter people from revisiting your site is by allowing it to
become stale.
Extending HTML
HTML is a somewhat limited document-formatting language. It is based on tags, which
instruct the browser how to display a chunk of text or an image. As such, the HTML is
limited to a static, one-way interaction with the user. The web page can be as sophisti-
cated and attractive to the surfer’s eyes as it can possibly be, but the user cannot
interact with the page. Interaction cannot be static—it requires constructs such as if
statements and for loops, which are not part of the HTML syntax.
These missing constructs are found in JavaScript. This object-oriented language pro-
vides web page authors with the power to reach a very high level of interaction
between the user and the document. The power of the language is best witnessed
from the pace of its evolution. Browser providers are coming out with new extensions
and features every few months, leapfrogging each other in their constant quest for
market dominance. The leading browser provider companies are thus setting the stan-
dards in web page authoring features, with JavaScript being of special importance.
2 n Chapter 1
33. CGI Programs
You are probably familiar with popular search engines such as Yahoo!, AltaVista, and
Excite. Have you asked yourself how these engines work? They are based on CGI
(Common Gateway Interface) scripts. CGI extends the interaction between the user
and the document to a higher level where the document communicates with the web
server on which the web pages reside. When you click the Submit button on a form,
your browser sends your entries from the HTML form to the server, where the CGI
script processes the data and sends it to another program running on the server. The
results are then transmitted to the user’s browser.
CGI scripts can be written in any language, Perl and C being the most popular ones.
Objectively, Perl and C are more complicated to program than JavaScript, and there-
fore, CGI scripting is usually mastered only by experienced programmers.
You are now in a position to understand why search engines need such powerful
machines to run their devices. A typical search engine receives several million
requests per day. For example, suppose a provider needs to answer one million search
requests per day. A simple calculation shows that that server must process approxi-
mately ten one-second-long requests per second. Each of these ten requests is a CGI
script executing on the server.
Helpers, Plug-ins, Applets, and CGI
Web page authoring consists of several layers. The more powerful the layer, the more
complex it is to program. The fundamental layer is HTML. As we explained earlier,
JavaScript extends HTML to a dynamic user/page interaction. Helpers, plug-ins, and
applets extend JavaScript’s capabilities even more.
Helpers
Browsers are very powerful in converting HTML tags into attractive pages, as well as
interpreting JavaScript scripts to animated commercials, but they have some deficien-
cies in other areas such as understanding audio that comes in from a web site. Your
browser, though, is smart enough to use helper applications to do such jobs instead.
The conversion of digitized sound to audio you can hear through your speakers is done
by a program that resides on your hard disk and is launched by the browser.
Plug-ins
Another way to extend browser capabilities is by plugging an application into it. At this
stage we will not discuss plug-ins, because a full chapter is dedicated to these mecha-
nisms and their powerful connections with JavaScript.
Introduction to JavaScript n 3
1
Chapter
34. Java Applets
OK, so you have tried HTML, JavaScript, helpers, and plug-ins (in this order) and you
are still not satisfied with your web page. Let’s say you want to place a rotating globe
on your page. Sun Microsystems answered this need by developing a language for the
web called Java. Talented programmers can use Java to build small applications
(applets) that are downloaded to the browser upon hitting the appropriate page and
then automatically discarded from memory when a new page is loaded. The applet
concept is similar to the image file concept. As the .gif file is loaded upon hitting the
page, which calls the appropriate image, so is the applet loaded upon the browser’s
request. The applet, though, is more than a static combination of pixels; it is an inde-
pendent program that executes when the page loads and is automatically terminated
when the page unloads. The applet is a self-sustained, independent module, without
any possibilities for user interaction during its execution.
The classic example of an applet is a scrolling LED banner, similar to the scrolling sign
at Times Square. There is no better way to inform your visitors about changes you
have made to your page. You can change your banner whenever you want to bring new
items to the user’s attention. This touch of animation can bring your page to life and
create the perception of a dynamic, up-to-date site.
For a browser company to support Java applets, it needs to license the technology
from Sun and build the proper hooks in the browser. The first one to do it was Sun
itself, with its HotJava browser. Netscape incorporated it later, as did Microsoft. Java
applets are assets that people are accumulating, and every browser must support them
to keep up with the nonstop competition.
You have probably asked yourself about the origin of Java. The Java language is derived
from C and C++ and is targeted for more experienced programmers. Therefore, many
web page authors and casual programmers cannot adopt the language as easily as they
have adopted HyperCard, ToolBook, or Visual Basic. JavaScript was created to answer
this exact need.
CGI (Common Gateway Interface)
There are some tasks that cannot be accomplished by the browser on the client side.
Building a common database for an engineering department must rely on a server
accepting data and requests from all users and storing it for future access and process-
ing. Such an application can be written in C, C++, Perl, or any other language. The
communication protocol between the server application and the client browser is
called CGI. You should buy a book on CGI if you intend to learn it, because it is far
beyond the scope of this book and is very difficult to learn without detailed
documentation.
4 n Chapter 1