30
Beginning JavaScript Second Edition Paul Wilton

C1.jpg Beginning JavaScript · With love to Beci, my very special lady. Many thanks to Catherine who for many years supported me and ensured my sanity chip remained plugged in—she’s

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

  • Beginning JavaScript™

    Second Edition

    Paul Wilton

    555871 FM.qxd 4/5/04 3:43 PM Page iii

    C1.jpg

  • 555871 FM.qxd 4/5/04 3:43 PM Page ii

  • Beginning JavaScript™

    555871 FM.qxd 4/5/04 3:43 PM Page i

  • 555871 FM.qxd 4/5/04 3:43 PM Page ii

  • Beginning JavaScript™

    Second Edition

    Paul Wilton

    555871 FM.qxd 4/5/04 3:43 PM Page iii

  • Beginning JavaScript™, Second EditionPublished byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

    Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana All rights reserved.

    Published simultaneously in Canada

    No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any formor by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except aspermitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the priorwritten permission of the Publisher, or authorization through payment of the appropriate per-copy feeto the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax(978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department,Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317)572-4447, E-mail: [email protected].

    LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHORMAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY ORCOMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALLWARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTIC-ULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMO-TIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BESUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THATTHE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PRO-FESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF ACOMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NORTHE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT ANORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR APOTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR ORTHE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAYPROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARETHAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEAREDBETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.

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

    Trademarks: Wiley, Wrox, the Wrox logo, and related trade dress are trademarks or registered trade-marks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, andmay not be used without written permission. All other trademarks are the property of their respectiveowners. 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 printmay not be available in electronic books.

    Library of Congress Control Number: 2004103175

    ISBN: 0-7645-5587-1

    Printed in the United States of America

    10 9 8 7 6 5 4 3 2 1

    555871 FM.qxd 4/5/04 3:43 PM Page iv

    www.wiley.com

  • With love to Beci, my very special lady. Many thanks to Catherine who for many years supported me and ensuredmy sanity chip remained plugged in—she’s very much missed. Also a big thank you to all in the Wrox team, espe-cially Mark Enochs and Jim Minatel. Their support, dedication, and hard work helped create this book and turnedmy jumble of words in a language closely resembling English into something truly professional. Finally a big patfor Katie, my loyal dog, for her ability to make me smile, getting me away from the computer with her incessantpestering for walks and her ability to ward off door-to-door salespeople.

    555871 FM.qxd 4/5/04 3:43 PM Page v

  • CreditsVice President & Executive Group PublisherRichard Swadley

    Vice President and Executive PublisherBob Ipsen

    Vice President and PublisherJoseph B. Wikert

    Executive Editorial DirectorMary Bednarek

    Senior Acquisitions EditorJim Minatel

    Editorial ManagerMary Beth Wakefield

    Development EditorMark Enochs

    Senior Production ManagerAngela Smith

    Copy EditorKim Cofer

    Project CoordinatorBarbara Moore

    Graphics and Production SpecialistsBeth BrooksCarrie FosterLauren GoddardKristin McMullan

    Quality Control TechniciansLaura AlbertJohn GreenoughAndy HollandbeckAngel PerezSusan Moritz

    Proofreading and IndexingTechbooks Production Services

    About Paul WiltonAfter an initial start as a Visual Basic applications programmer at the Ministry of Defense in the U.K.,Paul found himself pulled into the Net. Having joined an Internet development company, he spent thelast 5 years helping create Internet solutions and is currently working on an e-commerce website for amajor British bank.

    Paul’s main skills are in developing web front ends using DHTML, JavaScript, VBScript, and VisualBasic, and back-end solutions with ASP, Visual Basic, and SQL Server. Currently, in between web development projects, he is learning Palm OS programming.

    555871 FM.qxd 4/5/04 3:43 PM Page vi

  • Contents

    Introduction xix

    Chapter 1: Introduction to JavaScript and the Web 1

    Introduction to JavaScript 1What Is JavaScript? 1JavaScript and the Web 2Why Choose JavaScript? 3What Can JavaScript Do for Me? 4

    Tools Needed to Create JavaScript Web Applications 4The Tag and Your First Simple JavaScript Program 5A Brief Look at Browsers and Compatibility Problems 12Introducing the Trivia Quiz 14

    Ideas Behind the Coding of the Trivia Quiz 16What Functionality Do We Add and Where? 17

    Summary 18

    Chapter 2: Data Types and Variables 19

    Types of Data in JavaScript 19Numerical Data 20Text Data 20Boolean Data 22

    Variables—Storing Data in Memory 22Declaring Variables and Giving Them Values 24Assigning Variables with the Value of Other Variables 26

    Setting Up Your Browser for Errors 28Displaying Errors in Netscape Navigator 29Displaying Errors in Internet Explorer 30What Happens when We Get an Error 31

    Using Data—Calculations and Basic String Manipulation 35Numerical Calculations 35Operator Precedence 39Basic String Operations 42Mixing Numbers and Strings 43

    555871 FM.qxd 4/5/04 3:43 PM Page vii

  • viii

    Contents

    Data Type Conversion 45Dealing with Strings That Won’t Convert 48

    Arrays 49A Multi-Dimensional Array 54

    The Trivia Quiz—Storing the Questions Using Arrays 58Summary 61Exercise Questions 62

    Question 1 62Question 2 62

    Chapter 3: Decisions, Loops, and Functions 63

    Decision Making—The if and switch Statements 64Comparison Operators 64The if Statement 66Logical Operators 71Multiple Conditions Inside an if Statement 73else and else if 77Comparing Strings 79The switch Statement 80

    Looping—The for and while Statements 84The for Loop 85The for...in Loop 88The while Loop 90The do...while loop 90The break and continue Statements 91

    Functions 92Creating Your Own Functions 93Variable Scope and Lifetime 97

    The Trivia Quiz—Building One of the Basic Functions 97Summary 100Exercise Questions 102

    Question 1 102Question 2 103Question 3 103Question 4 103

    Chapter 4: JavaScript—An Object-Based Language 105

    Object-Based Programming 105A Brief Introduction to Objects 105Objects in JavaScript 106

    555871 FM.qxd 4/5/04 3:43 PM Page viii

  • ix

    Contents

    Using JavaScript Objects 107Primitives and Objects 110

    The JavaScript Native Objects 111String Objects 111The Math Object 122Number Object 128Array Objects 130Date Objects 136JavaScript Classes 145

    Summary 155Exercise Questions 156

    Question 1 156Question 2 156Question 3 156

    Chapter 5: Programming the Browser 157

    Introduction to the Browser Objects 158The window Object—Our Window onto the Page 159The history Object 161The location Object 161The navigator Object 162The screen Object 163The document Object—The Page Itself 163Connecting Code to Web Page Events 167Browser Version Checking Examples 173

    Summary 183Exercise Questions 185

    Question 1 185Question 2 185Question 3 185

    Chapter 6: HTML Forms—Interacting with the User 187

    HTML Forms 188Other Form Object Properties and Methods 190

    HTML Elements in Forms 191Common Properties and Methods 193Button Form Elements 195Text Elements 198textarea Element 205Checkboxes and Radio Buttons 208The select Elements 215

    555871 FM.qxd 4/5/04 3:43 PM Page ix

  • x

    Contents

    The Trivia Quiz 228Creating the Form 228Creating the Answer Radio Buttons 229

    Summary 233Exercises 235

    Question 1 235Question2 235

    Chapter 7: Windows and Frames 237

    Frames and the window Object 238Coding between Frames 242Code Access between Frames 247

    Opening New Windows 257Opening Up a New Browser Window 257Scripting between Windows 265Moving and Resizing Windows 270

    Security 270Trivia Quiz 271

    Creating the New Trivia Quiz 272Summary 288Exercise Questions 289

    Question 1 289Question 2 289

    Chapter 8: String Manipulation 291

    Additional String Methods 292The split() Method 292The replace() Method 296The search() Method 296The match() Method 296

    Regular Expressions 297Simple Regular Expressions 298Regular Expressions: Special Characters 300Covering All Eventualities 308Grouping Regular Expressions 309

    The String Object—split(), replace(), search(), and match() Methods 312The split() Method 312The replace() Method 314The search() Method 318The match() Method 318

    555871 FM.qxd 4/5/04 3:43 PM Page x

  • xi

    Contents

    Using the RegExp Object’s Constructor 322The Trivia Quiz 323Summary 330Exercise Questions 330

    Question 1 331Question 2 331Question 3 331

    Chapter 9: Date, Time, and Timers 333

    World Time 334Setting and Getting a Date Object’s UTC Date and Time 339

    Timers in a Web Page 347One-Shot Timer 347Setting a Timer that Fires at Regular Intervals 352

    The Trivia Quiz 357Summary 363Exercise Questions 364

    Question 1 364Question 2 364

    Chapter 10: Common Mistakes, Debugging, and Error Handling 365

    I Can’t Believe I Just Did That: Some Common Mistakes 3651: Undefined Variables 3662: Case Sensitivity 3673: Incorrect Number of Closing Braces 3684: Missing + Signs When Concatenating 3685: Equals Rather than Is Equal to 3696: Incorrect Number of Closing Parentheses 3697: Using a Method as a Property and Vice Versa 370

    Microsoft Script Debugger 371Obtaining the Script Debugger 371Installing the Script Debugger 372Using the Script Debugger 374

    Netscape Debugging 391Netscape Navigator 7 Venkman Debugger 391The JavaScript Console 396

    Error Handling 400Preventing Errors 400The try...catch Statements 401

    Summary 411

    555871 FM.qxd 4/5/04 3:43 PM Page xi

  • xii

    Contents

    Exercise Questions 412Question 1 412Question 2 412

    Chapter 11: Storing Information: Cookies 415

    Baking Our First Cookie 415A Fresh Baked Cookie 416The Cookie String 424

    Creating a Cookie 427Getting a Cookie’s Value 431Cookie Limitations 437Cookie Security and IE6 438Summary 443Exercise Questions 444

    Question 1 444Question 2 444

    Chapter 12: Dynamic HTML in Early Browsers 445

    Style Sheets 446Adding a Touch of Style 447Positioning Elements 450Style Sheets and JavaScript 454

    Dynamic HTML in Internet Explorer 4.0+ 454Accessing Page Tags 454Changing Appearances 455Positioning and Moving Content 458Changing, Adding, and Deleting Existing Content 460DHTML Events and the IE event Object 470Dynamic Menus in IE 472

    Dynamic HTML in Netscape Navigator 4.x 489The Tag and Layer Object 489The NN event Object 498Dynamic Menus in NN 4.x 501

    Cross Browser IE 4.0+ and NN 4.x DHTML 514Small Changes within Pages 514Redirecting the Browser 518

    Summary 519Exercise Questions 520

    Question 1 520Question 2 520

    555871 FM.qxd 4/5/04 3:43 PM Page xii

  • xiii

    Contents

    Chapter 13: Dynamic HTML in Modern Browsers 521

    Why Do We Need Web Standards? 522The Web Standards 524

    HTML 524ECMAScript 524XML 525XHTML 526

    The Document Object Model 527The DOM Standard 528Differences Between the DOM and the BOM 529Representing the HTML Document as a Tree Structure 529The DOM Objects 533DOM Properties and Methods 535The DOM Event Model 552

    Writing Cross-Browser DHTML Using the DOM 557Animated Text Example 558Adding and Deleting Text Example 561Mouse Rollover Example 565Dynamic Menu Example 567

    Summary 580Exercise Questions 580

    Question 1 580Question 2 581

    Chapter 14: JavaScript and XML 583

    What Is XML Used for? 583The Basics of XML 584

    Creating an XML Document 584DTDs: Creating Well-Formed and Valid XML Documents 592Referencing the DTD from an XML File 596Rules of XML Syntax 598XML Data Elements 600

    Altering the Look of Our XML 602Style Sheets and XML 603eXtensible Style Language 609

    Manipulating XML with JavaScript 613Reading XML Documents with JavaScript 614Creating an Intelligent XML File Download Detector (IE Only) 616Manipulating the XML File 616Displaying a Daily Message 617

    Summary 624

    555871 FM.qxd 4/5/04 3:43 PM Page xiii

  • xiv

    Contents

    Exercise Questions 624Question 1 624Question 2 625

    Chapter 15: Using ActiveX and Plug-Ins with JavaScript 627

    Checking for and Embedding Plug-Ins on Netscape Navigator 628Adding a Plug-In to the Page 628Checking For and Installing Plug-Ins in Netscape 630

    Checking For and Embedding ActiveX Controls on Internet Explorer 634Adding an ActiveX Control to the Page 634Installing an ActiveX Control 637

    Using Plug-Ins and ActiveX Controls 638Testing Your No Plug-In or ActiveX Control Redirection Script 643Potential Problems 643

    Summary 646Exercise Question 647

    Question 1 647

    Chapter 16: Server-Side Scripting with ASP 649

    What Is Server-Side Scripting? 649Personal Web Server (IIS) 651

    Installing IIS on Windows 98 651Installing IIS on Windows XP 654Managing IIS under Windows XP 656

    Introduction to Active Server Pages 667Inserting Server-Side Script 668Differences between Server-Side and Client-Side Script 669Writing Server-Side Script 669

    ASP Objects 673Requests and Responses 673Request Object: Getting Information from the User 674Response Object: Sending Information to the Client 696Using the Server Object to Run Components 704Session Object: Keeping Track of Users 710Application Object 712

    Trivia Quiz Goes Server-Side 713Microsoft’s ASP.NET 718

    Summary 719Exercise Questions 720

    Question 1 720Question 2 720

    555871 FM.qxd 4/5/04 3:43 PM Page xiv

  • xv

    Contents

    Chapter 17: Databases 721

    A Brief Guide to Databases 722How Information Is Organized in Databases 722Creating a Database 724Database Design: Adding More Fields and Tables 727Relationships and Primary Keys 731Defining Relationships between Tables 736Structured Query Language 739

    Accessing Databases from a Web Page 746Making a Connection 747Returning Information from a Database 753Changing Information in a Database 761

    Trivia Quiz 770Trivia Quiz Database 770Creating the TriviaQuestions Database 770Changes to the Trivia Quiz Logic 777Changes to QuizPage.asp 778Changes to GlobalFunctions.htm 779Changes to NoteUserSelections.asp 781Asking a Question: Changing AskQuestion.htm 782Checking the Answer: CheckAnswer.asp 787Displaying a Summary of Results 791

    Summary 795Exercise Questions 796

    Question 1 796Question 2 796

    Appendix A: Exercise Solutions 797

    Chapter 2 797Question 1 797Question 2 798

    Chapter 3 799Question 1 799Question 2 800Question 3 801Question 4 802

    Chapter 4 803Question 1 803Question 2 804Question 3 805

    555871 FM.qxd 4/5/04 3:43 PM Page xv

  • xvi

    Contents

    Chapter 5 807Question 1 807Question 2 808Question 3 810

    Chapter 6 812Question 1 812Question 2 813

    Chapter 7 818Question 1 818Question 2 820

    Chapter 8 826Question 1 826Question 2 827Question 3 828

    Chapter 9 829Question 1 829Question 2 831

    Chapter 10 833Question 1 833Question 2 833

    Chapter 11 836Question 1 837Question 2 839

    Chapter 12 841Question 1 841Question 2 844

    Chapter 13 850Question 1 850Question 2 853

    Chapter 14 853Question 1 853Question 2 854

    Chapter 15 856Question 1 856

    Chapter 16 858Question 1 858Question 2 862

    Chapter 17 870Question 1 870Question 2 876

    555871 FM.qxd 4/5/04 3:43 PM Page xvi

  • xvii

    Contents

    Appendix B: JavaScript Core Reference 885

    Browser Reference 885Reserved Words 885

    Other Identifiers to Avoid 886JavaScript Operators 887

    Operator Precedence 892JavaScript Statements 893

    Block 893Conditional 893Declarations 894Loop 894Execution Control Statements 895Exception Handling Statements 896Object Manipulation Statements 896Conditional Compile Statements 896Predefined Conditional Compilation Variables 897Other Statements 898

    Top-Level Properties and Functions 898Top-Level Properties 898Top-Level Functions 899

    JavaScript Core Objects 900ActiveXObject 900Array 900Boolean 902Date 903Enumerator 906Function 906java 908JavaArray 908JavaClass 908JavaObject 909JavaPackage 909Math 909netscape 911Number 911Object 912Packages 913RegExp 913String 918sun 921VBArray 921

    555871 FM.qxd 4/5/04 3:43 PM Page xvii

  • xviii

    Contents

    Appendix C: JavaScript Client Reference 923

    Browser Support for JavaScript 923Operators 924Statements 924Events 924

    Mouse Events 924Keyboard Events 925HTML Control Events 925Window Events 925Other Events 926

    Top-Level Functions 926Objects 926

    The Anchor Object 926The Applet Object 927The Area Object 927The Button Object 927The Checkbox Object 928The document Object 929The event Object 931The FileUpload Object 932The Form Object 933The Frame Object 933The Hidden Object 934The history Object 934The IMG Object 935The Link Object 935The location Object 936The navigator Object 937The Option Object 938The Password Object 939The Radio Object 940The Reset Object 941The screen Object 941The Select Object 942The Submit Object 943The Text Object 944The Textarea Object 944The window Object 945

    Appendix D: Latin-1 Character Set 949

    Index 957

    555871 FM.qxd 4/5/04 3:43 PM Page xviii

  • xix

    Introduction

    JavaScript is a scripting language that enables you to enhance static web applications, by providingdynamic, personalized, and interactive content. This improves the experience of visitors to your site andmakes it more likely that they will visit again. You must have seen the flashy drop-down menus, movingtext, and changing content that is now widespread on websites—all of these are techniques enabledthrough JavaScript. Supported by all the major browsers, JavaScript is the language of choice on the web.JavaScript 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, howit works, and what you can do with it. Starting from the basic syntax, you’ll move on to learn how to cre-ate powerful web applications. Don’t worry if you’ve never programmed before—this book will teachyou all you need to know, step-by-step. You’ll find that JavaScript can be a great introduction into theworld of programming; with the knowledge and understanding that you’ll gain from this book, you’llbe able to move on to learn newer and more advanced technologies in the world of computing.

    Who This Book Is ForTo get the most out of this book, you’ll need to have an understanding of HTML and how to create astatic web page. You don’t need to have any programming experience; this book will teach you all youneed to know to incorporate JavaScript into your pages, so that you can create more dynamic and excit-ing web applications.

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

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

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

    What This Book CoversWe’ll begin by looking at exactly what JavaScript is and then take our first steps with the underlying language and syntax. You’ll learn all the fundamental programming concepts, including data and datatypes, and structuring your code to make decisions in your programs or to loop over the same piece ofcode many times.

    555871 FM.qxd 4/5/04 3:43 PM Page xix

  • xx

    Introduction

    Once you’re comfortable with the basics, we’ll move on to one of the key ideas of JavaScript—the object.You’ll learn how to take advantage of the objects that are native to the JavaScript language, such as Datesand Strings, and find out how these objects allow you to manage complex data and simplify your pro-grams. Next, you’ll see how we can use JavaScript to manipulate objects made available to us in thebrowser, such as forms, windows, and other controls. Using this knowledge, we can start to create trulyprofessional-looking applications that allow us to interact with the user.

    Long pieces of code are very hard to get right every time—even for the experienced programmer—andJavaScript code is no exception. We look at common syntax and logical errors, how we can spot them,and how to use the Microsoft Script Debugger to aid us with this task. Also, we need to examine how wehandle the errors that slip through the net, and ensure that these do not detract from the experience ofthe end user of our application.

    From here, we’ll move on to more advanced topics, such as using cookies, jazzing up our web pageswith Dynamic HTML, and introducing XML. Finally, we’ll move away from manipulation of data andcode on the client-side and discuss ASP, the environment that enables dynamic generation of web con-tent using server-side scripting and back-end databases.

    The appendices at the end of the book provide you with a comprehensive reference for the JavaScriptlanguage. They also include solutions to the exercises found at the end of each chapter.

    All the new concepts that are introduced in this book are illustrated with practical examples, whichallow you to experiment with JavaScript and build on the theory that you have just learned. Throughoutthe book, we’ll also be building up a more complex sample application—an online trivia quiz—whichwill allow you to see how JavaScript is used in action in a real-world situation.

    What You Need to Use This BookBecause JavaScript is a text-based technology, all you really need to create documents containingJavaScript 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 JavaScript 1.2or above, namely version 4 or above of Netscape Navigator or Internet Explorer. (See the table inChapter 1 that lists the versions of JavaScript that are supported in the different versions of NetscapeNavigator and Internet Explorer.) Later in the book we’ll also be looking at code specific to the latestbrowsers, and for this you’ll need Internet Explorer 6 and Netscape Navigator 7. Some of the code inlater chapters, where we examine Dynamic HTML and scripting of the DOM, is specific to particularbrowsers, but the majority of the code presented is cross-browser-compatible. Where there are excep-tions, they will be clearly noted.

    In Chapter 16, we introduce scripting on the server-side with JavaScript and Active Server Pages (ASP).You will need a web server to run the code examples in this and the subsequent chapter. We have usedMicrosoft’s free Internet Information Server, for which there is an installation guide included in Chapter16, but any other server that supports ASP is also OK.

    In Chapter 17, we use JavaScript to access a database. For demonstration purposes, the database we useis Microsoft Access 2000, so to run the code examples you will need this software on your machine. Thedatabase itself is available for download along with the rest of the code for this book.

    555871 FM.qxd 4/5/04 3:43 PM Page xx

  • xxi

    Introduction

    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.

    This background style is used for asides to the current discussion.

    The following styles are also used in the text:

    ❑ When we introduce important words, we highlight them in italics.

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

    ❑ We show file names and code within the text like so: persistence.properties.

    ❑ We present code in two different ways:

    In code examples, the code foreground style shows new, important, pertinent code.

    The code background style shows code that’s less important in the present context,or has been shown before.

    Source CodeAs you work through the examples in this book, you may choose either to type in all the code manuallyor to use the source code files that accompany the book. All of the source code used in this book is avail-able for download at http://www.wrox.com. At the site, simply locate the book’s title (either by usingthe Search box or by using one of the title lists), and click the Download Code link on the book’s detailpage to obtain all the source code for the book. Because many books have similar titles, you may find iteasiest to search by ISBN, which for this book is 0764555871. Once you download the code, just decom-press it with your favorite compression tool. Alternatively, you can go to the main Wrox code downloadpage at http://www.wrox.com/dynamic/books/download.aspx to see the code available for thisbook and all other Wrox books.

    ErrataWe make every effort to ensure that there are no errors in the text or in the code. However, no one is per-fect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or faultypiece of code, we would be very grateful for your feedback. By sending in errata, you may save anotherreader hours of frustration, and you will be helping us provide even higher quality information.

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

    555871 FM.qxd 4/5/04 3:43 PM Page xxi

  • xxii

    Introduction

    To find the errata page for this book, go to http://www.wrox.com and locate the title using the Searchbox 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 has been submitted for this book and posted by Wrox editors. A completebook 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 informationand, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editionsof the book.

    p2p.wrox.comFor author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based sys-tem for you to post messages relating to Wrox books and related technologies and interact with otherreaders and technology users. The forums offer a subscription feature to e-mail you topics of interest ofyour 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 find a number of different forums that will help you not only asyou read this book, but also as you develop your own applications. To join the forums, do the following:

    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 com-plete the joining process.

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

    Once you have joined, you can post new messages and respond to messages other users post. You canread messages at any time on the web. If you would like to have new messages from a particular forume-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, which answer ques-tions about how the forum software works as well as many common questions specific to P2P and Wroxbooks. To read the FAQs, click the FAQ link on any P2P page.

    555871 FM.qxd 4/5/04 3:43 PM Page xxii

  • 1Introduction to JavaScript

    and the Web

    In this introductory chapter, we’ll take a look at what JavaScript is, what it can do for you, andwhat you need to be able to use it. With these foundations in place, we will see throughout the restof the book how JavaScript can help you to create powerful web applications for your website.

    The easiest way to learn something is by actually doing it, so throughout the book we’ll be creat-ing a number of useful example programs using JavaScript. We start this process in this chapter, bythe end of which you will have created your first piece of JavaScript code.

    Additionally over the course of the book, we’ll develop a complete JavaScript web application: anonline trivia quiz. By seeing it develop, step-by-step, you’ll get a good understanding of how tocreate your own web applications. At the end of this chapter, we’ll look at the finished trivia quizand discuss the ideas behind its design.

    Introduction to JavaScriptIn this section, we’re going to take a brief look at what JavaScript is, where it came from, how itworks, and what sorts of useful things we can do with it.

    What Is JavaScript?Having bought this book you are probably already well aware that JavaScript is some sort of com-puter language, but what is a computer language? Put simply, a computer language is a series ofinstructions that instruct the computer to do something. That something can be a wide variety ofthings, including displaying text, moving an image, or asking the user for information. Normallythe instructions, or what is termed code, are processed from the top line downward. Processed sim-ply means that the computer looks at the code we’ve written, works out what action we wanttaken, and then takes that action. The actual act of processing the code is called running or execut-ing it.

    01 555871 Ch01.qxd 4/2/04 11:40 AM Page 1

  • Using natural English, let’s see what instructions, or code, we might write to make a cup of coffee.

    1. Put coffee in cup.2. Fill kettle with water.3. Put kettle on to boil.4. Has the kettle boiled? If so, then pour water into cup; otherwise, continue to wait.5. Drink coffee.

    We’d start running this code from the first line (instruction 1), and then continue to the next (instruction2), then the next, and so on until we came to the end. This is pretty much how most computer languageswork, JavaScript included. However, there are occasions when we might change the flow of execution,or even skip over some code, but we’ll see more of this in Chapter 3.

    JavaScript is an interpreted language, rather than a compiled language. What do we mean by the termsinterpreted and compiled?

    Well, to let you in on a secret, your computer doesn’t really understand JavaScript at all. It needs some-thing to interpret the JavaScript code and convert it into something that it understands; hence it is aninterpreted language. Computers only understand machine code, which is essentially a string of binarynumbers (that is, a string of zeros and ones). As the browser goes through the JavaScript, it passes it to aspecial program called an interpreter, which converts the JavaScript to the machine code your computerunderstands. It’s a bit like having a translator to translate English into Spanish, for example. The impor-tant point to note is that the conversion of the JavaScript happens at the time the code is run; it has to berepeated every time the code is run. JavaScript is not the only interpreted language; there are others,including VBScript.

    The alternative compiled language is one where the program code is converted to machine code before it’sactually run, and this conversion only has to be done once. The programmer uses a compiler to convertthe code that he wrote to machine code, and it is this machine code that is run by the program’s user.Compiled languages include Visual Basic and C++. Using a real-world analogy, it’s like having someonetranslate our English document into Spanish. Unless we change the document, we can use it withoutretranslation as much as we like.

    Perhaps this is a good point to dispel a widespread myth: JavaScript is not the script version of the Javalanguage. In fact, although they share the same name, that’s virtually all they do share. Particularly goodnews is that JavaScript is much, much easier to learn and use than Java. In fact, languages like JavaScriptare the easiest of all languages to learn but are still surprisingly powerful.

    JavaScript and the WebFor most of this book we’ll be looking at JavaScript code that runs inside a web page loaded into abrowser. All we need to create these web pages is a text editor, for example, Windows NotePad, and aweb browser, such as Netscape Navigator or Internet Explorer, with which we can view our pages.These browsers come equipped with JavaScript interpreters.

    In fact, the JavaScript language first became available in the web browser Netscape Navigator 2. Initially,it was called LiveScript. However, because Java was the hot technology of the time, Netscape decided

    2

    Chapter 1

    01 555871 Ch01.qxd 4/2/04 11:40 AM Page 2

  • that JavaScript sounded more exciting. Once JavaScript really took off, Microsoft decided to add theirown brand of JavaScript to Internet Explorer, which they named JScript. Since then, both Netscape andMicrosoft have released improved versions and included them in their latest browsers. Although thesedifferent brands and versions of JavaScript have much in common, there are enough differences to causeproblems if we’re not careful. Initially we’ll be creating code that’ll work with Netscape and Microsoftversion 4 and later browsers. Later chapters of the book look at features available only to Netscape 6+and IE 5.5+. We’ll look into the problems with different browsers and versions of JavaScript later in thischapter, and see how we deal with them.

    The majority of the web pages containing JavaScript that we will create in this book can be stored onyour hard drive and loaded directly into your browser from the hard drive itself, just as you’d load anynormal file (such as a text file). However, this is not how web pages are loaded when we browse web-sites on the Internet. The Internet is really just one great big network connecting computers together.Websites are a special service provided by particular computers on the Internet; the computers provid-ing this service are known as web servers.

    Basically the job of a web server is to hold lots of web pages on its hard drive. When a browser, usuallyon a different computer, requests a web page that is contained on that web server, the web server loads itfrom its own hard drive and then passes the page back to the requesting computer via a special commu-nications protocol called HyperText Transfer Protocol (HTTP). The computer running the web browser thatmakes the request is known as the client. Think of the client/server relationship as a bit like a customer/shopkeeper relationship. The customer goes into a shop and says, “Give me one of those.” The shop-keeper serves the customer by reaching for the item requested and passing it back to the customer. In aweb situation, the client machine running the web browser is like the customer and the web server get-ting the page requested is like the shopkeeper.

    When we type an address into the web browser, how does it know which web server to get the pagefrom? Well, just as shops have addresses, say, 45 Central Avenue, SomeTownsville, so do web servers.Web servers don’t have street names; instead they have Internet Protocol (IP) addresses, which uniquelyidentify them on the Internet. These consist of four sets of numbers, separated by dots; for example,127.0.0.1.

    If you’ve ever surfed the net, you’re probably wondering what on earth I’m talking about. Surely webservers have nice www.somewebsite.com names, not IP addresses? In fact, the www.somewebsite.comname is the “friendly” name for the actual IP address; it’s a whole lot easier for us humans to remember.On the Internet, the friendly name is converted to the actual IP address by computers called domain nameservers, something your Internet service provider will have set up for you.

    Toward the end of the book, we’ll go through the process of how to set up our own web server in a step-by-step guide. We’ll see that web servers are not just dumb machines that pass pages back to clients, butin fact they can do a bit of processing themselves using JavaScript. We’ll be looking at this later in thebook as well.

    Why Choose JavaScript?JavaScript is not the only scripting language; there are others such as VBScript and Perl. So whychoose JavaScript over the others?

    The main reason for choosing JavaScript is its widespread use and availability. Both of the most com-monly used browsers, Internet Explorer and Netscape Navigator, support JavaScript, as do some of the

    3

    Introduction to JavaScript and the Web

    01 555871 Ch01.qxd 4/2/04 11:40 AM Page 3

  • less commonly used browsers. So, basically we can assume that most people browsing our website willhave a version of JavaScript installed, though it is possible to use a browser’s options to disable it.

    Of the other scripting languages we mentioned, VBScript, which can be used for the same purposes asJavaScript, is only supported by Internet Explorer running on the Windows operating system, and Perlis not used at all in web browsers.

    JavaScript is also very versatile and not just limited to use within a web page. For example, it can beused in Windows to automate computer administration tasks and inside Adobe Acrobat.pdf files to con-trol the display of the page just as in web pages, although this is a more limited version of JavaScript.However, the question of which scripting language is the most powerful and useful has no real answer.Pretty much everything that can be accomplished in JavaScript can be done in VBScript, and vice versa.

    What Can JavaScript Do for Me?The most common uses of JavaScript are interacting with users, getting information from them, and vali-dating their actions. For example, say we want to put a drop-down menu on the page so that users canchoose where they want to go to on our website. The drop-down menu might be plain old HTML, but itneeds JavaScript behind it to actually do something with the user’s input. Other examples of usingJavaScript for interactions are given by forms, which are used for getting information from the user.Again these may be plain HTML, but we might want to check the validity of the information that theuser is entering. For example, if we had a form taking a user’s credit card details in preparation for theonline purchase of goods, we’d want to make sure they had actually filled in their credit card detailsbefore we sent them the goods. We might also want to check that the data being entered is of the correcttype, such as a number for their age rather than text.

    JavaScript can also be used for various “tricks.” One example is switching an image in a page for a dif-ferent one when the user rolls her mouse over it, something often seen in web page menus. Also, ifyou’ve ever seen scrolling messages in the browser’s status bar (usually at the bottom of the browserwindow) or inside the page itself and wondered how they manage that, this is another JavaScript trickthat we’ll demonstrate later in the book. We’ll also see how to create expanding menus that display a listof choices when a user rolls his or her mouse over them, another commonly seen JavaScript-driven trick.

    Tricks are OK up to a point, but even more useful are small applications that provide a real service. Forexample, a mortgage seller’s website that has a JavaScript-driven mortgage calculator, or a websiteabout financial planning that includes a calculator that works out your tax bill for you. With a littleinventiveness you’ll be amazed at what can be achieved.

    Tools Needed to Create JavaScriptWeb Applications

    All that you need to get started with creating JavaScript code for web applications is a simple text editor,such as Windows NotePad, or one of the many slightly more advanced text editors that provide linenumbering, search and replace, and so on. An alternative is a proper HTML editor; you’ll need one thatallows you to edit the HTML source code, because that’s where you need to add your JavaScript. A num-ber of very good tools specifically aimed at developing web-based applications, such as Macromedia’s

    4

    Chapter 1

    01 555871 Ch01.qxd 4/2/04 11:40 AM Page 4

  • excellent Dreamweaver MX, are also available. However, in this book we’ll be concentrating onJavaScript, rather than any specific development tool. When it comes to learning the basics, it’s oftenbest to write the code by hand rather than relying on a tool to do it for you. This helps you to under-stand the fundamentals of the language before you attempt the more advanced logic that is beyond atool’s capability. Once you have a good understanding of the basics, you can use tools as timesavers sothat you can spend more time on the more advanced and more interesting coding.

    You’ll also need a browser to view your web pages in. It’s best to develop your JavaScript code on thesort of browsers you expect visitors to use to access your website. We’ll see later in the chapter that thereare different versions of JavaScript, each supported by different versions of the web browsers. Each ofthese JavaScript versions, while having a common core, also contains various extensions to the language.All the examples that we give in this book have been tested on Netscape Navigator versions 4.0, 4.7, 6,and 7, and Internet Explorer versions 4.0 to 6.0. Wherever a piece of code does not work on any of thesebrowsers, a note to this effect has been made in the text. (In case you’re wondering, Netscape Navigator5 never made it out on general release to the public.)

    Even if your browser supports JavaScript, it is possible to disable this functionality in the browser. So,before we start on our first JavaScript examples in the next section, you should check whether JavaScriptis enabled in your browser.

    To do this in Netscape Navigator, choose Preferences from the Edit menu on the browser. In the windowthat appears, click the Advanced tab or item from the list. In Netscape 7 you need to click on Scripts andplug-ins, and check that the checkbox beside Enable JavaScript for Navigator is checked. If not, thencheck it. You can also change what JavaScript code is permitted to do; for example, you can modify thecode to permit JavaScript to open new browser windows.

    It is harder to turn off scripting in Internet Explorer. Choose Internet Options from the Tools menu onthe browser, click the Security tab, and check whether the Internet or Local intranet options have customsecurity settings. If either of them do, click the Custom Level button, and scroll down to the Scriptingsection. Check that Active Scripting is set to Enable.

    A final point to note is how to open our code examples in your browser. For most of the book, you sim-ply need to open the file from where it is stored on your hard drive. You can do this in a number ofways. One way in Internet Explorer is to choose Open from the File menu, and click the Browse buttonto browse to where you stored the code. Similarly, in Netscape Navigator choose Open Page from theFile menu, and click the Choose File button; in Netscape Navigator 6, choose Open File from the Filemenu.

    The Tag and Your FirstSimple JavaScript Program

    We’ve discussed the subject of JavaScript for long enough; now let’s look at how we put it into our webpage. In this section, we’ll write our first piece of JavaScript code.

    Inserting JavaScript in a web page is much like inserting any other HTML content; we use tags to markthe start and end of our script code. The tag we use to do this is the tag. This tells the browserthat the following chunk of text, bounded by the closing tag, is not HTML to be displayed,

    5

    Introduction to JavaScript and the Web

    01 555871 Ch01.qxd 4/2/04 11:40 AM Page 5

  • but rather script code to be processed. We call the chunk of code surrounded by the and tags a script block.

    Basically when the browser spots tags, instead of trying to display the contained text to theuser, it uses the browser’s built-in JavaScript interpreter to run the code’s instructions. Of course,the code might give instructions about changes to the way the page is displayed or what is shown in the page, but the text of the code itself is never shown to the user.

    We can put the tags inside the header (between the and tags), or inside thebody (between the and tags) of the HTML page. However, although we can put themoutside these areas, for example, before the tag or after the tag, this is not permitted inthe web standards and so is considered bad practice.

    The tag has a number of attributes, but the most important one for us are the language andtype attributes. As we saw earlier, JavaScript is not the only scripting language available, and differentscripting languages need to be processed in different ways. We need to tell the browser which scriptinglanguage to expect so that it knows how to process it. There are no prizes for guessing that the lan-guage attribute, when using JavaScript, takes the value JavaScript. So, our opening script tag willlook like this:

    Including the language attribute is good practice, but within a web page it can be left off. Browsers suchas Internet Explorer (IE) and Netscape Navigator (NN) default to a script language of JavaScript. Thismeans that if the browser encounters a tag with no language attribute set, it assumes that thescript block is written in JavaScript. However, it is good practice to always include the languageattribute.

    In some situations JavaScript is not the default language, such as when script is run server-side (seeChapter 16), so we need to specify the language and sometimes the version of JavaScript that our webpage requires. However, when not specifying the language attribute will cause problems, I’ll be sure towarn you.

    However, the web standards have depreciated the requirements for the language attribute; this meansthe final aim is for its removal. In its place we have the type attribute, and this is made mandatory bythe web standards, although most current browsers will let us get away without including it. In the caseof script, we need to specify that the type is text/JavaScript, as follows:

    However, older browsers do not support the type attribute, so for compatibility it’s best to include both,as shown here:

    Also note that we can’t currently specify the JavaScript version with the type attribute, only with thelanguage attribute.

    OK, let’s take a look at our first page containing JavaScript code.

    6

    Chapter 1

    01 555871 Ch01.qxd 4/2/04 11:40 AM Page 6