javascript - download.e-bookshelf.de · updated and revised, this book offers a hands-on look at...

30
Wrox Programmer to Programmer™ Join the discussion @ p2p.wrox.com 4th Edition Beginning JavaScript ® Paul Wilton, Jeremy McPeak JavaScript

Upload: others

Post on 26-Jun-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

Wrox Programmer to Programmer™Join the discussion @ p2p.wrox.com

4th Edition

Beginning

JavaScript®

Paul Wilton, Jeremy McPeak

Beginning

Wilton, McPeak

$39.99 USA $47.99 CANWeb Development/JavaScript

JavaScript®

Step-by-step guidance to creating powerful web apps with JavaScript

4th Edition

wrox.comProgrammer ForumsJoin our Programmer to Programmer forums to ask and answer programming questions about this book, join discussions on the hottest topics in the industry, and connect with fellow programmers from around the world.

Code Downloads Take advantage of free code samples from this book, as well as code samples from hundreds of other books, all ready to use.

Read More Find articles, ebooks, sample chapters and tables of contents for hundreds of books, and more reference resources on programming topics that matter to you.

JavaScript allows you to enhance your web pages and web applications by providing dynamic, personalized, and interactive content. Serving as a great introduction to JavaScript, this book offers all you need to start using JavaScript on your web pages right away. It’s fully updated and covers utilizing JavaScript with the latest versions of the Internet Explorer®, Firefox®, and Safari® browsers.

• Walks you through the basics of JavaScript: what it is, how it works, and what you can do with it

• Covers the various tools needed to create JavaScript web applications

• Escorts you through selecting a single character from a string, converting character codes to a string, and copying string parts

• Shows you how to join arrays, copy parts of an array, sort arrays, and reverse an array’s order

• Explains how using a JavaScript framework (such as jQuery, Prototype, and MooTools) makes JavaScript programming faster and more efficient

• Offers an in-depth look at Ajax

• Reviews common mistakes, debugging, and error handling

Paul Wilton owns his own company, providing online booking systems to vacation property owners, which is largely developed using JavaScript.

Jeremy McPeak is a self-taught programmer who began his career by tinkering with web sites in 1998. He is the coauthor of Professional Ajax, 2nd Edition and several online articles covering topics such as XSLT, ASP.NET Web Forms, and C#. He is currently employed at an energy-based company building in-house conventional and web applications.

Wrox Beginning guides are crafted to make learning programming languages and technologies easier than you think, providing a structured, tutorial format that will guide you through all the techniques involved.

525937_cover_2.indd 1525937_cover_2.indd 1 12/18/09 2:29 PM12/18/09 2:29 PM

Page 2: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

Get more out of WROX.com

Programmer to Programmer™

InteractTake an active role online by participating in our P2P forums

Wrox Online LibraryHundreds of our books are available online through Books24x7.com

Wrox Blox Download short informational pieces and code to keep you up to date and out of trouble!

Chapters on DemandPurchase individual book chapters in pdf format

Join the CommunitySign up for our free monthly newsletter at newsletter.wrox.com

BrowseReady for more Wrox? We have books and e-books available on .NET, SQL Server, Java, XML, Visual Basic, C#/ C++, and much more!

Contact Us. We always like to get feedback from our readers. Have a book idea? Need community support? Let us know by e-mailing [email protected]

Related Wrox Books

Beginning CSS, 2nd EditionISBN: 978-0-470-17708-2Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand designers’ processes from start to finish and gain insight into how designers overcome a site’s unique set of challenges and obstacles. Become comfortable with solving common problems, learn the best practices for using XHMTL with CSS, orchestrate a new look for a blog, tackle browser-compatibility issues, and develop functional navigational structures.

Beginning JavaScript and CSS Development with jQueryISBN: 978-0-470-22779-4Beginning JavaScript and CSS Development with jQuery presents the world of dynamic web applications to web developers from the standpoint of modern standards. The author shows new JavaScript developers how working with the standard jQuery library will help them to do more with less code and fewer errors.

Concise Guide to DojoISBN: 978-0-470-45202-8Dojo has rapidly become one of the hottest JavaScript-based web development frameworks. It provides you with the power and flexibility to create attractive and useful dynamic web applications quickly and easily. In this fast-paced, code-intensive guide, you’ll discover how to quickly start taking advantage of Dojo. The pages are packed with useful information and insightful examples that will help you.

JavaScript Programmer’s ReferenceISBN: 978-0-470-34472-9Both a tutorial and a reference guide for web developers, employ this complete JavaScript reference to help you understand JavaScript data types, variables, operators, expressions, and statements, work with JavaScript frameworks and data, and improve performance with Ajax.

Professional Ajax, 2nd EditionISBN: 978-0-470-10949-6Professional Ajax, 2nd Edition is written for web application developers looking to enhance the usability of their web sites and web applications and intermediate JavaScript developers looking to further understand the language. This second edition is updated to cover Prototype, jQuery, FireBug, Microsoft Fiddler, ASP.NET AJAX Extensions, and much more.

Professional JavaScript for Web Developers, 2nd Edition ISBN: 978-0-470-22780-0This updated bestseller offers an in-depth look at the JavaScript language and covers such topics as debugging tools in Microsoft Visual Studio, FireBug, and Drosera; client-side data storage with cookies, the DOM, and Flash; client-side graphics with JavaScript including SVG, VML, and Canvas; and design patterns including creational, structural, and behavorial patterns.

Professional JavaScript Frameworks: Prototype, YUI, ExtJS, Dojo and MooTools ISBN: 978-0-470-38459-6This book offers a selection of some of the most active and most used JavaScript frameworks available, replete with practical examples and explanations of what each framework does best. You’ll look at common web development tasks and discover how each framework approaches that set of tasks, as well as learn how to use the features of each framework and avoid potential pitfalls.

525937_cover_2.indd 2525937_cover_2.indd 2 12/18/09 2:29 PM12/18/09 2:29 PM

Page 3: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

Beginning JavaScript®

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv

Chapter 1: Introduction to JavaScript and the Web . . . . . . . . . . . . . . . . . . . . . 1Chapter 2: Data Types and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Chapter 3: Decisions, Loops, and Functions . . . . . . . . . . . . . . . . . . . . . . . . . 51Chapter 4: Common Mistakes, Debugging, and Error Handling . . . . . . . . . . . 87Chapter 5: JavaScript — An Object-Based Language . . . . . . . . . . . . . . . . . . 133Chapter 6: Programming the Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189Chapter 7: HTML Forms: Interacting with the User . . . . . . . . . . . . . . . . . . . 219Chapter 8: Windows and Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263Chapter 9: String Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301Chapter 10: Date, Time, and Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347Chapter 11: Storing Information: Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . 367Chapter 12: Dynamic HTML and the W3C Document Object Model . . . . . . . 391Chapter 13: Using ActiveX and Plug-Ins with JavaScript . . . . . . . . . . . . . . . 469Chapter 14: Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491Chapter 15: JavaScript Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527Appendix A: Answers to Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591Appendix B: JavaScript Core Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 665Appendix C: W3C DOM Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697Appendix D: Latin-1 Character Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733

25937ffirs.indd i25937ffirs.indd i 9/22/09 11:23:54 AM9/22/09 11:23:54 AM

Page 4: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

25937ffirs.indd ii25937ffirs.indd ii 9/22/09 11:23:54 AM9/22/09 11:23:54 AM

Page 5: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

Beginning JavaScript®

Fourth Edition

25937ffirs.indd iii25937ffirs.indd iii 9/22/09 11:23:54 AM9/22/09 11:23:54 AM

Page 6: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

25937ffirs.indd iv25937ffirs.indd iv 9/22/09 11:23:54 AM9/22/09 11:23:54 AM

Page 7: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

Beginning JavaScript®

Fourth Edition

Paul WiltonJeremy McPeak

25937ffirs.indd v25937ffirs.indd v 9/22/09 11:23:54 AM9/22/09 11:23:54 AM

Page 8: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

Beginning JavaScript® Fourth EditionPublished byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256

www.wiley.com

Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-0-470-52593-7

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifi cally disclaim all warranties, including without limitation warranties of fi tness for a particular purpose. No warranty may be created or extended by sales or pro-motional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Library of Congress Control Number: 2009933758

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affi liates, in the United States and other countries, and may not be used without written permission. JavaScript is a registered trademark of Sun Microsystems Incorporated. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.

25937ffirs.indd vi25937ffirs.indd vi 9/22/09 11:23:54 AM9/22/09 11:23:54 AM

Page 9: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

In memory of my mum, June Wilton, who in 2006 lost her brave battle against cancer.

She was always very proud of me and my books and showed my books

to anyone and everyone she happened to meet however briefl y and whether they

wanted to see them or not! She’s very much missed.

— Paul Wilton

To my family: Starla, Hayden, and Evan (whom we haven’t yet met in person).

To my parents: Jerry and Judy.

Thank you all for your love and support.

— Jeremy McPeak

25937ffirs.indd vii25937ffirs.indd vii 9/22/09 11:23:54 AM9/22/09 11:23:54 AM

Page 10: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

25937ffirs.indd viii25937ffirs.indd viii 9/22/09 11:23:54 AM9/22/09 11:23:54 AM

Page 11: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

About the AuthorsPaul Wilton started as a Visual Basic applications programmer at the Ministry of Defense in the UK and then found himself pulled into the Net. Having joined an Internet development company, he spent three years helping create Internet solutions. He’s now running his own successful and rapidly growing com-pany developing online holiday property reservation systems.

Jeremy McPeak is a self-taught programmer who began his career by tinkering with web sites in 1998. He is the co-author of Professional Ajax, 2nd Edition (Wiley 2007) and several online articles covering top-ics such as XSLT, ASP.NET WebForms, and C#. He is currently employed in an energy-based company building in-house conventional and web applications.

Jeremy can be reached through his web site www.wdonline.com.

25937ffirs.indd ix25937ffirs.indd ix 9/22/09 11:23:54 AM9/22/09 11:23:54 AM

Page 12: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

25937ffirs.indd x25937ffirs.indd x 9/22/09 11:23:54 AM9/22/09 11:23:54 AM

Page 13: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

CreditsAcquisitions EditorScott Meyers

Project EditorMaureen Spears

Technical EditorDavid M. Karr

Production EditorRebecca Anderson

Copy EditorC.M. Jones

Editorial DirectorRobyn B. Siesky

Editorial ManagerMary Beth Wakefi eld

Marketing ManagerDavid Mayhew

Production ManagerTim Tate

Vice President and Executive Group PublisherRichard Swadley

Vice President and Executive PublisherBarry Pruett

Associate PublisherJim Minatel

Project Coordinator, CoverLindsay Stanford

CompositorCraig Johnson, Happenstance Type-O-Rama

ProofreaderKathryn Duggan

IndexerJ & J Indexing

Cover Image© Photographer’s Choice/Punchstock

25937ffirs.indd xi25937ffirs.indd xi 9/22/09 11:23:54 AM9/22/09 11:23:54 AM

Page 14: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

25937ffirs.indd xii25937ffirs.indd xii 9/22/09 11:23:54 AM9/22/09 11:23:54 AM

Page 15: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

Acknowledgments

First, a big thank you to my partner Beci, who, now that the book’s fi nished, will get to see me for more than 10 minutes a week.

I’d also like to say a very big thank you to Maureen Spears, who has worked very effi ciently on getting this book into print.

Thanks also to Jim Minatel for making this book happen.

Many thanks to everyone who’s supported and encouraged me over my many years of writing books. Your help will always be remembered.

Finally, pats and treats to my German Shepherd Dog, Katie, who does an excellent job of warding off disturbances from door-to-door salespeople.

— Paul Wilton

First and foremost, a huge thank you to my wife for putting up with my late nights.

Just as huge thanks go to the people at Wiley Publishing: Jim Minatel and Scott Meyers for making this happen; Maureen Spears who was absolutely wonderful to work with in getting this book into its fi nal, printed form; and David M. Karr for keeping me honest.

Lastly, thank you Nicholas C. Zakas, author of Professional JavaScript, 2nd Edition (Wiley 2009) and co-author of Professional Ajax, 2nd Edition (Wiley 2007), for getting me into this business.

— Jeremy McPeak

25937ffirs.indd xiii25937ffirs.indd xiii 9/22/09 11:23:55 AM9/22/09 11:23:55 AM

Page 16: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

25937ffirs.indd xiv25937ffirs.indd xiv 9/22/09 11:23:55 AM9/22/09 11:23:55 AM

Page 17: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

Contents

Introduction xxv

Chapter 1: Introduction to JavaScript and the Web 1

Introduction to JavaScript 1What Is JavaScript? 1JavaScript and the Web 2Why Choose JavaScript? 4What Can JavaScript Do for Me? 4Tools Needed to Create JavaScript Web Applications 5

Where Do My Scripts Go? 7Linking to an External JavaScript File 7Advantages of Using an External File 8

Your First Simple JavaScript Programs 8A Brief Look at Browsers and Compatibility Problems 15Summary 16

Chapter 2: Data Types and Variables 17

Types of Data in JavaScript 17Numerical Data 18Text Data 18Boolean Data 20

Variables — Storing Data in Memory 20Creating Variables and Giving Them Values 21Assigning Variables with the Value of Other Variables 24

Using Data — Calculations and Basic String Manipulation 26Numerical Calculations 26Operator Precedence 30Basic String Operations 34Mixing Numbers and Strings 35

Data Type Conversion 37Dealing with Strings That Won’t Convert 40

Arrays 40A Multi-Dimensional Array 45

Summary 49Exercise Questions 50

25937ftoc.indd xv25937ftoc.indd xv 9/22/09 11:02:27 AM9/22/09 11:02:27 AM

Page 18: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

xvi

Contents

Chapter 3: Decisions, Loops, and Functions 51

Decision Making — The if and switch Statements 51Comparison Operators 52The if Statement 54Logical Operators 58Multiple Conditions Inside an if Statement 60else and else if 64Comparing Strings 66The switch Statement 67

Looping — The for and while Statements 71The for Loop 71The for...in Loop 74The while Loop 75The do...while loop 77The break and continue Statements 78

Functions 79Creating Your Own Functions 79Variable Scope and Lifetime 83

Summary 84Exercise Questions 86

Chapter 4: Common Mistakes, Debugging, and Error Handling 87

D’oh! I Can’t Believe I Just Did That: Some Common Mistakes 87Undefi ned Variables 88Case Sensitivity 89Incorrect Number of Closing Braces 90Incorrect Number of Closing Parentheses 90Using Equals (=) Rather than Is Equal To (==) 91Using a Method as a Property and Vice Versa 91Missing Plus Signs During Concatenation 92

Error Handling 93Preventing Errors 93The try … catch Statements 94

Debugging 103Debugging in Firefox with Firebug 104Debugging in Internet Explorer 116Debugging in Safari 123Using Dragonfl y: Opera’s Development Tools 127

Summary 131Exercise Questions 131

25937ftoc.indd xvi25937ftoc.indd xvi 9/22/09 11:02:27 AM9/22/09 11:02:27 AM

Page 19: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

xvii

Contents

Chapter 5: JavaScript — An Object-Based Language 133

Object-Based Programming 133What Are Objects? 134Objects in JavaScript 134Using JavaScript Objects 135Primitives and Objects 138

JavaScript’s Native Object Types 139String Objects 139Array Objects 150New Array Methods 156The Math Object 160Number Object 167The toFixed() Method 167Date Objects 168

Creating New Types of Objects (Reference Types) 177Summary 187Exercise Questions 188

Chapter 6: Programming the Browser 189

Introduction to the Browser’s Objects 190The window Object 191The history Object 193The location Object 194The navigator Object 194The screen Object 195The document Object 195Using the document Object 195The images Collection 198The links Collection 199

Responding to the User’s Actions with Events 199What Are Events? 200Connecting Code to Events 200Determining the User’s Browser 206

Summary 215Exercise Questions 217

Chapter 7: HTML Forms: Interacting with the User 219

HTML Forms 219Other Form Object Properties and Methods 222

HTML Elements in Forms 223

25937ftoc.indd xvii25937ftoc.indd xvii 9/22/09 11:02:27 AM9/22/09 11:02:27 AM

Page 20: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

xviii

Contents

Common Properties and Methods 224Button Elements 226Text Elements 229The textarea Element 236Check Boxes and Radio Buttons 239Selection Boxes 247

Summary 260Exercise Questions 262

Chapter 8: Windows and Frames 263

Frames and the window Object 264Coding Between Frames 268Code Access Between Frames 273

Opening New Windows 284Opening a New Browser Window 284Scripting Between Windows 292Moving and Resizing Windows 297

Security 298Summary 298Exercise Questions 299

Chapter 9: String Manipulation 301

Additional String Methods 302The split() Method 302The replace() Method 305The search() Method 305The match() Method 306

Regular Expressions 306Simple Regular Expressions 307Regular Expressions: Special Characters 315Covering All Eventualities 323Grouping Regular Expressions 323Reusing Groups of Characters 325

The String Object — split(), replace(), search(), and match() Methods 327The split() Method 327The replace() Method 329The search() Method 332The match() Method 333

25937ftoc.indd xviii25937ftoc.indd xviii 9/22/09 11:02:27 AM9/22/09 11:02:27 AM

Page 21: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

xix

Contents

Using the RegExp Object’s Constructor 335Telephone Number Validation 339Validating a Postal Code 341Validating an E-mail Address 342Validating a Domain Name 342

Summary 345Exercise Questions 345

Chapter 10: Date, Time, and Timers 347

World Time 348Setting and Getting a Date Object’s UTC Date and Time 351

Timers in a Web Page 358One-Shot Timer 359Setting a Timer that Fires at Regular Intervals 363

Summary 364Exercise Questions 365

Chapter 11: Storing Information: Cookies 367

Baking Your First Cookie 367A Fresh-Baked Cookie 368The Cookie String 374

Creating a Cookie 377Getting a Cookie’s Value 381Cookie Limitations 386

A User May Disable Cookies 386Number and Information Limitation 387

Cookie Security and IE6+ 388Summary 389Exercise Questions 389

Chapter 12: Dynamic HTML and the W3C Document Object Model 391

The Web Standards 392HTML 394XML 394XHTML 395ECMAScript 396

25937ftoc.indd xix25937ftoc.indd xix 9/22/09 11:02:27 AM9/22/09 11:02:27 AM

Page 22: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

xx

Contents

The Document Object Model 397The DOM Standard 397Differences Between the DOM and the BOM 399Representing the HTML Document as a Tree Structure 399The Core DOM Objects 402DOM Objects and Their Properties and Methods 404

Manipulating the DOM 422Accessing Elements 422Changing Appearances 422Positioning and Moving Content 429Example: Animated Advertisement 432DOM Event Handling 437Event Handling in Internet Explorer 443

Writing Cross-Browser DHTML 447JavaScript and XML 453

Manipulating XML with JavaScript 454Retrieving an XML File in IE 454Retrieving an XML File in Firefox and Opera 457Retrieving an XML File (Cross-Browser) 458Example: Displaying a Daily Message 459

Summary 467Exercise Questions 468

Chapter 13: Using ActiveX and Plug-Ins with JavaScript 469

Checking for and Embedding Plug-ins (Non-IE Browsers) 470Adding a Plug-in to the Page 470Checking for and Installing Plug-ins 472

Checking for and Embedding ActiveX Controls on Internet Explorer 474Adding an ActiveX Control to the Page 475Installing an ActiveX Control 478

Using Plug-ins and ActiveX Controls 480Determining Plug-in/ActiveX Control Availability 481Finishing Up 482Testing the Disabling of the Form 484Potential Problems 485

Summary 488Exercise Question 489

25937ftoc.indd xx25937ftoc.indd xx 9/22/09 11:02:27 AM9/22/09 11:02:27 AM

Page 23: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

xxi

Contents

Chapter 14: Ajax 491

What Is Ajax? 491What Can It Do? 492Browser Support 493

Using the XMLHttpRequest Object 494Cross-Browser Issues 494Using the XMLHttpRequest Object 497Asynchronous Requests 499

Creating a Simple Ajax Module 500Planning the HttpRequest Module 500The HttpRequest Constructor 501Creating the Methods 502The Full Code 503

Validating Form Fields with Ajax 505Requesting Information 506The Received Data 506Before You Begin 506

Things to Watch Out For 515Security Issues 515Usability Concerns 516

Summary 525Exercise Questions 525

Chapter 15: JavaScript Frameworks 527

Picking a Framework to Work With 527Getting Started 528

Installing the Frameworks 529Testing the Frameworks 530

Digging Deeper Into jQuery 537Selecting Elements 537Changing Style 539Creating, Appending, and Removing Elements 541The jQuery Event Model and Handling Events 543Rewriting the DHTML Toolbar with jQuery 545Using jQuery for Ajax 550

Diving into Prototype 558Retrieving Elements 558Manipulating Style 560Creating, Inserting, and Removing Elements 561Using Events 562Rewriting the DHTML Toolbar with Prototype 563Using Ajax Support 567

25937ftoc.indd xxi25937ftoc.indd xxi 9/22/09 11:02:27 AM9/22/09 11:02:27 AM

Page 24: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

xxii

Contents

Delving into MooTools 575Finding Elements 575Altering Style 576Creating, Inserting, and Removing Elements 577Using and Handling Events 578Rewriting the DHTML Toolbar with MooTools 579Ajax Support in MooTools 584

Summary 590Exercise Questions 590

Appendix A: Answers to Exercises 591

Chapter 2 591Chapter 3 593Chapter 4 597Chapter 5 600Chapter 6 604Chapter 7 610Chapter 8 616Chapter 9 624Chapter 10 628Chapter 11 631Chapter 12 634Chapter 13 641Chapter 14 643Chapter 15 653

Appendix B: JavaScript Core Reference 665

Browser Reference 665Reserved Words 666

Other Identifi ers to Avoid 667JavaScript Operators 668

Assignment Operators 668Comparison Operators 669Arithmetic Operators 670Bitwise Operators 671Bitwise Shift Operators 672Logical Operators 672Miscellaneous Operators 673Operator Precedence 674

25937ftoc.indd xxii25937ftoc.indd xxii 9/22/09 11:02:27 AM9/22/09 11:02:27 AM

Page 25: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

xxiii

Contents

JavaScript Statements 675Block 675Conditional 676Declarations 676Loop 676Execution Control Statements 677Exception Handling Statements 677Other Statements 678

Top-Level Properties and Functions 678JavaScript and Jscript Core Objects 679

ActiveXObject 679Array 680Boolean 682Date 682Function 685Math 687Number 688Object 689RegExp 690String 693

Appendix C: W3C DOM Reference 697

DOM Core Objects 697Low-Level DOM Objects 697High-Level DOM Objects 700

HTML DOM Objects 705Miscellaneous Objects: The HTML Collection 705HTML Document Objects: The HTML Document 706HTML Element Objects 707HTMLButtonElement 709

DOM Event Model and Objects 719EventTarget 719Event 720MouseEvent 720

Miscellaneous Events 722

Appendix D: Latin-1 Character Set 725

Index 733

25937ftoc.indd xxiii25937ftoc.indd xxiii 9/22/09 11:02:28 AM9/22/09 11:02:28 AM

Page 26: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

25937flast.indd xxiv25937flast.indd xxiv 9/22/09 11:02:45 AM9/22/09 11:02:45 AM

Page 27: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

Introduction

JavaScript is a scripting language that enables you to enhance static web applications by providing dynamic, personalized, and interactive content. This improves the experience of visitors to your site and makes it more likely that they will visit again. You must have seen the fl ashy drop-down menus, moving text, and changing content that are now widespread on web sites — they are enabled through JavaScript. Supported by all the major browsers, JavaScript is the language of choice on the Web. It can even be used outside web applications — to automate administrative tasks, for example.

This book aims to teach you all you need to know to start experimenting with JavaScript: what it is, how it works, and what you can do with it. Starting from the basic syntax, you’ll move on to learn how to create powerful web applications. Don’t worry if you’ve never programmed before — this book will teach you all you need to know, step by step. You’ll fi nd that JavaScript can be a great introduction to the world of programming: with the knowledge and understanding that you’ll gain from this book, you’ll be able to move on to learn newer and more advanced technologies in the world of computing.

Whom This Book Is ForTo get the most out of this book, you’ll need to have an understanding of HTML and how to create a static web page. You don’t need to have any programming experience.

This book will also suit you if you have some programming experience already and would like to turn your hand to web programming. You will know a fair amount about computing concepts, but maybe not as much about web technologies.

Alternatively, you may have a design background and know relatively little about the web and computing concepts. For you, JavaScript will be a cheap and relatively easy introduction to the world of program-ming and web application development.

Whoever you are, we hope that this book lives up to your expectations.

What This Book CoversYou’ll begin by looking at exactly what JavaScript is, and taking your fi rst steps with the underlying language and syntax. You’ll learn all the fundamental programming concepts, including data and data types, and structuring your code to make decisions in your programs or to loop over the same piece of code many times.

Once you’re comfortable with the basics, you’ll move on to one of the key ideas in JavaScript — the object. You’ll learn how to take advantage of the objects that are native to the JavaScript language, such as dates and strings, and fi nd out how these objects enable you to manage complex data and simplify

25937flast.indd xxv25937flast.indd xxv 9/22/09 11:02:45 AM9/22/09 11:02:45 AM

Page 28: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

Introduction

xxvi

your programs. Next, you’ll see how you can use JavaScript to manipulate objects made available to you in the browser, such as forms, windows, and other controls. Using this knowledge, you can start to cre-ate truly professional-looking applications that enable you to interact with the user.

Long pieces of code are very hard to get right every time — even for the experienced programmer — and JavaScript code is no exception. You look at common syntax and logical errors, how you can spot them, and how to use the JavaScript debuggers for Firefox, Internet Explorer, Safari/Chrome, and Opera to aid you with this task. Also, you need to examine how to handle the errors that slip through the net, and ensure that these do not detract from the experience of the end user of your application.

From here, you’ll move on to more advanced topics, such as using cookies and jazzing up your web pages with dynamic HTML and XML. Finally, you’ll be looking at a relatively new and exciting technology: Ajax. This allows your JavaScript in a HTML page to communicate directly with a server, and useful for, say, looking up information on a database sitting on your server. If you have the Google toolbar you’ll have seen something like this in action already. When you type a search word in the Google toolbar, it comes up with suggestions, which it gets via the Google search database.

Finally, you’ll explore some of the time saving JavaScript frameworks such as jQuery, Prototype, and MooTools and seeing how they work and how they can help you create sophisticated JavaScript powered applications.

All the new concepts introduced in this book will be illustrated with practical examples, which enable you to experiment with JavaScript and build on the theory that you have just learned.

You’ll fi nd four appendixes at the end of the book. Appendix A provides solutions to the exercises included at the end of most chapters throughout the book. The remaining appendixes contain the reference material that your authors hope you fi nd useful and informational. Appendix B contains the JavaScript language’s core reference. Appendix C contains a complete W3C DOM Core reference — as well as information on the HTML DOM and DOM Level 2 Event model. Appendix D contains the decimal and hexadecimal character codes for the Latin-1 character set.

What You Need to Use This BookBecause JavaScript is a text-based technology, all you really need to create documents containing JavaScript is Notepad (or your equivalent text editor).

Also, in order to try out the code in this book, you will need a web browser that supports a modern version of JavaScript. Ideally, this means Internet Explorer 8 or later and Firefox 3 or later. The book has been extensively tested with these two browsers. However, the code should work in most modern web browsers, although some of the code in later chapters, where you examine dynamic HTML and script-ing the DOM, is specifi c to particular browsers; but the majority of the code presented is cross-browser. Where there are exceptions, they will be clearly noted.

ConventionsTo help you get the most from the text and keep track of what’s happening, we’ve used a number of conventions throughout the book.

25937flast.indd xxvi25937flast.indd xxvi 9/22/09 11:02:45 AM9/22/09 11:02:45 AM

Page 29: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

Introduction

xxvii

Try It OutThe Try It Out is an exercise you should work through, following the text in the book.

1. It usually consists of a set of steps.

2. Each step has a number.

3. Follow the steps with your copy of the database.

As you work through each Try It Out, the code you’ve typed will be explained in detail.

Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.

Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.

As for styles in the text:

We ❑ highlight in italic type new terms and important words when we introduce them.

❑ We show keyboard strokes like this: Ctrl+A.

We show fi le names, URLs, and code within the text like so: ❑ persistence.properties.

We present code in two different ways: ❑

Important code in code examples is highlighted with a gray background.The gray highlighting is not used for code that’s less important in the present context, or that has been shown before.

Source CodeAs you work through the examples in this book, you may choose either to type in all the code manually or to use the source-code fi les that accompany the book. All of the source code used in this book is avail-able for download at www.wrox.com. Once at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.

Because many books have similar titles, you may fi nd it easiest to search by ISBN; this book’s ISBN is 978-0-470-52593-7.

Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

25937flast.indd xxvii25937flast.indd xxvii 9/22/09 11:02:45 AM9/22/09 11:02:45 AM

Page 30: JavaScript - download.e-bookshelf.de · Updated and revised, this book offers a hands-on look at designing standards-based, large-scale, professional-level CSS web sites. Understand

Introduction

xxviii

ErrataWe make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you fi nd an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration, and at the same time you will be helping us provide even higher-quality information.

To fi nd the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that have been submitted for this book and posted by Wrox editors. A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fi x the problem in subsequent editions of the book.

p2p.wrox.comFor author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system on which you can post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At http://p2p.wrox.com you will fi nd a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

1. Go to p2p.wrox.com and click the Register link.

2. Read the terms of use and click Agree.

3. Complete the required information to join as well as any optional information you wish to provide, and click Submit.

4. You will receive an e-mail with information describing how to verify your account and complete the joining process.

You can read messages in the forums without joining P2P, but in order to post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post. You can read mes-sages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to ques-tions about how the forum software works, as well as many common questions specifi c to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

25937flast.indd xxviii25937flast.indd xxviii 9/22/09 11:02:45 AM9/22/09 11:02:45 AM