Preface

Several bookmarks in my primary web browser link to sites that have, for years, displayed the “under construction” message and yellow-and-black “men working” road sign symbol. Ever the optimist, I keep the bookmarks alive and periodically visit the sites, looking forward to the day when the stick figure in the hard hat with the shovel leaves the scene, revealing a gleaming site containing the information that I had hoped for years ago.

This image comes to mind because my “brain browser” has maintained a bookmark to this book for years—but that stick figure kept hammering, sawing, and digging while the book remained forever “under construction.” Even though client-side JavaScript has been around since late 1995, and true Dynamic HTML concepts have been within reach since 1998, the road has been a bumpy one for those trying to use (and write about) the technologies. Conflicts in document object model (DOM) implementations in various browsers, complicated by the evolution of the World Wide Web Consortium’s (W3C) DOM recommendation, have made deployment of insightful client-side applications occasionally treacherous. This is especially true if the application must run on a broad range of browser brands and operating systems.

Now that the W3C DOM standard has fleshed itself out sufficiently, and other DHTML-related standards (HTML, XHTML, and Cascading Style Sheets) are largely working toward the same interoperable goals, it is finally time to apply the current state of the art to typical client-side scripting tasks. A cookbook approach lends itself nicely to provide answers to the most common question lead-in from programmers, designers, and content authors: “How do I...?”

About You

Client-side scripting and DHTML are such broad and deep subjects that virtually every reader coming to this book will have different experience levels, expectations, and perhaps, fears. No book could hope to anticipate every possible question from someone wishing to use these technologies in their web pages. Therefore, this book makes some assumptions about readers at various stages of their experience:

  • You have at least rudimentary knowledge of client-side JavaScript concepts. You know how to put scripts into a web page — where <script> tags go as well as how to link an external .js file into the current page. You also know what variables, strings, numbers, Booleans, arrays, and objects are—even if you don’t necessarily remember the precise way they’re used with the JavaScript language. This book is not a tutorial, but you can learn a lot from reading the introductions to each chapter and the discussions following each solution.

  • You may be a casual scripter, who wants to put a bit of intelligence into a web page for some project or other. You don’t use the language or object model every day, so you need a refresher about even some simple things, such as the correct syntax for creating an array or pre-loading images for fast image rollover effects.

  • While surfing the Web, you may have encountered some scripted DHTML effect that you’d like to implement or adapt for your own pages, but either you can’t decipher the code you see or you want to “roll your own” version to avoid copyright problems with the code’s original owner. If the effect or technique you’ve seen is fairly popular, this cookbook probably has a recipe for it. You can use these recipes as they are or modify them to fit your designs. There are no royalties or copyrights to worry about, as long as you don’t offer these recipes to others as part of a collection of scripts. Of course, if you wish to acknowledge this book in your source code comments, that would be great!

  • You may be an experienced web developer who has probed gingerly, if at all, into client-side scripting. The horror stories of yore about browser incompatibilities have kept your focus entirely on server-side programming. But now that so many mainstream sites are using client-side scripting to improve the user experience, you are ready to take another look at what is out there.

  • At the far end of the spectrum, you may be an experienced client-side DHTML developer in search of new ideas and techniques. For instance, you may have developed exclusively for the Internet Explorer browser on the Windows platform, but you wish to gravitate toward standards-compatible syntax for future coding.

Virtually every reader will find that some recipes in this book are too simple and others are too complex for their experience level. I hope the more difficult ones challenge you to learn more and improve your skills. Even if you think you know it all, be sure to check the discussions of the easier recipes for tips and insights that may be new to you.

About the Recipes

It’s helpful for a reader to know up front what biases an author has on the book’s subject. To carry the cookbook metaphor too far, just as a culinary chef has identifiable procedures and seasonings, so do I format my code in a particular way and employ programming styles that I have adopted over the years.

More important than scripting style, however, are the implementation threads that weave their way throughout the code examples. Because these examples may serve as models for your own development, they are written for maximum clarity to make it easy (I hope) for you to follow the execution logic. Names assigned to variables, functions, objects, and the like are meant to convey their purpose within the context of the example. One of the goals of coding is that the operation of a program should be self-evident to someone else reading the code, even if that “someone else” is the programmer who revisits the code six months later to fix a bug or add a feature. There’s no sense in being cryptically clever if no one can understand what you mean by assigning some value to a variable named x.

This book unabashedly favors the W3C DOM way of addressing document objects. You can use this format to reference element objects in browsers starting with Microsoft Internet Explorer 5 and Netscape 6, which means that the vast majority of browsers in use today support this standard. Where IE does not support the standard (as in handling events), all recipes here include efficient cross-browser implementations. You won’t find too much in the way of IE-only solutions, especially if they would cover only the Windows version of IE.

At the same time, this book acknowledges that you may need to support users who do not have W3C DOM-empowered browsers. You will find that substantial attention is paid to making even advanced DHTML scripts coexist gracefully in an old or nonscriptable browser. This is particularly important if you wish your pages to serve visitors with accessibility challenges (such as vision or physical impairments) or pocket computers containing underpowered browsers.

One credo dominates the recipes throughout this book: scripting must add value to static content on the page. Don’t look to this book for scripts that cycle background colors to nauseate visitors or make elements bounce around the page while singing Happy Birthday. You may be able to figure out how do those horrible things from what you learn in this book, but that’s your business. The examples here, while perhaps conservative, are intended to solve real-world problems that scripters and developers face in professional-quality applications.

The scripting techniques and syntax you see throughout this book are designed for maximum forward compatibility. It’s difficult to predict the future of any technology, but the W3C DOM and ECMAScript standards, as implemented in today’s latest browsers, are the most stable platforms on which to build client-side applications since client-side scripting began. With a bit of code added here and there to degrade gracefully in older browsers, your applications should be running fine well into the future.

What’s in This Book

The first four chapters focus on fundamental JavaScript topics. In Chapter 1, Strings, you will see the difference between a string value and a string object. Regular expressions play a big role in string parsing for these recipes. You will also see a reusable library for reading and writing string data to cookies. Chapter 2, Numbers and Dates, includes recipes for handling number formatting and conversions, as well as date calculations that get used in later recipes. Perhaps the most important core JavaScript language chapter is Chapter 3, Arrays and Objects. Recipes in this chapter provide the keys to one- and multidimensional array creation, array sorting, object creation, hash table simulation, and exploration of the prototype inheritance powers of objects. Chapter 4, Variables, Functions, and Flow Control, includes a recipe for improving overall script performance.

Chapter 5 through Chapter 8 provide solutions for problems that apply to almost all scriptable browsers. In Chapter 5, Browser Feature Detection, you will learn how to free yourself of the dreaded “browser sniffing” habit and use forward-compatible techniques for determining whether the browser is capable of running a block of script statements. If multiple windows are your nemesis, then Chapter 6, Managing Browser Windows, provides plenty of ideas to handle communication between windows. A few recipes present suggestions for modal windows (or facsimiles thereof). Not everyone is a frame lover, but Chapter 7, Managing Multiple Frames, may be of interest to all, especially if you don’t want your site being “framed” by another site. Intelligent forms—one of the driving forces behind the creation of client-side scripting—are the subject of Chapter 8, Dynamic Forms. Updated to modern techniques, recipes include form validation (with or without regular expressions) and some cool but subtle techniques found on some of the most popular web sites on the Internet.

Interactivity with the user is driven by event processing, and Chapter 9, covers the most common event processing tasks you’ll encounter with DHTML scripting. Events ripple through most of the remaining chapters’ recipes. That includes many recipes in Chapter 10, where you’ll see how to implement a variety of menuing designs and pass data from one page to the next. Chapter 11, provides recipes for both basic and advanced style sheet techniques as they apply to dynamic content, including how to load a browser- or operating system-specific stylesheet into the page. Style sheets play a big role in Chapter 12, where recipes abound for image rollovers and user-controlled font sizes, to name a couple.

Chapter 13, addresses numerous challenges in keeping positioned elements under tight rein. A positioning library recipe is used extensively throughout the rest of the book, including more recipes in this chapter for animating elements, scrolling content, and creating a draggable element. In Chapter 14, the W3C DOM gets a good workout with recipes for tasks such as embedding JavaScript and XML data within a document, transforming data into renderable HTML content, and sorting HTML tables instantly on the client. Additional dynamic content recipes come in Chapter 15, where more complex recipes show you how to use DHTML for a slide show, a visual count-down timer, and a pop-up calendar date picker, among others.

Browser Platforms

Each recipe includes a browser compatibility rating. The rating provides version information for only three browser platforms: Internet Explorer for Windows, Internet Explorer for Macintosh, and Netscape Navigator. When the rating for IE shows no particular distinction between the Windows and Macintosh OS platforms, both OS versions are covered. The number following the browser brand is the first version in which the recipe will work. The discussion section may include additional variations that work with either older browsers or only newer browsers.

Compatibility ratings indicating Netscape 6 or later also apply to the Mozilla browser and other browsers built with Mozilla (and the Gecko rendering engine). Mozilla 1.0.1 equates to Netscape 7, so recipes rated for Netscape 6 or later apply to all Mozilla releases at least since 1.0.

Other browsers, such as Opera and myriad others with yet smaller installed bases, are not shown in the compatibility ratings. Some discussions specifically address Opera, and by and large the recipes from Chapter 1 through Chapter 7 will work in Opera 5 or later. Where Opera has more substantial problems is where the recipe dives into W3C DOM techniques. As of the release of Opera 6, the browser does not offer sufficient DOM scriptability for many tasks. If Opera is a significant share of your installed base, you can try to make the scripts work for that browser or treat it as unscriptable. Throughout this book, you are encouraged to write scripts that degrade gracefully in nonscriptable browsers. Use those safeguards to protect Opera users from more advanced scripting tasks.

A new browser from Apple, called Safari, may become influential in the Macintosh market, perhaps replacing Internet Explorer as the dominant browser on the Mac OS X platform. Safari, built atop an engine called KHTML, is in beta release at the time of this book’s publication. It is foolhardy to script around bugs in a beta browser, so it would be unfair to rate recipe compatibility for Safari or any unfinished browser. One can only hope that new browser engines follow the standards implementations of their more experienced brethren to ensure script compatibility across a multitude of modern browser brands.

This book’s focus on the W3C DOM in later chapters may seem to exclude a lot of older browsers (although the DHTML library in Chapter 13 is backward-compatible to Netscape 4). As demonstrated by many talented scripters on the Web, you can script your way around a lot of buggy behavior to force an application to work on almost any scriptable browser (to a point). For the sake of code-listing simplicity, however, this book elects to stay in the modern mainstream of final release browsers.

Conventions Used in This Book

The following typographical conventions are used throughout this book:

Italic is used for:

  • Pathnames, filenames, program names, sample email addresses, and sample web sites

  • New terms where they are defined

Constant Width is used for:

  • Any HTML, CSS, or scripting term, including HTML tags, attribute names, object names, properties, methods, and event handlers

  • All HTML and script code listings

Constant Width Italic is used for:

  • Method and function parameter or assigned value placeholders that indicate an item is to be replaced by a real value in actual use

Request for Comments

We have tested and verified the information in this book to the best of our ability, but you may find that features have changed (or even that we have made mistakes!). Please let us know about any errors you find, as well as your suggestions for future editions, by writing to:

O’Reilly & Associates
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 928-9938 (in the United States or Canada)
(707) 829-0515 (international or local)
(707) 829-0104 (fax)

There is a web page for this book, which lists errata, downloadable examples, and any additional information. You can access this page at:

http://www.oreilly.com/catalog/jvdhtmlckbk/

To ask technical questions or comment on the book, send email to:

For more information about books, conferences, resource centers, and the O’Reilly Network, see the O’Reilly web site at:

http://www.oreilly.com

Acknowledgments

The “under construction” sign has been on this book since early 1999, when I signed on to write a cookbook covering DHTML. While the project has not been underway as long as Boston’s “Big Dig,” it is the longest I have waited for the technology and real world to catch up with my idea of what such a book should be. O’Reilly had the patience to let the subject matter mature and also wait while I wrote the second edition of Dynamic HTML: The Definitive Reference, which is a testament to a publishing firm that doesn’t rush about just to publish a title to occupy space on the bookseller shelf.

By stroke of luck, the passage of time meant that the unfinished title fell into the lap of Paula Ferguson, the most knowledgeable and tireless book editor for whom I’ve had the pleasure of writing during my 25-year career. She has edited many of O’Reilly’s most popular and successful titles, and magically blends the best interests of publisher, author, and reader into the finished product.

I was also very fortunate to have three additional pairs of watchful eyes looking over my shoulder to provide technical critiques of the work in progress. In alphabetical order, Sue Giller, Robert Husted, and Dori Smith, made countless suggestions that I adopted to improve the writing and scripting. Thank you times three!

Much of the impetus for selecting the recipes for this book has come from the scripting public. Having read thousands of online forum threads since 1996, having listened to readers of my JavaScript and Dynamic HTML books for years, and having observed search queries that lead visitors to my web site (http://www.dannyg.com), I believe I have distilled the essence of the needs of most client-side scripters. Your pain, confusion, and frustration with the technologies have not gone unnoticed. I hope this book provides the relief and understanding you crave.

Get JavaScript & DHTML Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.