O'Reilly logo

JavaScript & DHTML Cookbook, 2nd Edition by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Preface

It may be difficult to imagine that a technology born as recently as 1995 would have had enough of a life cycle to experience a rise and fall in popularity, followed now by an amazing renaissance. Client-side scripting, begun initially with JavaScript embedded in Netscape Navigator 2, has experienced such a roller coaster ride. A number of early incompatibilities among major browsers caused many a content author’s head to ache. But we learned to live with it, as a long period of stability in one platform—Internet Explorer 6, in particular—meant that we could use our well-worn compatibility workarounds without cause for concern. Another stabilizing factor was the W3C DOM Level 2 specification, which remained a major target for browser makers not following Microsoft’s proprietary ways. Mozilla, Safari, and Opera used the W3C DOM as the model to implement, even if Microsoft didn’t seem to be in a hurry to follow suit in all cases.

Two factors have contributed to the rebirth of interest in JavaScript and Dynamic HTML. The first is the wide proliferation of broadband connections. Implementing large client-side applications in JavaScript can take a bunch of code, all of which must be downloaded to the browser. At dial-up speeds, piling a 50–75 kilobyte script onto a page could seriously degrade perceived performance; at broadband speeds, nobody notices the difference.

But without a doubt, the major attraction these days is the now widespread availability in all mainstream browsers of a technology first implemented by Microsoft: the XMLHttpRequest object. It’s a mouthful (leading some to refer to it as, simply, XHR), but it allows background communication between the browser and server so that a script can request incremental data from the server and update only a portion of a page. It is far more efficient than downloading a bunch of data with the page and less visually disruptive than the old submit-and-wait-for-a-new-page process. To help put a label on the type of applications one can build with this technology, the term Asynchronous JavaScript and XML (Ajax) was coined. In truth, Ajax is simply a catchy handle for an existing technology.

Ajax has opened the floodgates for web developers. Perhaps the most popular first implementation was Google Maps, whereby you could drag your way around a map, while scripts and the XMLHttpRequest object in the background downloaded adjacent blocks of the map in anticipation of your dragging your way over there. It was smooth, fast, and a real joy to use. And now, more powerful applications—word processors, spreadsheets, email clients—are being built with JavaScript and DHTML.

JavaScript in the browser was originally designed for small scripts to work on small client-side tasks. It is still used that way quite a bit around the Web. Not every application is a mega DHTML app. Therefore, this collection of recipes still has plenty of small tasks in mind. At the same time, however, many recipes from the first edition have been revised with scripting practices that will serve both the beginner and the more advanced scripter well. Examples prepare you for the eventuality that your scripting skills will grow, perhaps leading to a mega DHTML app in the future. Even so, there are plenty of times when you need an answer to that age-old programming question: “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 his 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 preloading 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 copy-right 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 upfront 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 and updated 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 the other mainstream browsers addressed in this edition (Mozilla-based browsers, Safari, and Opera 7 or later), which means that the vast majority of browsers in use today support this standard. Where IE (including IE 7) 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 IEonly solutions, especially if they would cover only the Windows version of IE.

The long period of browser stability we have enjoyed since the first edition means that visitors to public sites almost never use what are now antique browsers—IE prior to 5.5 and Netscape Navigator 4 or earlier. All recipes are optimized for the current browsers, but they also try to prevent hassles for anyone driving by in her steam-powered browser.

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 to 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. You also see how creating custom objects for your libraries can reduce potential naming conflicts as projects grow. 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, Managing Events, covers the most common event processing tasks you’ll encounter with DHTML scripting. Events (and one of the libraries shown in Chapter 9) ripple through most of the remaining chapters’ recipes. That includes many recipes in Chapter 10, Page Navigation Techniques, where you’ll see how to implement a variety of menuing designs and pass data from one page to the next. Chapter 11, Managing Style Sheets, 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, Visual Effects for Stationary Content, where recipes abound for image rollovers and user-controlled font sizes, to name a couple.

Chapter 13, Positioning HTML Elements, 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, Creating Dynamic Content, the W3C DOM and XMLHttpRequest object get good workouts 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, Dynamic Content Applications, where more complex recipes show you how to use DHTML for a slide show, a user-editable document, and a pop-up calendar date picker, among others.

Browser Platforms

Freed from having to worry much about compatibility with very old browsers, the goal of each recipe’s design in this edition is to work in the following browsers:

  • Microsoft Internet Explorer 6 or later

  • Mozilla 1.7.5 (Firefox 1.0, Netscape 8.0, Camino 1.0) or later

  • Apple Safari 1.2 or later (including the Windows version)

  • Opera 7 or later

Many of the simpler scripts in early chapters work in browsers all the way back to Netscape Navigator 2, but that is hardly the focus here. Occasionally, a recipe may require a later version of Mozilla, Safari, or Opera, as noted clearly in the recipe. In those cases, the recipe is designed to prevent script errors from appearing in slightly older versions of these modern browsers.

You will also see many references in this book to designing pages to convey mission-critical information for browsers that either aren’t equipped with JavaScript or have scripting turned off. Beyond the browsers mentioned in the previous list, there are a lot of users of browsers in portable wireless devices and browsers for users with vision or motor skill impairments. Always keep accessibility in mind with your designs.

Conventions Used in This Book

The following typographical conventions are used throughout this book:

Italic

Indicates pathnames, filenames, program names, sample email addresses, and sample web sites; and new terms where they are defined

Constant width

Indicates any HTML, CSS, or scripting term, including HTML tags, attribute names, object names, properties, methods, and event handlers; and all HTML and script code listings

Constant width italic

Indicates method and function parameters or assigned value placeholders that represent an item to be replaced by a real value in actual use

Constant width bold

Used to draw attention to specific parts of code

Tip

This icon signifies a tip, suggestion, or general note.

Warning

This icon indicates a warning or caution.

Using Code Examples

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "JavaScript & DHTML Cookbook, Second Edition, by Danny Goodman. Copyright 2007 Danny Goodman, 978-0-596-51408-2.”

If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at .

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 Media, Inc.
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/9780596514082

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

Safari® Enabled

When you see a Safari® Enabled icon on the cover of your favorite technology book, that means the book is available online through the O’Reilly Network Safari Bookshelf.

Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at http://safari.oreilly.com.

Acknowledgments

The physical act of writing a book—converting thoughts to keystrokes and characters on the screen—is a solitary one. But once the first draft is submitted, an army of dedicated professionals join the author in shaping the work into a finished product. When the army marches under the O’Reilly banner, the author can be assured of a commitment to quality, even from many individuals whom the author never meets.

I extend my sincere appreciation to my editor, Tatiana Apandi, who magically kept me on schedule. I also thank Rob Hoexter and Sergio Pereira, who provided invaluable contributions to improving the writing and scripting.

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 deserve.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required