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
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
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 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.
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.
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
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.
The following typographical conventions are used throughout this book:
Indicates pathnames, filenames, program names, sample email addresses, and sample web sites; and new terms where they are defined
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
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.
If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at firstname.lastname@example.org.
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)|
There is a web page for this book, which lists errata, downloadable examples, and any additional information. You can access this page at:
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:
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.
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.