Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

The Book of JavaScript, 2nd Edition: A Practical Guide to Interactive Web Pages
The Book of JavaScript, 2nd Edition: A Practical Guide to Interactive Web Pages
The Book of JavaScript, 2nd Edition: A Practical Guide to Interactive Web Pages
Ebook1,179 pages6 hours

The Book of JavaScript, 2nd Edition: A Practical Guide to Interactive Web Pages

By Thau

Rating: 4.5 out of 5 stars

4.5/5

()

Read preview

About this ebook

JavaScript makes it easy to add interactivity, animation, and other tricks to your web pages. But this isn't just a book of JavaScripts for you to cut and paste into your HTML, only to find out that nothing works as you'd expected. Using real-world examples as the starting point, author thau! walks you step-by-step through various scripts and explains how they produce the effects you want.

Because no discussion of JavaScript today is complete without coverage of Ajax Asynchronous JavaScript and XML), this thoroughly updated second edition includes new chapters on Ajax to get you up to speed with this valuable method for creating truly dynamic web pages.

You'll also find revised appendices and new examples that reflect today's web environment. Learn to:
– Work with frames, forms, cookies, and alarms
– Use events to react to a user's actions
– Perform image swaps and rollovers
– Program your own functions to produce customized solutions
– Store user preferences and build a shopping cart
– Use Ajax to turn web pages into applications

If you need to spruce up tired-looking pages, The Book of JavaScript, 2nd Edition will help take your site from bland to brilliant.

BONUS: Includes a complete reference to all JavaScript objects and functions, including examples, properties, methods, handlers, and browser compatibility!
LanguageEnglish
PublisherNo Starch Press
Release dateDec 6, 2006
ISBN9781593271305
The Book of JavaScript, 2nd Edition: A Practical Guide to Interactive Web Pages

Related to The Book of JavaScript, 2nd Edition

Related ebooks

Programming For You

View More

Reviews for The Book of JavaScript, 2nd Edition

Rating: 4.5 out of 5 stars
4.5/5

3 ratings1 review

What did you think?

Tap to rate

Review must be at least 10 words

  • Rating: 5 out of 5 stars
    5/5

    Nov 13, 2024

    Thank You This Is Very Good, Maybe This Can Help You
    Download Full Ebook Very Detail Here :
    https://amzn.to/3XOf46C
    - You Can See Full Book/ebook Offline Any Time
    - You Can Read All Important Knowledge Here
    - You Can Become A Master In Your Business

Book preview

The Book of JavaScript, 2nd Edition - Thau

The Book of JavaScript, 2nd Edition

The Book of JavaScript, 2nd Edition

Table of Contents

ADVANCE PRAISE FOR THE BOOK OF JAVASCRIPT, 2ND EDITIONPRAISE FOR THE BOOK OF JAVASCRIPT, 1ST EDITIONFOREWORDFOREWORD TO THE FIRST EDITIONACKNOWLEDGMENTSINTRODUCTIONHow This Book Is OrganizedCompanion Website1. WELCOME TO JAVASCRIPT!Is JavaScript for You?Is This Book for You?The Goals of This BookWhat Can JavaScript Do?What Are the Alternatives to JavaScript?CGI ScriptingVBScriptJavaFlashJavaScript's LimitationsJavaScript Can't Talk to ServersJavaScript Can't Create GraphicsJavaScript Works Differently in Different BrowsersGetting StartedWhere JavaScript Goes on Your Web PagesDealing with Older BrowsersYour First JavaScriptSummaryAssignment2. USING VARIABLES AND BUILT-IN FUNCTIONS TO UPDATE YOUR WEB PAGES AUTOMATICALLYVariables Store InformationSyntax of VariablesNaming VariablesArithmetic with VariablesWrite Here Right Now: Displaying ResultsLine-by-Line Analysis of Figure 2-4StringsLine-by-Line Analysis of Figure 2-6More About Functionsalert()Line-by-Line Analysis of Figure 2-9prompt()ParametersWriting the Date to Your Web PageBuilt-in Date FunctionsDate and Time MethodsCode for Writing the Date and TimeLine-by-Line Analysis of Figure 2-12How the European Space Agency Writes the Date to Its PageSummaryAssignment3. GIVING THE BROWSERS WHAT THEY WANTA Real-World Example of Browser DetectionBrowser Detection MethodsQuick-but-Rough Browser DetectionMore Accurate Browser DetectionRedirecting Visitors to Other Pagesif-then StatementsBoolean ExpressionsNestingif-then-else Statementsif-then-else-if StatementsWhen and Where to Place Curly BracketsOR and ANDORANDPutting It All TogetherA Few More Details About Boolean ExpressionsHow Netscape Provides Browser-Specific ContentSummaryAssignment4. WORKING WITH ROLLOVERSA Real-World Example of RolloversTriggering EventsEvent TypesQuotes in JavaScriptClicking the Link to NowhereMore Interesting ActionsSwapping ImagesWorking with Multiple ImagesWhat's with All the Dots?The document ObjectObject PropertiesFinally, Rollovers!Image PreloadingHow the Tin House Rollovers WorkSummaryAssignment5. OPENING AND MANIPULATING WINDOWSReal-World Examples of Opening Windows to Further InformationWorking with Windows as ObjectsOpening WindowsManipulating the Appearance of New WindowsSome Browsers and Computers Open Windows DifferentlyClosing WindowsUsing the Right Name: How Windows See Themselves and Each OtherMoving Windows to the Front or Back of the ScreenWindow PropertiesThe status PropertyThe opener PropertyMore Window MethodsResizing WindowsMoving WindowsSummaryAssignment6. WRITING YOUR OWN JAVASCRIPT FUNCTIONSFunctions as ShortcutsBasic Structure of JavaScript FunctionsNaming Your FunctionsParentheses and Curly BracketsAn Example of a Simple FunctionWriting Flexible FunctionsUsing ParametersLine-by-Line Analysis of Figure 6-4Using More Than One ParameterGetting Information from FunctionsLine-by-Line Analysis of Figure 6-9Dealing with Y2KLine-by-Line Analysis of Figure 6-12Defining Variables ProperlySummaryAssignment7. PROVIDING AND RECEIVING INFORMATION WITH FORMSReal-World Examples of FormsForm BasicsText FieldsButtons, Checkboxes, and Radio ButtonsSelect ElementsTextareasFinal Form CommentsForms and JavaScriptNaming Form ElementsNaming Radio ButtonsNaming OptionsReading and Setting Form ElementsReading Information from Text FieldsSetting the Value of a Text FieldTextareasCheckboxesRadio ButtonsPull-Down Menus and Scrollable ListsHandling Events Using Form ElementsMake this a ShortcutUsing Pull-Down Menus as Navigational ToolsOne Last Forms ShortcutHow the Doctors Without Borders Pull-Down Navigation Tool WorksSummaryAssignment8. KEEPING TRACK OF INFORMATION WITH ARRAYS AND LOOPSReal-World Examples of ArraysJavaScript's Built-In ArraysFiguring Out How Many Items an Array ContainsGoing Through Arrayswhile Loopswhile Loops and ArraysGoing Off the Deep EndUsing array.length in Your LoopAn Incremental ShortcutBeware of Infinite Loopsfor LoopsHow AntWeb Checks Off All the CheckboxesLine-by-Line Analysis of Figure 8-11Creating Your Own ArraysLine-by-Line Analysis of Figure 8-12How the Book of JavaScript Tip Box WorksChecking for Blank StatementsChecking the Last Element in the ArrayTesting the Limits of ArraysThe startScroll() FunctionA Streamlined VersionLoops Can NestCreating Arrays As You Go AlongAssociative ArraysLine-by-Line Analysis of Figure 8-18SummaryAssignment9. TIMING EVENTSReal-World Examples of Timing EventsSetting an Alarm with setTimeout()Canceling an Alarm with clearTimeout()Line-by-Line Analysis of Figure 9-3Repeating Timed ActionsLine-by-Line Analysis of Figure 9-5Using parseInt() with Form ElementsClearing Out a Time-Out Before You Set a New OneDeclaring Variables That Hold Time-Outs Outside FunctionsBuilding a Clock with Timing LoopsLine-by-Line Analysis of Figure 9-7How the Book of JavaScript Website's Timer WorksHow Space.com's Countdown Script WorksCalculating TimesGlobal Variables and ConstantsA Timed Slide ShowLine-by-Line Analysis of Figure 9-11A Safer Version of rotateImage()Why Declaring a Variable Outside a Function Is UnsafeWhy You Can't Put var Inside a Timing LoopThe SolutionThe HitchThe Solution to the HitchWhy image_array Is Declared Outside the rotateImage() FunctionSummaryAssignment10. USING FRAMES AND IMAGE MAPSA Real-World Example of Frames and Image MapsFramesFrame BasicsFrames and JavaScriptFrames and Image SwapsChanging the Contents of Two Frames at OnceFrames Inside FramesJavaScript and Frames Inside FramesFrame BustingUsing Frames to Store InformationLine-by-Line Analysis of Figure 10-15Image MapsImage Map BasicsImage Maps and JavaScriptHow Salon's Bug-Eating Script WorksSalon's Nested FramesSalon's Image MapThe changeMe() FunctionSummaryAssignment11. VALIDATING FORMS, MASSAGING STRINGS, AND WORKING WITH SERVER-SIDE PROGRAMSA Real-World Example of Form ValidationMaking Sure a Visitor Has Filled Out a Form ElementLine-by-Line Analysis of Figure 11-2String HandlingBreaking Strings ApartMatching String Patterns with Regular ExpressionsHow Dictionary.com's Form Validators WorkLine-by-Line Analysis of Figure 11-11SummaryAssignment12. SAVING VISITOR INFORMATION WITH COOKIESA Real-World Example of CookiesWhat Are Cookies?What Cookies Can and Can't DoWorking with CookiesSetting CookiesReading CookiesResetting CookiesSetting More Than One Piece of InformationSetting the Duration of a CookieWho Can Read the Cookie?The Whole CookieSetting Multiple CookiesCookie LibrariesA Cookie-Based Shopping CartAdding an Item to the CartThe Checkout PageThe readTheCookie() FunctionThe checkOut() FunctionSummaryAssignment13. DYNAMIC HTMLReal-World Examples of DHTMLCSS BasicsThe

TagPositioning a div with CSSHiding a divLayering divsJavaScript and DHTMLMaking divs MoveUsing setTimeout() and clearTimeout() to Animate a PageLine-by-Line Analysis of Figure 13-10Changing the Contents of a divspans and getElementsByTagName()Advanced DOM TechniquesW3C DOM OverviewCreating and Adding Elements Using the W3C DOMAdding Text to an ElementAdding Elements in the Middle of a Page and Removing ElementsAdditional DOM DetailsManipulating a Page Using the DOMFancy Event HandlingThe event ObjectAdding Event Handlers Using JavaScriptDrop-Down MenusLine-by-Line Analysis of Figure 13-23The BordersSummaryAssignment14. AJAX BASICSA Real-World Example of AjaxIntroduction to AjaxAsynchronicity—The A in AjaxXML—The X in AjaxJavaScript—The J in AjaxCreating and Sending RequestsCreating a Request ObjectTelling the Object Where to Send the RequestWhat to Do When the Request Is AnsweredWriting JavaScript That Is Called After the Request Has Been AnsweredSending the RequestPutting Everything TogetherGetting the ResultsDemonstrating AsynchronicityLine-by-Line Analysis of Figure 14-6Ajax and UsabilityThe Back ButtonURLs and BookmarkingPoor DesignTo Ajax, or Not to AjaxBad: Just Because You CanBad: It's the Hot New ThingBad: Replacing Something That Works with Something New and ConfusingGood: In-Context Data ManipulationGood: Interactive WidgetsGood: Saving StateSummaryAssignment15. XML IN JAVASCRIPT AND AJAXA Real-World Example of Ajax and XMLGoogle SuggestXML—the Extensible Markup LanguageThe Rules of XMLThe XML HeaderXML ElementsXML AttributesIllegal XML CharactersXML Documents Have a Single Root ElementFinal Comments About the XML FormatProcessing XMLLine-by-Line Analysis of Figure 15-6Internet Explorer, responseXML, and Client-Side AjaxProblems with White Space in XMLCreating a Suggest Application for TranslationFinding the TranslationsDisplaying the ResultsSummaryAssignment16. SERVER-SIDE AJAXReal-World Examples of Server-Side AjaxThe Power of WebserversA Server-Side Programming LanguagePHP BasicsSending Simple Input to PHP with a GET RequestPassing Input in a URLUsing PHP to Read the Inputs of a GET RequestCreating a Google Suggest Application with an Ajax GET RequestContacting Third-Party Webservers with Ajax and PHPThe JavaScript for the Homemade Google Suggest ApplicationUsing PHP to Contact Other WebserversAjax and the POST MethodAn Ajax-Friendly FormPOSTing with AjaxSending XML Information from the Browser to a WebserverHEAD Requests: Getting Information About a Server-Side FileAdding Headers to Your ResponsesHeaders and XMLThe Caching ProblemFile Handling in PHPCreating and Adding Contents to a Text File with PHPReading Files in PHPWhen Communication Breaks DownAutomatically Updating a Web Page When a Server-Side File ChangesreadFileDoFunction()callReadFile()callUpdateIfChanged()stopTimer()Recap and BreatheThe Server-Side PHP CodeSummaryAssignment17. PUTTING IT ALL TOGETHER IN A SHARED TO DO LISTFeatures of the To Do List ApplicationTo Do List Data FilesuserInfo.xmlTo Do List FileTo Do List Server SideThe To Do List Client Side, Part 1: The HTMLThe To Do List Client Side, Part 2: The JavaScriptThe Function Road MapLogging In and OutFunctions Related to Logging InHelper FunctionsDisplaying Available ListsDisplaying a Specific ListProcessing Changes to a ListLimitations on Manipulating XML DocumentsAdding a New ItemA Few Closing NotesClient-Side or Server-Side Code?Security IssuesSummaryAssignment18. DEBUGGING JAVASCRIPT AND AJAXGood Coding PracticesStarting with CommentsFilling In the CodeAvoiding Common MistakesUse a Consistent Naming ConventionAvoid Reserved WordsRemember to Use Two Equal Signs in Logical TestsUse Quotation Marks CorrectlyFinding BugsPrinting Variables with alert() StatementsDebugging Beyond AlertsUsing Your Browser's Bug DetectorUsing JavaScript DebuggersDebugging Ajax in Firefox 1.5 and 2.0Other Debugging ResourcesFixing BugsBack Up Your ProgramFix One Bug at a TimeAvoid Voodoo CodingLook for Similar BugsClear Your HeadAsk for HelpSummaryA. ANSWERS TO ASSIGNMENTSChapter 2Chapter 3Chapter 4Chapter 5index.htmlimage_page.htmlChapter 6Chapter 7Chapter 8Chapter 9Chapter 10index.htmlassignment-nav.htmlblank.htmlChapter 11index.htmlassignment-nav.htmlblank.htmlChapter 12Chapter 13Chapter 14addressBook.xmlindex.htmlChapter 17Join FunctionsGiving a User Access to Your To Do ListB. RESOURCESTutorialsHTML TutorialsCascading Style Sheets TutorialsAdvanced Topics in JavaScriptAjax TutorialsExample JavaScript and Ajax CodeGood Ajax WebsitesAjax FrameworksJavaScriptPHPJava.NETRubyC. REFERENCE TO JAVASCRIPT OBJECTS AND FUNCTIONSalert() [FF, IE 3]AnchorPropertiesAppletPropertiesMethodsArea [FF, IE 3]Array [FF, IE 3]PropertiesMethodsLess Common MethodsButton (Including Submit and Reset Buttons)PropertiesHandlersMethodsCheckboxPropertiesHandlersMethodsclearInterval() [FF, IE 4]clearTimeout() [FF, IE 3]confirm() [FF, IE 3]DateMethods for Getting the Date and TimeMethods for Getting the UTC Date and TimeThe Problematic getYear() MethodMethods for Setting the Date and TimeMethods for Setting the UTC Date and TimeMethods for Converting Dates to StringsDocumentPropertiesMethodselements[] [FF, IE 3]escape() [FF, IE 3]eval() [FF, IE 3]EventPropertiesFileUploadPropertiesMethodsHandlersFormPropertiesMethodsHandlersHiddenPropertiesHistoryPropertiesMethodsHTMLElement [FF, IE 4]PropertiesMethodsHandlers [FF, IE 4]ImagePropertiesisNaN() [FF, IE 4]LinkLocationPropertiesMethodsMath [FF, IE 3]PropertiesMethodsNavigatorPropertiesLess Common PropertiesMethodsNumberPropertiesMethodsOptionPropertiesparseInt() [FF, IE 3]parseFloat() [FF, IE 3]PasswordPropertiesMethodsHandlersprompt()RadioPropertiesMethodsHandlersResetScreenPropertiesSelectPropertiesHandlerssetInterval() [FF, IE 4]setTimeout() [FF, IE 3]StringPropertiesMethodsStyle [FF, IE 4]Properties [FF, IE 5]SubmitTextTextareaPropertiesMethodsHandlersthis [FF, IE 3]unescape() [FF, IE 3]var [FF, IE 3]windowPropertiesMethodsFeaturesMethodsLess Common MethodsHandlersXMLHttpRequest [FF] and ActiveXObject(Microsoft.XMLHTTP) [IE 5.5]PropertiesMethodsHandlersD. CHAPTER 15'S ITALIAN TRANSLATOR AND CHAPTER 17'S TO DO LIST APPLICATIONChapter 15's Italian TranslatorChapter 17's To Do List Applicationtodo.htmlreadXMLFile.phpsaveXMLFile.php

The Book of JavaScript, 2nd Edition

thau!

Copyright © 2006

The Book of JavaScript, 2nd Edition

No Starch Press


Dedication

I dedicate this revised edition of The Book of JavaScript to my wonderful wife Kirsten Menger-Anderson, who never failed to keep a straight face when I said, It's almost done.

ADVANCE PRAISE FOR THE BOOK OF JAVASCRIPT, 2ND EDITION

Thau! has been demonstrating his JavaScript wisdom since before it was cool. Now, this new edition of his classic text makes JavaScript wizardry more accessible than ever for experts and beginners alike.

--JESSE JAMES GARRETT, CREATOR OF THE TERM AJAX AND AUTHOR OF The Elements of User Experience

The fastest way to killer JavaScript chops!

--STEWART BUTTERFIELD, CO-FOUNDER, FLICKR.COM

"The new version of The Book of JavaScript offers the same elegant simplicity, but now includes the whiz-bang popular advances like working with the DOM and Ajax."

--TED RHEINGOLD, TOP DOG, DOGSTER, INC. (DOGSTER.COM AND CATSTER.COM)

PRAISE FOR THE BOOK OF JAVASCRIPT, 1ST EDITION

"The Book of JavaScript shines. . . . [It's] an outstanding model for teaching language by example."

--WEB TECHNIQUES (NOW NEW ARCHITECT)

A great introduction to JavaScript for beginners.

--JAVASCRIPT.COM

"The Book of JavaScript is ideal for people who are intimidated by the thought of writing code."

--FOREWORD MAGAZINE

A practical, surprisingly easy guide to use, even for relative novices.

--THE MIDWEST BOOK REVIEW

"Thau's JavaScript tutorials at Webmonkey.com are so insanely popular, they've earned him a Plato-like following of devoted fans . . . Thau-mania is destined to grow to Elvis proportions."

--EVANY THOMAS, FORMER MANAGING EDITOR, WEBMONKEY.COM

FOREWORD

The first JavaScript I remember writing was a routine to change two frames at the same time. I was the production specialist for HotWired, and it was shortly after frames and JavaScript debuted, well before there was documentation for either. Fortunately, it was also well before Internet Explorer 3.0 appeared on the scene, so I only had to make sure my JavaScript worked for Netscape 2.0. Even so, without a reference book to point out where possible pitfalls could be or answer simple questions such as how to set variables that JavaScript would like or how to make different windows talk to each other, it was one hell of a challenge. And it was deeply satisfying when I got it to work correctly.

When Dave asked me to do the technical review of the second edition of The Book of JavaScript, I couldn't have been more pleased or honored. The deep satisfaction I felt when I wrote those first JavaScripts and they worked correctly, and the deeper satisfaction I felt as more and more browsers were released and I figured out how to write cross-browser and cross-platform JavaScript, are the same feelings I got when I read Dave's explanations and examples. He describes what a piece of code is going to do and how to think about it, then lays out an example of code that makes sense—whether you're a seasoned programmer or entirely new to JavaScript. On top of all that, he takes a practical approach to programming, he's able to explain complex problems in a way that doesn't make them sound daunting, and when you're done covering each topic, you feel like you've earned the knowledge. That's rare, and it's really, really refreshing.

Since the first edition of this book was published, there have been a few advancements in JavaScript, most notably the advent of Ajax. Ajax is a concept that makes even a few professional programmers' heads spin, but (not surprisingly) Dave manages to break down what Ajax is and what it isn't, explains when it makes sense to use it, and shows you how to do it.

If you're new to JavaScript, you win—you couldn't ask for a better person to teach you how to program. If you're an old hat at JavaScript and you're looking for a refresher course or wondering how to take advantage of Ajax, you win too.

Happy coding!

Luke Knowland

Interaction Designer, Six Apart

San Francisco

FOREWORD TO THE FIRST EDITION

I learned JavaScript completely on my own. There was no one to tell me about event handlers or how to set cookies. No one even explained what a variable is, let alone the best ways to name them. Of course I had reference books, but they were intimidating tomes, full of cryptic lists and tables, written by programmers for programmers.

David Thau is a remarkable combination of natural teacher and seasoned programmer. As a result, The Book of JavaScript not only teaches JavaScript thoroughly and enjoyably in a friendly, unintimidating tone, but it teaches programming as elegantly as any book I've seen. In fact, I've always thought of this as Thau's ulterior motive—he pretends he's just showing you how to make a rollover or validate the text in an HTML form, but before you know it you've learned how to code!

Perhaps the most telling thing I can say is that, reading this book, I can't help but wish I was learning JavaScript for the first time. If you are, then consider yourself lucky to have Thau as a teacher. You couldn't do better.

Happy JavaScripting!

Nadav Savio

Principal, Giant Ant Design

San Francisco

ACKNOWLEDGMENTS

This second edition of The Book of JavaScript took me much longer to complete than I could have imagined. I'd like to thank the entire No Starch Press staff for putting up with all the delays and surprise extra bits. I would especially like to thank Christina Samuell for moving the process along, William Pollock, Riley Hoffman, Jerome Colburn, and Stephanie Provines for extensive edits, and Luke Knowland for making sure all the code works and offering many excellent suggestions. I'd also like to thank my neighbor, Laurentino Padilla, for sweeping our sidewalk on Thursdays. Without him, this book would have taken even longer to finish.

INTRODUCTION

You are about to begin a journey through JavaScript—a programming language that adds interactivity and spark to web pages all over the Internet. This book, written primarily for nonprogrammers, provides scripts you can cut and paste for use on your website, but it also explains how they work, so you'll soon be writing your own scripts. Each chapter focuses on a few important JavaScript features, shows you how professional websites incorporate those features, and gives you examples of how you might add those features to your own web pages.

How This Book Is Organized

Before you dive in, here is a quick overview of what you'll learn as you make your way through The Book of JavaScript.

Have fun!

Chapter 1

This chapter lays out the book's goals, introduces you to JavaScript and compares it to other tools, describes some of the nifty ways in which JavaScript can enhance your web pages, and walks you through writing your first JavaScript.

Chapter 2

Did you know that JavaScript can figure out what day it is and write the date to a web page? This chapter will show you how. Along the way you'll also learn how JavaScript remembers things using variables and performs actions using functions.

Chapter 3

In this chapter you'll learn how to direct someone to a web page specifically designed for his or her browser. You'll figure out which browser the visitor is using, then you'll use if-then statements and their kin to point the visitor in the right direction.

Chapter 4

This chapter covers everyone's favorite JavaScript trick—the image swap. You'll also learn how to trigger JavaScript based on a viewer's actions.

Chapter 5

This chapter explains everything you need to know about opening new browser windows—another favorite JavaScript trick. You'll also learn how JavaScript writes HTML to the new windows, closes them, and moves them around on the screen.

Chapter 6

Functions are the major building blocks of any JavaScript program, so learning to write your own is a critical step toward JavaScript mastery. This chapter gives you the tools you'll need to write your own functions and put them to work.

Chapter 7

This chapter shows you how JavaScript works with HTML forms to collect all kinds of information from your users and give them fancy ways to navigate your site.

Chapter 8

JavaScript calls lists arrays, and they come in very handy. This chapter describes how JavaScript deals with these lists, whether they include all the images on a web page or all the friends in your address book.

Chapter 9

This chapter discusses setting events to occur at specific times. For example, you can open a window and then close it in five seconds, or you can write a clock that updates every second. Once you know how to do this, you can create games and other interactive applications based on timed events.

Chapter 10

How JavaScript works with HTML frames and image maps is the subject of this chapter. It covers topics including changing two or more frames at once and preventing your web page from getting trapped in someone else's frame set.

Chapter 11

This chapter shows you how to make sure people are filling out your HTML forms completely. Along the way, you'll learn fancy ways to check user input—for example, you'll learn how to check the formatting of an email address.

Chapter 12

Cookies are bits of code that let your web pages save information a visitor has provided even after he or she turns off the computer. This allows your site to greet a guest by name whenever he visits (if he tells you his name, of course!).

Chapter 13

This chapter introduces Dynamic HTML, a feature of newer browsers that lets you animate entire web pages.

Chapter 14

This chapter begins a trilogy of chapters on Ajax, a programming technique that helps you build websites that act like desktop applications. Here you'll be introduced to Ajax and most of the JavaScript you'll need to know to create Ajax applications.

Chapter 15

The X in Ajax stands for XML. This chapter describes how to represent information using the XML data-sharing standard and process XML documents using JavaScript.

Chapter 16

You'll wrap up your introduction to Ajax with instructions for writing programs that run on webservers. This chapter touches on the PHP programming language and shows you how PHP programs store files on webservers and contact other webservers for information.

Chapter 17

In this chapter you'll apply everything you learned in the first 16 chapters and create a collaborative To Do list application. Not much new material will be introduced, but you'll see how everything we've covered so far fits together.

Chapter 18

This chapter wraps things up by giving you tips for what to do when the JavaScript you've written isn't working correctly.

Appendix A

Here you'll find answers to the assignments that end each chapter.

Appendix B

This appendix provides information about the many JavaScript and Ajax libraries you can use to further enhance your web pages.

Appendix C

This appendix lists all of the objects and functions that comprise JavaScript.

Appendix D

The last appendix gives a couple of the book's longest code examples in their entirety.

Companion Website

The Book of JavaScript website (http://www.bookofjavascript.com) contains the code examples from each chapter, archived copies of many of the websites mentioned, and lots of script libraries and freeware. You'll find that each chapter has its own directory, complete with the example scripts and relevant images from that chapter, as well as the answer to that chapter's assignment. Here's a rundown of the directories.

/Chapter01, /Chapter02, and so on

Each chapter has its own directory. For example, the code examples from Chapter 1 are available at http://www.bookofjavascript.com/Chapter01.

/Freeware

This directory contains free software you may find useful, including:

XAMPP webserver and PHP packages for Windows and Linux

MAMP webserver and PHP packages for Macintosh

Flock social web browser

Venkman JavaScript debugger for Firefox

Firefox 2.0 browser

/Libraries

This directory contains free JavaScript libraries you can cut and paste into your website, including:

Prototype JavaScript Framework

Webmonkey Cookie Library

Sarissa XML Toolkit

/Websites

This directory contains HTML (including JavaScript) and images for many of the websites discussed in the book.

Chapter 1. WELCOME TO JAVASCRIPT!

Welcome to The Book of JavaScript. JavaScript is one of the fastest and easiest ways to make your website truly dynamic—that is, interactive. If you want to spruce up tired-looking pages, you've got the right book.

This book will give you some ready-made JavaScripts you can implement immediately on your website, but, more importantly, it will take you step by step through sample scripts (both hypothetical and real-world examples) so that you understand how JavaScript works. With this understanding you can modify existing scripts to fit your specific needs as well as write scripts from scratch. Your knowledge of JavaScript will grow as you work through the book; each chapter introduces and explores in depth a new JavaScript topic by highlighting its application in real-life situations.

Is JavaScript for You?

If you want a quick, easy way to add interactivity to your website, if the thought of using complex programming languages intimidates you, or if you're interested in programming but simply don't know where to start, JavaScript is for you.

JavaScript, a programming language built into your web browser, is one of the best ways to add interactivity to your website because it's the only cross-browser language that works directly with web browsers. Other languages such as Java, Perl, PHP, and C don't have direct access to the images, forms, and windows that make up a web page.

JavaScript is also very easy to learn. You don't need any special hardware or software, you don't need access to a webserver, and you don't need a degree in computer science to get things working. All you need is a web browser and a text editor such as SimpleText or Notepad.

Finally, JavaScript is a complete programming language, so if you want to learn more about programming, it provides a great introduction. (If you don't give a hoot about programming, that's fine too. There are plenty of places—including this book and its companion website—where you can get prefab scripts to cut and paste right into your pages. But you'll get much more out of the book by using it as a tool for learning JavaScript programming.)

Is This Book for You?

This book assumes you don't have any programming background. Even if you have programmed before, you'll find enough that's new in JavaScript to keep you entertained. One of the best things about JavaScript is that you don't have to be a mega-expert to get it working on your web pages right away. You do need a working knowledge of HTML, however.

The Goals of This Book

The main goal of this book is to get you to the point of writing your own JavaScripts. An important tool in learning to write scripts is the ability to read other people's scripts. JavaScript is a sprawling language, and you can learn thousands of little tricks from other scripts. In fact, once you've finished this book, you'll find that viewing the source code of web pages that use JavaScript is the best way to increase your knowledge.

Each of the following chapters includes JavaScript techniques used in building professional sites. Along the way, I'll point out sites that use the technique described, and by viewing the source code of such sites you'll soon see there are many ways to script. Sometimes going through a site's code reveals interesting aspects of JavaScript that I don't cover in this book.

Beyond learning how to write your own JavaScript and read other people's scripts, I also want you to learn where to look for additional information on JavaScript. As I've noted, the best place to learn new techniques is to view the source code of web pages you find interesting. However, several websites also offer free JavaScripts. I'll be introducing some of these as we go along, but here are a few good examples to get you started:

http://www.webmonkey.com/reference/javascript_code_library

http://javascript.internet.com

http://www.scriptsearch.com/JavaScript/Scripts

http://www.javascriptsearch.com

Another good place to get information is a JavaScript reference book. The Book of JavaScript is primarily a tutorial for learning basic JavaScript and making your website interactive. It's not a complete guide to the language, which includes too many details for even a lengthy introduction to cover. If you're planning to become a true JavaScript master, I suggest picking up JavaScript: The Definitive Guide by David Flanagan (O'Reilly, 2006) after making your way through this book. The last 500 or so pages of Flanagan's book list every JavaScript command and the browsers in which it works.

What Can JavaScript Do?

JavaScript can add interactivity to your web pages in a number of ways. This book offers many examples of JavaScript's broad capabilities. The following are just two examples that illustrate what you can do with JavaScript.

The first example (Figure 1-1) is a flashing grid of colored squares (to get the full effect, browse to http://www.bookofjavascript.com/Chapter01/Fig01-01.html), created by a fellow named Taylor way back in 1996. Flashy, isn't it? In this example, a JavaScript function changes the color of a randomly chosen square in the grid every second or so.

A demonstration of JavaScript's artful abilities

Figure 1-1. A demonstration of JavaScript's artful abilities

Mousing over one of the five icons below the squares (number, plus sign, square, letter, and horizontal line) tells the page to use a new set of images on the grid. For example, mousing over the number icon tells the JavaScript to start replacing the squares with 1s and 0s. This page illustrates four important JavaScript features you'll learn about throughout the book:

How to change images on a web page

How to affect web pages over time

How to add randomness to web pages

How to dynamically change what's happening on a web page based on an action taken by someone viewing the page

Although Taylor's demo is beautiful, it's not the most practical application of JavaScript. Figure 1-2 (available at http://www.bookofjavascript.com/Chapter01/Fig01-02.html) shows you a much more practical use of JavaScript that calculates the weight of a fish based on its length. Enter the length and type of fish, and the JavaScript calculates the fish's weight. This fishy code demonstrates JavaScript's ability to read what a visitor has entered into a form, perform a mathematical calculation based on the input, and provide feedback by displaying the results in another part of the form. You may not find calculating a fish's weight a particularly useful application of JavaScript either, but you can use the same skills to calculate a monthly payment on a loan (Chapter 7), score a quiz (Chapter 10), or verify that a visitor has provided a valid email address (Chapter 11).

How much does my fish weigh?

Figure 1-2. How much does my fish weigh?

These are just two examples of the many features JavaScript can add to your websites. Each chapter will cover at least one new application. If you want a preview of what you'll learn, read the first page or so of each chapter.

What Are the Alternatives to JavaScript?

Several other programming languages can add interactivity to web pages, but they all differ from JavaScript in important ways. The four main alternatives are CGI scripting, Java, VBScript, and Flash.

CGI Scripting

Before JavaScript, using CGI scripts was the only way to make web pages do more than hyperlink to other web pages containing fixed text. CGI stands for Common Gateway Interface. It's a protocol that allows a web browser running on your computer to communicate with programs running on webservers. It is most often used with HTML forms—pages where the user enters information and submits it for processing. For example, the user might see a web page containing places for entering the length and selecting the type of a fish, as well as a Compute button. When the user keys in the length, selects the type, and clicks the button, the information is sent to a CGI script on the server. The CGI script (which is probably written in a programming language like Perl, PHP, or C) receives the information, calculates the weight of the fish, and sends the answer, coded as an HTML page, back to the browser.

CGI scripts are very powerful, but because they reside on webservers, they have some drawbacks.

The Need for Back-and-Forth Communication

First, the connection between your web browser and the webserver limits the speed of your web page's interactivity. This may not sound like a big problem, but imagine the following scenario: You're filling out an order form with a dozen entry fields including name, address, and phone number (see Figure 1-3), but you forget to fill out the phone number and address fields. When you click the Submit button to send the information across the Internet to the webserver, the CGI script sees that you didn't fill out the form completely and sends a message back across the Internet requesting that you finish the job. This cycle could take quite a while over a slow connection. If you fill out the form incorrectly again, you have to wait through another cycle. People find this process tiresome, especially if they're customers who want their orders processed quickly.

With JavaScript, though, the programs you write run in the browser itself. This means that the browser can make sure you've filled out the form correctly before sending the form's contents to the webserver. JavaScript thus reduces the time your information spends traveling between the browser and the server.

A simple order form

Figure 1-3. A simple order form

Server Overload by Concurrent Access

Another drawback to CGI scripts is that a webserver running a CGI program can get bogged down if too many people call the script simultaneously (for example, if too many fishermen decided to run the weight calculator and click the Compute button at the same time). Serving up HTML pages is pretty easy for a webserver. However, some CGI scripts take a long time to run on a machine, and each time someone calls the script, the server has to start up another copy of it. As more and more people try to run the script, the server slows down progressively. If a thousand people are trying to run the script at once, the server might take so long to respond that either the user or the browser gives up, thinking the server is dead. This problem doesn't exist in JavaScript because its scripts run on each visitor's web browser—not on the webserver.

Security Restrictions

A third problem with CGI scripts is that not everyone has access to the parts of a webserver that can run CGI scripts. Since a CGI script can conceivably crash a webserver or exploit security flaws, system administrators generally guard these areas, only allowing fellow administrators access. If you have Internet access through an Internet service provider (ISP), you may not be allowed to write CGI scripts. If you are designing web pages for a company, you may not be given access to the CGI-enabled areas of the webserver. JavaScript, on the other hand, goes right into the HTML of a web page. If you can write a web page, you can put JavaScript in the page without permission from recalcitrant administrators.

VBScript

The language most similar to JavaScript is Microsoft's proprietary language, VBScript (VB stands for Visual Basic). Like JavaScript, VBScript runs on your web browser and adds interactivity to web pages. However, VBScript works only on computers running Internet Explorer (IE) on Microsoft Windows, so unless you want to restrict your readership to people who use IE on Windows, you should go with JavaScript.

Java

Although JavaScript and Java have similar names, they aren't the same. Netscape, now a part of AOL, initially created JavaScript to provide interactivity for web pages, whereas Sun Microsystems wrote Java as a general programming language that works on all kinds of operating systems.

Flash

Flash is a tool from Macromedia developed to add animation and interactivity to websites. Almost all modern browsers can view Flash animations or can easily download the Flash plug-in. Flash animations look great, and a basic Flash animation requires no programming skills at all. To create Flash animations, however, you must purchase a Flash product from Macromedia.

While some people consider Flash and JavaScript to be competitors, that's not the case. In fact, you can call JavaScript programs from Flash, and you can manipulate Flash animations using JavaScript. Web page designers will often blend the two, using Flash for animations and JavaScript for interactivity that does not involve animations. Flash animations can also be made more interactive using a language called ActionScript, which is almost exactly like JavaScript.

JavaScript's Limitations

Yes, JavaScript does have limitations, but these limitations are natural and unavoidable by-products of its main purpose: to add interactivity to your web pages.

JavaScript Can't Talk to Servers

One of JavaScript's drawbacks is also its main strength: It works entirely within the web browser. As we've seen, this cuts down on the amount of time your browser spends communicating with a webserver. On the other hand, this also means that JavaScript can't communicate with other machines and therefore can't handle some server tasks you may need to do.

For example, JavaScript can't aggregate information collected from your users. If you want to write a survey that asks your visitors a couple of questions, stores their answers in a database, and sends a thank-you email when they finish, you'll have to use a program that runs on your webserver. As we'll see in Chapter 7, JavaScript can make the survey run more smoothly, but once a visitor has finished filling out the questions, JavaScript can't store the information on the server, because it can't contact the server. In order to store the survey information, you need to use a program that runs on a webserver. Sending email with JavaScript is also impossible, because to send email JavaScript would have to contact a mail server. Again, you need a server-side program for this job.

Although JavaScript can't directly control programs that run on webservers, it can ask webservers to run programs, and it can send information to those programs. We'll see examples of that in Chapter 7 and Chapter 13, and we'll get a taste for writing server-side programs in Chapter 15 and Chapter 16.

JavaScript Can't Create Graphics

Another of JavaScript's limitations is that it can't create its own graphics. Whereas more complicated languages can draw pictures, JavaScript can only manipulate existing pictures (that is, GIF or JPEG files). Luckily, because JavaScript can manipulate created images in so many ways, you shouldn't find this too limiting.

JavaScript Works Differently in Different Browsers

Perhaps the most annoying problem with JavaScript is that it works somewhat differently in different browsers. JavaScript was introduced in 1996 by Netscape in version 2 of Netscape Navigator. Since then, JavaScript has changed, and every browser implements a slightly different version of it—often adding browser-specific features. Luckily, starting in the late 1990s, the European Computer Manufacturers Association (ECMA) began publishing standards for JavaScript, which they call ECMAScript. About 99 percent of all browsers being used today comply with at least version 3 of the ECMA standard. These include Internet Explorer version 5.5 and later, Netscape version 6 and later, Mozilla, Firefox, all versions of Safari, and Opera version 5 and later. Because almost all browsers currently in use adhere to version 3 of the ECMA standard, I'll be using that as the standard version of JavaScript in the book. Where incompatibilities between browsers arise, I'll point them out.

Getting Started

We're about ready to begin. To write JavaScripts, you need a web browser and a text editor. Any text editor will do: Notepad or WordPad in Windows and SimpleText on a Macintosh are the simplest choices. Microsoft Word or Corel's WordPerfect will work as well. You can also use a text editor such as BBEdit or HomeSite, which are designed to work with HTML and JavaScript.

Some tools for building websites will actually write JavaScript for you—for example, Adobe's Dreamweaver and GoLive. These tools work fine when you want to write JavaScripts for common features such as image rollovers and you know you'll never want to change them. Unfortunately, the JavaScript often ends up much longer than necessary, and you may find it difficult to understand and change to suit your needs. Unless you want a JavaScript that works exactly like one provided by the package you've purchased, you're often best off writing scripts by hand. Of course, you can also use one of these tools to figure out how you want your page to behave and then go back and rewrite the script to suit your specific needs.

Note

Always save documents as text only, and end their names with .html or .htm. If you're using Microsoft Word or WordPerfect and you don't save your documents as text-only HTML or HTM files, both programs will save your documents in formats web browsers can't read. If you try to open a web page you've written and the browser shows a lot of weird characters you didn't put in your document, go back and make sure you've saved it as text only.

Where JavaScript Goes on Your Web Pages

Now let's get down to some JavaScript basics. Figure 1-4 shows you the thinnest possible skeleton of an HTML page with JavaScript.

An HTML page with JavaScript

Figure 1-4. An HTML page with JavaScript

In Figure 1-4, you can see the JavaScript between the tags in ❶ and ❷.

Note that you can also start JavaScript with this

Although this will work in all browsers, it's better to stick to the

Enjoying the preview?
Page 1 of 1