I Getting Started with JavaScript1 An Overview of JavaScript 11 2 Creating Your First Scripts 17 II Programming Fundamentals 3 Understanding Variables 39 4 Working with Functions 51 5 Bu
Trang 1I Getting Started with JavaScript
1 An Overview of JavaScript 11
2 Creating Your First Scripts 17
II Programming Fundamentals
3 Understanding Variables 39
4 Working with Functions 51
5 Building JavaScript Expressions 71
6 Controlling Your Code I: Testing 101
7 Controlling Your Code II: Looping 111
8 Working with Objects 127
9 Handling Events 141
10 Working with Arrays 165
11 Interacting with the User 197
12 Debugging Your Code 207
III Basic Objects
13 Dealing with Dates and Times: The Date Object 223
14 Working with Numbers: The Math Object 243
15 Manipulating Text: The String Object 265
16 Controlling the Browser: The Navigator Object 297
IV Working with Browser Windows
17 Understanding the Window Object 319
18 Opening, Moving, and Sizing Windows 337
19 JavaScript Surfing: The Location and History Objects 361
20 Manipulating Frames 377
21 JavaScript Project: Setting Up a Password-Protected
Page 405
V Working with the Document Object
22 Understanding the Document Object 427
23 Programming Links, Anchors, and Image Maps 447
24 Working with Images and Mouseovers 467
25 Creating and Using Cookies 495
26 JavaScript Project: Creating a Navigation Tree 523
VI Working with Forms
27 Understanding the Form Object 549
28 Programming Form Fields 569
29 Performing Form Validation 605
30 JavaScript Project: Creating a Shopping Cart 637
VII Working with Dynamic HTML
31 A Brief Overview of Dynamic HTML 673
32 Version 5 DHTML: The W3C’s Document Object
Model 683
33 Version 4 DHTML: Proprietary Object Models 721
34 Cross-Browser Solutions: Detection and Generic
Functions 731
35 Cross-Browser DHTML Examples 769
VIII Appendixes
A JavaScript Tools for Debugging Scripts 831
B JavaScript Reserved Words and Keywords 849
C Working with Regular Expressions 853 Index 873
Trang 2Special Edition Using JavaScript
Copyright © 2001 by Que
All rights reserved No part of this book shall be
repro-duced, stored in a retrieval system, or transmitted by any
means, electronic, mechanical, photocopying, recording,
or otherwise, without written permission from the
pub-lisher No patent liability is assumed with respect to the
use of the information contained herein Although every
precaution has been taken in the preparation of this book,
the publisher and author assume no responsibility for
errors or omissions Nor is any liability assumed for
dam-ages resulting from the use of the information contained
herein
International Standard Book Number: 0-7897-2576-2
Library of Congress Catalog Card Number: 2001087883
Printed in the United States of America
First Printing: June 2001
Trademarks
All terms mentioned in this book that are known to be
trademarks or service marks have been appropriately
capi-talized Que cannot attest to the accuracy of this
informa-tion Use of a term in this book should not be regarded as
affecting the validity of any trademark or service mark
Warning and Disclaimer
Every effort has been made to make this book as complete
and as accurate as possible, but no warranty or fitness is
implied The information provided is on an “as is” basis
The author and the publisher shall have neither liability
nor responsibility to any person or entity with respect to
any loss or damages arising from the information
con-tained in this book
Acquisitions EditorDean MillerDevelopment EditorSean DixonManaging EditorThomas F HayesProject EditorHeather McNeillCopy EditorJulie McNameeIndexer
Tina TrettinProofreaderHarvey StanbroughTechnical EditorJim O’DonnellTeam CoordinatorCindy TeetersInterior DesignerRuth HarveyCover DesignerDan ArmstrongRuth HarveyPage LayoutLizbeth Patterson
Trang 3Introduction 1
What You Need to Know 3
How the Book Is Structured 3
Where’s the Code? 6
Conventions Used in This Book 6
I Getting Started with JavaScript
1 An Overview of JavaScript 11
JavaScript: Controlling the Machine 12
What Is a Programming Language? 12
Is JavaScript Hard to Learn? 14
What Can You Do with JavaScript? 14
What Can’t You Do with JavaScript? 15
Cross-Browser Concerns 16
2 Creating Your First Scripts 17
What Do You Need to Get Started? 18
The Text Editor 18
The Browser 19
Basic Script Construction 20
The <script> Tag 20
Where Do You Put the Tag? 22
Example #1: Displaying a Message to
the User 22
More JavaScript Examples 24
Example #2: Writing Data to the
Page 24
Example #3: A JavaScript Function 26
Example #4: Handling a JavaScript
Event 28
Adding Comments to Your Code 29
Creating External JavaScript Files 30
Debugging and Troubleshooting ScriptProblems 32
II Programming Fundamentals
3 Understanding Variables 39What Is a Variable? 40
Declaring a Variable 40
Storing a Value in a Variable 41
Using Variables in Statements 42
Naming Variables: Rules and Best Practices 44
Rules for Naming Variables 44
Ideas for Good Variable Names 44
Understanding Literal Data Types 45
Working with Numeric Literals 46
Working with String Literals 47
Understand Boolean Literals 49
4 Working with Functions 51What Is a Function? 52
The Structure of a Function 52
Where Do You Put a Function? 53
Using a Function 54
Passing Values to Functions 56
Returning a Value from a Function 60
Understanding Local Versus GlobalVariables 61
Working with Local Scope 62
Working with Global Scope 64
Trang 4Using Recursive Functions 65
Debugging and Troubleshooting Script
Problems 68
Avoiding Infinite Recursion 68
5 Building JavaScript Expressions 71
What Is an Expression? 72
Understanding Expression Structure 72
Building Numeric Expressions 73
A Quick Look at the Arithmetic
Operators 73
Using the Addition (+) Operator 74
Using the Increment (++) Operator 75
Using the Subtraction and Negation
(-) Operators 76
Using the Decrement ( ) Operator 78
Using the Multiplication (*)
Operator 79
Using the Division (/) Operator 79
Using the Modulus (%) Operator 80
Using the Arithmetic Assignment
Operators 81
Building String Expressions 82
Building Comparison Expressions 84
The Comparison Operators 84
Using the Equal (==) Operator 85
Using the Not Equal (!=) Operator 85
Using the Greater Than (>)
Operator 86
Using the Less Than (<) Operator 86
Using the Greater Than Or Equal (>=)
Using the Identity (===) Operator 88
Using the Non-Identity (!==)
Using the Conditional (?:) Operator 89
Building Logical Expressions 91
The Logical Operators 91
Using the AND (&&) Operator 91
Using the OR (||) Operator 92
Using the NOT (!) Operator 93
Advanced Notes On the && and ||Operators 94
Understanding Operator Precedence 96
The Order of Precedence 96
Controlling the Order of Precedence 97
6 Controlling Your Code I: Testing 101
Using if() to Make True/False Decisions 102
Using if() else to Handle a false Result 103
Making Multiple Decisions 105
Using the AND (??) and OR (||)Operators 105
Nesting Multiple if() Statements 106
Using the switch() Statement 107
Debugging and Troubleshooting ScriptProblems 110
7 Controlling Your Code II: Looping 111
What Is Looping and Why Does YourCode Need It? 112
Using while() Loops 113
Using for() Loops 115
Using do while() Loops 118
Trang 5Controlling Loop Execution: break and
The JavaScript Object Hierarchy 129
The Window Object and Its
Hierarchy 129
Other Built-In JavaScript Objects 131
Manipulating Object Properties 132
Referencing a Property 132
Some Objects Are Properties 134
Changing the Value of a Property 134
Using for() in to Loop Through
Constructing Event Handlers 142
Step 1: Add the Event Handler Setup
Using the JavaScript Events 147
Handling When an Object Gets andLoses the Input Focus 148
The Change Event: Handling ModifiedForm Data 152
Handling Keyboard Events 153
Handling Mouse Events 156
Debugging and Troubleshooting ScriptProblems 163
10 Working with Arrays 165
What Is an Array? 166
Declaring an Array 167
Populating an Array with Data 168
Declaring and Populating an Array atthe Same Time 170
Using a Loop to Populate an Array 170
Using a Loop to Work with Array Data 172
Creating Multidimensional Arrays 173
Using the Array Object 176
The Array Object’s Properties 176
The Array Object’s Methods 178
Debugging and Troubleshooting ScriptProblems 189
11 Interacting with the User 197
Why Interact at All? 198
Displaying Messages Using the alert()Method 198
How the Alert Boxes Appear inDifferent Browsers 199
Asking Questions Using the confirm()Method 201
Getting Input Using the prompt() Method 202
How the Prompt Boxes Appear inDifferent Browsers 203
Trang 6Debugging and Troubleshooting Script
Display Expression Values 212
Display the Values of Object
Properties 216
More Debugging Strategies 217
The Top 10 Most Common JavaScript
Error Messages 217
III Basic Objects
13 Dealing with Dates and Times: The Date
Object 223
Understanding JavaScript Dates 224
Arguments Used with the Date
Object 224
Working with the Date Object 225
Specifying the Current Date and
Time 225
Specifying Any Date and Time 225
Extracting Information About a Date 227
Converting getMonth() into a Month
Setting the Date 233
Determining the Day of the Week forAny Date 234
Performing Date Calculations 236
Determining a Person’s Age 236
Performing Complex Date Calculations 237
Calculating an Age In Weeks, Days, and
So On 237
Calculating the Days Between TwoDates 239
Other Date Object Methods 240
14 Working with Numbers: The Math Object 243
How JavaScript Handles Numbers 244
A Quick Look at the Number Object 245
Converting Between Strings and Numbers 246
The parseInt() Function 247
The parseFloat() Function 247
The eval() Function 248
The Math Object 249
Properties of the Math Object 249
Methods of the Math Object 250
Rounding Numbers 251
Rounding a Number to a SpecifiedNumber of Decimals 252
Performing Financial Calculations 253
Generating Random Numbers 260
15 Manipulating Text: The String Object 265Strings and the String Object 266
Determining the Length of a String 266
Trang 7String Object Methods 268
Extracting Characters from the Left:
The left() Method 284
Extracting Characters from the Right:
The right() Method 284
Trimming Extra Spaces: The trim()
Padding a Number with Zeros 293
16 Controlling the Browser: The Navigator
Object 297
About the Navigator Object 298
Determining the User’s Browser
Information 304
Determining the Browser Name 304
Determining the Browser Version 305
Understanding the userAgent
IV Working with Browser Windows
17 Understanding the Window Object 319Revisiting the Window Object
Hierarchy 320
Referencing the Window Object 321
Window Dimensions and the ScreenObject 322
Displaying Messages In the Status Bar 325
Displaying a Custom Link Message 325
Setting Up a Default Status Bar Message 327
Working with JavaScript Timeouts andIntervals 328
Using a Timeout to Perform a FutureAction Once 328
Using an Interval to Perform a FutureAction Repeatedly 331
Emulating setInterval() withsetTimeout() 332
Creating a Scrolling Status Bar Message 333
18 Opening, Moving, and Sizing Windows 337Opening a Window 338
The JavaScript Way: The window.open()Method 338
The Simplest window.open() MethodSyntax 338
Controlling the Size and Position of theNew Window 341
Displaying Toolbars, Menu Bars andOther Window “Chrome” 344
Referencing the Page That Opened aWindow 347
Closing a Window 349
Trang 8Surfing Under Script Control 362
Using the Location Property to Change
the Displayed Page 362
Location Object Properties: 365
Surfing Using the Location Object’s
Properties 365
Using search to Pass a Parameter to
Another Web Page 369
Methods of the Location Object 372
Programmed Surfing with the History
Referencing Nested Frames 383
The top Property 391
Programming Frames 392
Loading a Page into a Frame 392
Updating Multiple Frames with One
Synchronizing Frame Loading 401
21 JavaScript Project: Setting Up a Protected Page 405
Password-Web Page Security Issues 406
A First Attempt at Password Protection 406
Prompting for a Password 406
Converting the Password and Filenameinto Codes 408
The First Real Solution: A Trick for Hidingthe Password 411
Trying Out the Trick 411
Making the Script a Bit More Friendly 412
User-Solving the “404 Not Found”
V Working with the Document Object
22 Understanding the Document Object 427Structure of the Document Object 428
Properties of the Document Object 428
Changing Document Colors 430
Using Color Names 431
Using RGB Values 434
Trang 9Methods of the Document Object 437
Writing Data to the Page 437
Writing to a Document at Startup 438
Writing Browser-Specific Code 440
Writing to a Document In Another
23 Programming Links and Anchors 447
Working with the Link Object 448
Using Functions in Place of URLs in a
Link 448
Referencing a Link Object 449
Link Object Properties 449
Link Object Events 455
Working with the Anchor Object 462
Referencing an Anchor Object 462
Anchor Object Properties 462
24 Working with Images and
Mouseovers 467
Working with the Image Object 468
Referencing an Image Object 468
Properties of the Image Object 469
Changing the Image Source 470
Cycling Through a Series of Images
Handling Image Object Events 481
Creating Mouseover Effects 487
The Simplest Mouseover 487
Preloading Mouseover Images 490
Using a Text Link Mouseover to
Change an Image 492
25 Creating and Using Cookies 495
Saving State: The Need for Truly GlobalVariables 496
What is a Cookie? 496
Advantages of Cookies 497
Disadvantages of Cookies 498
Setting Cookie Data 499
The Simplest Case: Setting the CookieName and Value 499
Getting the Cookie Value 500
Handling Multiple Cookies 501
Adding an Expiration Date 504
Specifying the Path 505
Setting Other Cookie Data 506
Handling All the Cookie Parameters 507
Deleting a Cookie 510
Advanced Cookie Operations 511
Storing Multiple Values in a SingleCookie 511
Encoding Cookie Values 513
Encrypting Cookie Values 516
Debugging and Troubleshooting ScriptProblems 520
Building a Stronger Key 520
26 JavaScript Project: Creating a NavigationTree 523
The Need for Navigation 524
Stage 1: Designing and Creating the MenuObjects 525
Stage 2: Writing a Basic Menu 530
Stage 3: Expanding and Collapsing theMenu Items 534
Stage 3: Expanding and Collapsing theMenu Items 535
Stage 4: Adding Graphics and OtherInterface Enhancements 538
Trang 10VI Working with Forms
27 Understanding the Form Object 549
Structure of the Form Object 550
Referencing a Form Object 550
Form Object Properties 551
Understanding Form Fields 551
Referencing a Form Field 552
Common Form Field Properties 553
Looping Through Form Fields 554
Passing Form and Field Objects to a
Function 555
Programming Buttons 556
Accepting or Rejecting a Submit 556
Accepting or Rejecting a Reset 559
Using a Button to Process Other
Code 560
Forcing a Submit or Reset: The
sub-mit() and reset() Methods 562
Restricting the Number of Form
Submissions 564
28 Programming Form Fields 569
Now For Some Real Form
Programming 570
Programming Text Fields 570
The Text Object 570
The Textarea Object 571
The Password Object 572
The FileUpload Object 572
The Hidden Object 573
Getting a Text Field Value 574
Setting a Text Field Value 576
A More Ambitious Example:
A Mortgage Calculator 578
Making a Text Field Read-Only 582
Special Edition Using JavaScript
x
Programming Checkboxes 585
Getting the Checkbox State 586
Setting the Checkbox State 586
Using a Checkbox to Disable FormFields 587
Controlling the Number of ActivatedCheckboxes 588
Programming Radio Buttons 590
Referencing Radio Buttons 591
Getting a Radio Button State 592
Setting the Radio Button State 594
Programming Selection Lists 594
The Select Object 595
The Option Object 595
Referencing an Option In a SelectionList 596
Getting the Currently Selected ListOption 596
Getting Multiple Selected Options 597
Setting the Selected List Option 598
Creating a Navigation List 599
Modifying a List On-the-Fly 601
29 Performing Form Validation 605The Need for Browser-Based Validation 606
Displaying the Form Data forConfirmation 607
Making Form Fields Mandatory 612
First, a Trick: Adding CustomProperties to an Object 613
Checking for Empty Fields 615
Checking for Fields that Contain OnlyWhitespace Characters 617
Validating the Field Data Type 618
Checking for Alphabetic Data 619
Checking for Integer Data 620
Checking for Signed Integer Data 621
Checking for Floating-Point Data 622
Trang 11Checking for Invalid Data 624
Checking a Numeric Range 625
Removing Extraneous Characters from
a Field 628
Checking Alphanumeric Data Against a
Mask 631
Checking an E-mail Address 634
30 JavaScript Project: Creating a Shopping
Cart 637
Making the Move to E-Commerce 638
Creating the Project Data 638
Designing the Data 638
Creating the Database Using
JavaScript 640
An Overview of the Project 644
Customizing This Project for Your
Own Use 646
Setting Up Your Store 646
Understanding the Shopping Cart 649
Using the Shopping Cart 650
Creating the Cart On-the-Fly Using
JavaScript 650
The Shopping Cart’s Buttons 653
Understanding the Personal Details
Page 655
Initializing the Personal Details
Page 658
Validating the Personal Details 660
Understanding the Credit Card Details
Page 662
Writing the Invoice 662
Initializing and Validating the Credit
Card Details 666
VII Working with Dynamic HTML
31 A Brief Overview of Dynamic HTML 673The Need for Truly Dynamic Pages 674
Dynamic HTML: Scripting for ControlFreaks 674
DHTML Today: A Mess! 675
The Big DHTML Picture 676
An Introduction to the Document ObjectModel 676
The DOM: A Hierarchy of Nodes 679
32 Version 5 DHTML: The W3C’s DocumentObject Model 683
Dealing with Nodes in the DOM 684
Specifying a Node 684
Getting Node Information 687
Working with Elements 688
Working with Tag Attributes 691
Working with Styles 694
Working with Text Nodes 697
An Example: A Text Fader 699
Changing the Structure of the DocumentHierarchy 704
Creating an Element 704
Creating a Text Node 705
Appending a Child Node 705
Inserting a Child Node 709
Replacing a Child Node 713
Cloning a Child Node 715
Removing a Child Node 718
Trang 1233 Version 4 DHTML: Proprietary Object
Models 721
The Pre-DOM Dark Ages 722
The Internet Explorer 4 DHTML
Document Object Model 722
Working with Text 726
The Netscape Navigator 4 Document
Handling Different Browsers 733
Detecting the User’s Browser 735
Using Browser Version Detection 735
Using Object Detection 737
Creating a Custom Object Front-End 739
Examining the Object 739
Cross-Browser Style References 741
Creating the Custom Objects 742
Using a Custom Object 746
Defining the Custom Object
Methods 746
Other Cross-Browser Functions 763
Special Edition Using JavaScript
xii
35 Cross-Browser DHTML Examples 769
Some Notes Before We Begin 770
Cross-Browser DHTML Text Examples 770
A Cross-Browser Tooltip 770
Scrolling Text Horizontally 773
Scrolling Text Vertically 785
Cross-Browser DHTML Image Examples 794
Creating a Logo That Stays in Place asthe User Scrolls 794
Setting Up a Cross-Browser DHTMLSlide Show 796
VIII Appendixes
A JavaScript Tools for Debugging Scripts 831Using the Microsoft Script Debugger 832
Pausing a Script 832
Stepping Through a Script 836
Monitoring Script Values 837
Executing Statements in the CommandWindow 838
Using Netscape’s JavaScript Debugger 838
Pausing a Script 839
Stepping Through a Script 844
Monitoring Script Values 845
B JavaScript Reserved Words and Keywords 849
JavaScript Reserved Words 850
JavaScript Keywords 850
Trang 13C Working with Regular Expressions 853
Pattern Matching the String Object
Pattern Matching the Regular Expression
Building Regular Expressions 854
Special Symbols Used in Regular
The search() Method 868
The replace() Method 870
Index 873
Trang 14Special Edition Using JavaScript
xiv
About the Author
Paul McFedries is the president of Logophilia Limited, a technical writing company He
has been programming since he was a teenager in the mid-1970s, has programmed thing from mainframes to desktops to bar code scanners, and has worked with many differ-ent languages, including Fortran, assembly language, C++, and of course, JavaScript Paulhas written over three dozen books that have sold more than two million copies worldwide,
every-including Windows 98 Unleashed, VBA for Office 2000 Unleashed, The Complete Idiot’s Guide
to Windows Me, and The Complete Idiot’s Guide to Creating a Web Page Paul encourages all
readers to drop by his Web site:
www.mcfedries.com
If you have any comments about the book, please send them to the following address:UsingJavaScript@mcfedries.com
Note, however, that due to time constraints, Paul regrets that he cannot provide JavaScript
technical support or custom programming
Trang 15To Gypsy
Acknowledgments
Robert Pirsig, in Zen and the Art of Motorcycle Maintenance, wrote that “a person who sees
Quality and feels it as he works, is a person who cares.” If this book is a quality product(and I immodestly think that it is), it’s because the people at Que editorial cared enough tomake it so
So a round of hearty thanks is in order for all the good people who worked on this project.You’ll find them all listed near the front of the book, but I’d like to extend special kudos tothe folks I worked with directly: Dean Miller, Development Editor Sean Dixon, ProjectEditor Heather McNeill, and Technical Editor Jim O’Donnell And, last but proverbiallynot least, I’d like to thank all the thousands of readers of my Web page book who sent metheir JavaScript suggestions and experiences I couldn’t have written this book without you
Trang 16I n this introduction
What You Need to Know 3
How the Book Is Structured 3
Where’s the Code? 6
Conventions Used in This Book 6
Trang 17When the Web first came to the attention of the world’s non-geeks back in the mid-1990s,the vastness and variety of its treasures were a wonder to behold However, it didn’t takelong before a few courageous and intrepid souls dug a little deeper into this phenomenon
and discovered something truly phenomenal: they could make Web pages, too!
Why was that so amazing? Well, think back to those old days and think, in particular, of
what it meant to create what we now call content Think about television shows, radio
pro-grams, magazines, newspapers, books, and the other media of the time The one thing they
all had in common was that their creation was a decidedly uncommon thing It required a
team of professionals, a massive distribution system, and a lot of money.
The Web appeared to change all that because learning HTML was within the grasp of body who could feed himself, it had a built-in massive distribution system (the Internet),and it required little or no money For the first time in history, content was democratizedand was no longer defined as the sole province of governments and mega-corporations.Then reality set in
any-People soon realized that merely building a Web site wasn’t enough to attract “eyeballs,” asthe marketers say A site had to have interesting, useful, or fun content, or people wouldstay away in droves Not only that, but this good content had to be combined with a solidsite design, which meant that Web designers needed a thorough knowledge of HTML andgood design skills
But, alas, eventually even all that was not enough To make their Web sites work with theworld’s different browsers, to make their sites easy to navigate, and to give their sites thoseextra bells and whistles that surfers had come to expect, something more than content,HTML, and design was needed
That missing link was JavaScript
What we’ve all learned the hard way over the past few years is that you simply can’t puttogether a world-class Web site unless you have some scripting prowess in your site designtoolkit You need to know how to script your way out of the basic problems that afflict mostsites, and how to use scripts to go beyond the inherent limitations of HTML And it isn’tenough just to copy the generic scripts that are available on the Web and paste them intoyour pages First of all, most of those scripts are very poorly written, and second of all theyinvariably need some customization to work properly on your site
My goal in this book is to show you how to create your own JavaScript programs that aresuited to your site and your content My aim is to show you that JavaScript isn’t hard tolearn, and that even the most inveterate non-programmer can learn how to put togetherscripts that will amaze their friends (and themselves)
Trang 183How the Book is Structured
What You Need to Know
This book is not a primer on creating Web pages or on using the World Wide Web This is
a JavaScript book, pure and simple This means I assume you already know the following:
■ How to operate a basic text editor, and how to get around the operating system and filesystem on your computer
■ How to use your Web browser
■ The basic HTML tags and attributes, particularly those that comprise the HTML 4
standard
■ The basic style sheet rules and attributes, particularly those that comprise the
Cascading Style Sheets 2 standard
“I’ve Never Programmed Before!”
If you’ve never done a stitch of computer programming before, even if you’re not quite surewhat programming really is, don’t worry about it for a second because I had you in mind
when I wrote this book For too many years programming has been the property of ers” and other technowizards That made some sense because the programming languagesthey were using—with bizarre names such as C++ and Fortran—were exceedingly difficult
“hack-to learn, and even harder “hack-to master
JavaScript, however, is different It’s nowhere near as hard to learn as those for-nerds-only
languages I honestly believe that anyone can become a savvy and successful JavaScript
pro-grammer, and this book is, I hope, the proof of that assertion Just follow along, examine
my scripts carefully (particularly those in the first few chapters), and practice what you
learn, and you will master JavaScript.
“I Have Programmed Before!”
What if you’ve done some programming in the past? For example, you might have dipped
a toe or two in the JavaScript waters already, or you might have dabbled with Basic, VisualBasic, or some other language Will this book be too basic for you? No, not at all My other
main goal in this book is to provide you with a ton of examples of truly useful scripts that
you can customize and incorporate into your own site The book’s first few chapters start
slowly to avoid scaring off those new to this programming business But once we get pastthe basics, I introduce you to lots of great techniques and tricks that will take your pro-
gramming skills to a higher level
How the Book Is Structured
If you’re looking for lots of JavaScript history, theory and long-winded explanations of cepts, I’m sorry but you won’t find it here My philosophy throughout this book is “It’s the
Trang 19con-code, stupid!” I explain what needs to be explained and then I move on without further ado(or without any ado at all) to examples and scripts that do more to illuminate a concept thatany verbose explanations I could muster (and believe me, I can muster verbosity with thebest).
How you approach this book depends on your current level of JavaScript expertise (or lackthereof):
■ If you’re just starting out, begin at the beginning with Chapter 1 and work at your ownpace sequentially through to Chapter 12 This will give you all the knowledge you need
to pick and choose what you want to learn throughout the rest of the book
■ If you know a bit of JavaScript already, you can probably get away with taking a fastlook at Chapter 2, and then working quickly through the material in Part II You’llthen be ready to branch out and explore the rest of the book as you see fit
■ If you’re a relatively experienced JavaScript programmer, you might want to first skimthrough Part II I’ve got a few tricks in there that you might find interesting After that,feel free to consider the rest of the book a kind of scripting smorgasbord that you cansample as your programming taste buds dictate
Just so you know what to expect and to help you plan your forays into the book, the nextfew sections summarize the content of the book’s eight parts
Part I—Getting Started with JavaScript
This short section includes just two chapters Chapter 1, “An Overview of JavaScript,” givesyou the big JavaScript picture and explains why JavaScript is such a fundamental tool forWeb designers If you’re new to programming, you’ll appreciate my explanation of justwhat a programming language is Chapter 2, “Creating Your First Scripts,” gets down tothe coding brass tacks by showing you how to add scripts to your pages and by taking youstep-by-step through the process of creating a few simple scripts
Part II—Programming Fundamentals
Part II, with ten chapters in all, is the longest section of the book That’s appropriatebecause the aim of these chapters is to provide you with a solid JavaScript foundation And
if there’s a single secret to becoming a successful programmer it’s this: Learn the basics well.The more comfortable you are with things like variables, functions, and expressions (thetopics of Chapters 3 through 5), the easier time you’ll have grasping higher-level topics.Other chapters in Part II cover things such as controlling your JavaScript code, objects (one
of the most important JavaScript concepts), events, and arrays I also show you some tant techniques for getting your scripts to interact with your site visitors and how to trouble-
impor-shoot (debug in programming lingo) script problems.
Trang 205How the Book is Structured
Part III—Using JavaScript’s Basic Objects
The four chapters in Part III tackle four indispensable JavaScript objects The Date object(Chapter 13, “Dealing with Dates and Times: The Date Object”) enables you to work withdates and times For example, you can create simple JavaScript clocks, you can figure out
the number of days from now until some date in the future, and lots more The Math
object (Chapter 14, “Working with Numbers: The Math Object”) enables you to performlots of interesting calculations, including doing useful financial calculations such as comput-ing loan payments and figuring out the future value of an investment The String object
(Chapter 15, “Manipulating Text: The String Object”) is one of the most commonly usedJavaScript objects because your scripts work with text all the time Finally, the Navigator
object (Chapter 16, “Controlling the Browser: The Navigator Object”) enables you to ure out some interesting information about the browser that a site visitor is using (such asthe name of the browser, its version number, and what operating system it’s running on)
fig-Part IV—Working with Browser Windows
Your scripting moves into a higher gear here in Part IV That’s because these five chaptersshow you how to use JavaScript to manipulate the user’s actual browser window You’ll learnhow to display messages in the status bar, how to get the dimensions of the window, how toopen new windows, and how to close them when they’ve served their purpose I also showyou how to send the browser to a specified page and how to fiddle with frames via
JavaScript I close with a full-chapter project that shows you various methods for using
JavaScript to set up a password-protected Web page
Part V—Working with the Document Object
The Document object refers to the Web page that’s displayed in the browser, and the fivechapters in Part V show you a fistful of ways to work with these documents You learn how
to change document colors, work with links, and even how to write tags and text to a ment, on-the-fly! If you can’t wait to learn how to do those fun “mouseover” effects that arefeatured on many sites, then Chapter 24, “Working with Images and Mouseovers,” is the
docu-place to go I also show you how to work with cookies, and I close with another project: anavigation “tree” that makes it easy for visitors to get from here to there on your site
Part VI—Working with Forms
One of the most common uses for JavaScript code is to work with forms, and that’s just
what you’ll learn in the four chapters that comprise Part VI I show you how to control
form submission from your code and how to work with all the field types (text boxes, checkboxes, radio buttons, select lists, and so on) There’s also an entire chapter on form valida-tion that shows you how to do things such as ensure a field is filled in, check for valid phonenumbers and email addresses, and lots more I also take you through a complete shoppingcart script
Trang 21Part VII—Working with Dynamic HTML
Dynamic HTML refers to the ability to manipulate a page’s tag and text after it has already
loaded As you’ll see in the five chapters that make up Part VII, this enables you to createmany interesting effects, including text that scrolls across the page, image slide shows, andlots more
Part VIII—Appendixes
The book winds up with three appendixes Appendix A, “JavaScript Tools for DebuggingScripts,” shows you how to use Microsoft’s Script Debugger and Netscape’s JavaScriptDebugger, both of which can help you fix script problems Appendix B, “JavaScript
Reserved Words and Keywords,” provides you with a complete list of all the JavaScriptwords that you need to avoid when making up your own variable and function names.Appendix C, “Working with Regular Expressions,” introduces you to the wacky but usefulworld of JavaScript regular expressions
Where’s the Code?
I believe wholeheartedly that the best way to learn JavaScript (or anything, for that matter)
is to be given lots of good quality examples To that end, this book contains hundreds of
example scripts for you to try out and study However, life is way too short to have to type
in the examples by hand The good news is that you don’t have to because I’ve put everylast example online at my Web site Here’s where you’ll find everything:
http://www.mcfedries.com/UsingJavaScript/
Conventions Used in This Book
This book uses various stylistic and typographic conventions to make it easier to use:
Italic New terms and phrases when initially defined
Monospace Code listings, JavaScript keywords and reserved words, Web
addresses, and filenames
➥ Indicates the continuation of a long code line from the previous line
When you see a note in this book, it indicates additional information that might helpyou avoid problems or that should be considered in using the described features
Trang 227Conventions Used in This Book
Special Edition Using JavaScript uses cross references to help you access related information
in other parts of the book
➔ To learn more about JavaScript comments, see “Adding Comments to Your Code,” p 29.
Finally, some of the book’s chapters close with a special section titled “Debugging and
Troubleshooting Script Problems,” that tells you how to fix or work around common
JavaScript gotchas
Tip paragraphs suggest easier or alternative methods of executing a procedure Tipsintroduce techniques applied by seasoned developers to simplify tasks or to makedesign and implementation decisions that produce robust and maintainable systems
Cautions warn you of hazardous procedures (for example, activities that delete files)
Trang 24Getting Started with JavaScript
1 An Overview of JavaScript 11
2 Creating Your First Scripts 17
IPART
Trang 26An Overview of JavaScript
I n this chapter
JavaScript: Controlling the Machine 12
What Is a Programming Language? 12
Is JavaScript Hard to Learn? 14
What Can You Do with JavaScript? 14
What Can’t You Do with JavaScript? 15
Cross-Browser Concerns 16
1CHAPTER
Trang 27JavaScript: Controlling the Machine
When a Web browser is confronted with an HTML file, it goes through a simple buttedious process: it reads the file one line at a time, starting from (usually) the <html>tag atthe top and finishing with the </html>tag at the bottom Along the way, it might have tobreak out of this line-by-line monotony to perform some action based on what it has read.For example, if it stumbles over the <img>tag, the browser will immediately ask the Webserver to ship out a copy of the graphics file specified in the srcattribute
The point here is that, at its core, a Web browser is really just a page-reading machine thatdoesn’t know how to do much of anything else besides follow the instructions (the markup)
in an HTML file (For my own convenience, I’m ignoring the browser’s other capabilities,such as saving favorites or bookmarks.)
One of the reasons that I think many people get instantly hooked on creating Web pages isthat they quickly realize they have control over this page-reading machine Slap some textbetween a <b>tag and its corresponding </b>end tag and the browser dutifully displays thetext as bold Create a <table>structure and the browser displays your formerly haphazardtext in nice, neat rows and columns, no questions asked In other words, instead of just view-
ing pages from the outside, you now have a key to get inside the machine and start working its controls That is the hook that grabs people and gets them seriously interested in Web
page design
Imagine if you could take this idea of controlling the page-reading machine to the nextlevel Imagine if, instead of ordering the machine to process mere tags and text, you couldissue much more sophisticated orders that could actually control the inner workings of thepage-reading machine Who wouldn’t want that?
Well, that’s the premise behind JavaScript It’s essentially just a collection of commands thatyou can wield to control the browser Like HTML tags, JavaScript commands are inserteddirectly into the Web page file When the browser does its line-by-line reading of the fileand it comes across a JavaScript command, it executes that command, just like that
However, the key here is that the amount of control JavaScript gives you over the reading machine is much greater than what you get with HTML tags The reason is that
page-JavaScript is a full-fledged programming language The “L” in HTML might stand for
“language,” but there isn’t even the tiniest hint of a programming language associated with HTML JavaScript, though, is the real programming McCoy
What Is a Programming Language?
So what does it mean to call something a “programming language”? To understand thisterm, you need look no further than the language you use to speak and write At its mostfundamental level, human language is composed of two things—words and rules:
■ The words are groupings of letters that have a common meaning among all the peoplewho speak the same language For example, the word “book” denotes a particular type
of object and the word “read” denotes a particular type of action
Trang 2813What Is a Programming Language?
■ The rules are the ways in which words can be combined so as to create coherent and
understandable concepts If you want to be understood by other speakers of the
lan-guage, then you have only a limited number of ways to throw two or more words
together “I read a book” is an instantly comprehensible sentence, but “book a I read”
is gibberish
The key goal of human language is being understood by someone else who is listening to
you or reading something you wrote If you use the proper words to refer to things and
actions, and if you combine words according to the rules, then the other person will
understand you
A programming language works in more or less the same way That is, it, too, has words
and rules:
■ The words are a set of terms that refer to the specific things that your program works
with (such as a browser window) or the specific ways in which those things can be
manipulated (such as opening a browser window) They’re known as reserved words or
keywords.
■ The rules are the ways that the words can be combined so as to produce the desired
effect In the programming world, these rules are known as the language’s syntax.
In JavaScript, many of the words you work with are very straightforward There are some
that refer to aspects of the browser, others that refer to parts of the Web page, and some
that are used internally by JavaScript For example, in JavaScript the word windowrefers to
the browser window as a whole Similarly, the word open()refers to a specific type of action
(opening something)
The crucial concept here is that just as the fundamental purpose of human language is to be
understood by another person, the fundamental purpose of a programming language is to
be understood by whatever machine is processing the language With JavaScript, that
machine is the page-reading machine, the Web browser
You can make yourself understood by the page-reading machine by using the proper
JavaScript words and by combining them using the proper JavaScript syntax For example,
JavaScript’s syntax rules tell you that you can combine the words windowand open()like so:
window.open() If you use open().windowor window openor any other combination, the
page-reading machine won’t understand you
The key, however, is that being “understood” by the page-reading machine really means
being able to control the machine That is, your JavaScript “sentences” are actually
com-mands that you want the machine to carry out For example, if you want to open a new
browser window using JavaScript, you insert the following command inside your Web page:
window.open()
When the page-reading machine trudges through the HTML file and it comes upon this
statement, it will go right ahead and open up a new browser window (Actually, there are
1
I
Part
Ch
Trang 29some extra things that need to go along with the command for it to work properly I tell youabout them in Chapter 2, “Creating Your First Scripts.”)
Is JavaScript Hard to Learn?
I think there’s a second reason why many folks get jazzed about creating Web pages: It’s not
that hard HTML sounds like it’s a hard thing, and certainly if you look at the source code of
a typical Web page without knowing anything about HTML, the code appears about asintimidating as anything you can imagine
However, I’ve found that anyone can learn HTML as long as they start with the basic tags,
see lots of examples of how they work, and slowly work their way up to more complexpages It’s just a matter of creating a solid foundation and then building on it
I’m convinced that JavaScript can be approached in much the same way I’m certainly notgoing to tell you that JavaScript is as easy to learn as HTML That would be a bald-facedlie However, I will tell you that there is nothing inherently difficult about JavaScript Usingour language analogy, it just has a few more words to know and a few more rules to learn.But I believe that if you begin with the basic words and rules, see lots of examples of how
they work, and then slowly build up to more complex scripts, that you can learn JavaScript
programming By the time you finish this book, I predict here and now that you’ll even be
a little bit amazed at yourself and at what you can do
What Can You Do with JavaScript?
The readers of my book on creating Web pages are a friendly bunch who enjoy writing to
me to tell me how their pages are coming along In many cases, they tell me they’ve hit theWeb page equivalent of a roadblock That is, there’s a certain thing they want to do, butthey don’t know how to do it in HTML So I end up getting lots of questions like these:
■ How do I display one of those pop-up boxes?
■ How do I figure out which browser a surfer is using?
■ How can I get a message to scroll along the status bar?
■ How can I make an image change when the mouse is over it?
■ How can I calculate the total for my order form?
For each question, the start of the answer is always this: “Sorry, but you can’t do that usingHTML; you have to use JavaScript instead.” I then supply them with a bit of code that theycan “cut and paste” into their Web pages and then get on with their lives
If you’re just getting started with JavaScript, then my goal in this book is to help you tomove from “cut-and-paste” to “code-and-load.” That is, I hope you’ll end up being able tocreate your own scripts to solve your own unique HTML and Web page problems I hope
to show you that learning JavaScript is worthwhile because there are many other things youcan do with it:
Trang 3015What Can’t You Do with JavaScript?
■ You can display the user’s current date and time, create animated “clocks,” determine a
person’s age, and perform many other date-related actions
■ You can calculate loan and mortgage payments and other financial data
■ You can determine not only the name of the user’s browser, but also its version number
and the operating system it’s running on
■ You can work with extra browser windows, which means you can open them, resize
them, close them, and even change their content at will
■ You can send the user’s browser to another page
■ You can set up a password-protected page
■ You can create a navigation “tree” that makes it easy for users to traverse the pages of
your site
■ You can validate the values in a form before submitting it to the server For example,
you can make sure that certain fields are filled in
■ You can create a “shopping cart” that stores the items a user has selected for purchasing
■ You can create sophisticated animations such as making text scroll across the screen or
setting up an image slide show complete with transition effects
In this book you’ll learn how to do all of these things and many more
What Can’t You Do with JavaScript?
JavaScript is good, but it’s not that good JavaScript can do many things, but there’s a long
list of things that it simply can’t do Here’s a sampling:
■ You can’t write data permanently to a file For example, you can’t take the data from a
guest book and add it to a page that displays the messages
■ You can’t access files on the server
■ You can’t access files on the user’s computer (except for a special file called a cookie;
see Chapter 25, “Creating and Using Cookies”)
■ You can’t glean any information about the user, including her email address or
IP address
■ You can’t submit credit card-based purchases for authorization and payment
■ You can’t create multiplayer games
■ You can’t get data from a server database
■ You can’t handle file uploads
There are versions of JavaScript that run on the server and that can do some of these things,
but I don’t discuss them in this book Instead, this is a book about what’s known as client-side
JavaScript, which means JavaScript that runs on the user’s browser (which programming
types like to call a client) Not to worry, though: There are so many things that client-side
JavaScript can do that you’ll have no trouble being as busy as you want to be
1
I
Part
Ch
Trang 31Cross-Browser Concerns
I mentioned earlier that your goal as a JavaScript programmer is to structure the language’swords and rules in such a way that the browser’s page-reading machine understands andcarries out your commands That sounds like a straightforward idea, but there’s a prettybig fly in the JavaScript ointment: browser compatibility As you probably know from yourHTML coding—or, even more so, from your style sheet coding—there are three problemsthat crop up constantly:
■ Browsers from different companies render HTML or style sheet codes in
different ways
■ Browsers from different companies don’t support the same set of tags and styles Somebrowsers have their own proprietary tags (such as Internet Explorer’s <marquee>tag andNetscape’s <layer>tag) and some browsers lack support for tags and styles that are con-sidered to be standard
■ Older browsers (including older versions of browsers from the same company) don’tsupport all of the features found in newer browsers
Unfortunately for your career as a JavaScript programmer, all of these problems also apply
to the JavaScript language The JavaScript words, and to a lesser extent the rules, stood by the page-reading machine are slightly different from one browser (and one browserversion) to the next The good news is that these differences aren’t major, so most of yourcode will run fine in most browsers However, it’s important that you never assume that justbecause a script is working in one browser that it will automatically work in all browsers Inthe same way that a good Web page designer checks out his pages in different browsers andbrowser versions, so should you run your scripts in as many different browsers as you possi-bly can I’ll talk more about this in the next chapter
Trang 32under-Creating Your First Scripts
I n this chapter
What Do You Need to Get Started? 18
Basic Script Construction 20
More JavaScript Examples 24
Adding Comments to Your Code 29
Creating External JavaScript Files 30
Debugging and Troubleshooting Script Problems 32
2CHAPTER
Trang 33For the purposes of this book, you don’t need a Web host because it’s possible to writeand test your scripts on your computer without being connected to the Internet.
What Do You Need to Get Started?
One of the nicest things about HTML is that the hurdles you have to leap to get started arenot only short, but few in number In fact, you really need only two things, both of whichare free: a text editor to enter the tags and text, and a browser to view the results (You’llalso need a Web server to host the finished pages, but the server isn’t necessary when you’recreating the pages.) Yes, there are high-end HTML editors and fancy graphics programs,but these fall into the “Bells and Whistles” category and you can create perfectly respectableWeb pages without them
The basic requirements for JavaScript programming are exactly the same as for HTML: atext editor and a browser Again, there are programs available to help you write and testyour scripts, but you don’t need them
➔ For a discussion of JavaScript debugging tools, see Appendix A, “JavaScript Tools for Debugging Scripts,” p 831.
Figure 2.1
If you’re using a word
processor, be sure to
save the file using a
plain text format.
The Text Editor
Any text editor will do for writing scripts If you run some flavor of Windows, the Notepadprogram is perfectly acceptable, as is the EDIT.COM DOS text editor that ships withWindows If the Mac is your machine of choice, use the built-in SimpleText program.Can you use a word processor instead of a text editor? Absolutely, but you need to be care-ful because you want to ensure that the resulting files are in a plain text format and not theformat of the word-processing program To illustrate how you do this, here’s the procedurefor saving a WordPad (the word processor that comes with Windows) document as a plaintext file:
1 Select the File, Save As command WordPad displays the Save As dialog box
2 In the Save as Type drop-down list, select Text Document, as shown in Figure 2.1
Trang 3419What Do You Need to Get Started?
3 Use the File Name text box to enter a name for the document:
• If you’re saving a Web page, finish the filename with the .htmor .htmlextension
• If you’re saving an external JavaScript file, be sure to add the js extension
➔ I cover external JavaScript files later in this chapter; see “Creating External JavaScript Files,” p 30.
4 Select a location for the file and then click Save
The Save As dialog box in most Windows word-processing programs has a Save as Type
drop-down list that you use to choose the plain text file format However, the name of the format
varies from program to program In Microsoft Word, for example, the item you choose is
called Text Only If you’re using the AppleWorks word processor on a Mac, the Save dialog
box has a File Format list from which you select the Text item (or the HTML item)
The Browser
The Web browser enables you to test your JavaScript programs before making them
avail-able to the public The problem here is that “the public” uses many different brands and
versions of browsers and, as you learned in Chapter 1, “An Overview of JavaScript,” not all
browsers support JavaScript in the same way Because there are dozens of browser
possibili-ties, it isn’t possible to test all of them The best approach is to cover as many of the most
popular browsers and versions as you can How do you know what’s popular? There are
many sites on the Web that will give you browser statistics (you can use the phrase “browser
statistics” as a query in any good search engine to find many Web sites), but here are two:
http://browserwatch.internet.com/
http://www.mcfedries.com/BrowserStats.html
The second page is from my Web site, and an example is shown in Figure 2.2 As you can
see, there are four browsers that, at least when I wrote this, held over 95% of the browser
market: Internet Explorer versions 4, 5, and 6, and Netscape Navigator versions 4.x
This page from my
Web site gives you a
browser breakdown of
the people who visit
my pages.
Trang 35In HTML 4.0, the languageattribute has been deprecated in favor of the type
attribute However, you should use both for backward compatibility (for example,Internet Explorer 3.x and earlier, and Netscape 4.x and earlier, don’t support the
typeattribute)
If you have just one computer, you should install only the most popular browsers Since youcan have only one version of Internet Explorer on a machine, install the most popular ver-sion (For example, based on the numbers in Figure 2.2, you’d install Internet Explorer 5.)For a second browser, select the most popular browser from a company other than
Microsoft (For example, the numbers in Figure 2.2 would dictate that the second browser
be Netscape 4.) If you have a second computer, install one or two of the next most popularbrowsers Over time, keep an eye on these usage statistics so that you always know whatpeople are using and can modify your setup accordingly
➔ For more about JavaScript and browsers, see “Cross-Browser Concerns,” p 16.
Basic Script Construction
With your text editor and browser (or browsers) running, you’re ready to start scripting.This section describes the standard procedure for constructing and testing a script You’llsee a working example that you can try out, and later you’ll move on to other examples thatillustrate some JavaScript techniques that you’ll use throughout this book
The <script> Tag
The basic container for a script is, naturally enough, the HTML <script>tag and its ated </script>end tag For a simple script, the tag is embellished with both the language
associ-attribute, which is set to the value “JavaScript”, and the typeattribute, which is set to
“text/javascript”:
<script language=”JavaScript” type=”text/javascript”>
JavaScript statements go here
</script>
You’ll almost always set the <script>tag’s languageattribute to “JavaScript” However, thereare other values that correspond to the various versions of JavaScript that have appeared overthe years The original JavaScript was supported by Netscape 2 and Internet Explorer 3 Hereare the initial browser versions that supported subsequent JavaScript releases:
JavaScript 1.1 Netscape 3.01JavaScript 1.2 Internet Explorer 4.01, Netscape 4.05JavaScript 1.3 Internet Explorer 5.0, Netscape 4.61JavaScript 1.4 Mozilla 5.0 Alpha Pre-Release M6JavaScript 1.5 Internet Explorer 5.5, Netscape 6 Beta 1
Trang 3621Basic Script Construction
In each release, new JavaScript features were added or existing features were modified This
means that earlier browsers don’t support the new or changed features To avoid errors if
you use such features, you can specify which JavaScript release your code uses For example,
if your code uses a JavaScript 1.1 feature, you’d set up your <script>tag like this:
<script language=”JavaScript1.1” type=”text/javascript”>
(Notice how, in the languagevalue, there’s no space between JavaScriptand the version
number.) The browser checks the JavaScript version (1.1, in the previous example) and, if
it doesn’t support that version, it ignores the script entirely Again, however, specifying
the version number will likely be something you do only occasionally
Handling Browsers That Don’t Support JavaScript
Before moving on, you should also note that there is a (very slight) chance that someone
might visit your page using an ancient browser that doesn’t support JavaScript In that case,
the browser will likely attempt to process the JavaScript statements that you insert between
the <script>and </script>tags To prevent that, enclose your script statements using the
HTML comment tags—<!—and —>—like this:
<script language=”JavaScript” type=”text/javascript”>
<! Commence hiding the script from ancient browsers
JavaScript statements go here
// Stop hiding the script >
</script>
Note that that line that includes the close comment tag is prefaced with a double slash (//)
The close comment tag (—>))>)> (close comment tag)> contains a double dash (—), which is
a JavaScript operator, so the //symbol tells the browser not to process the line as a
JavaScript statement //is an example of a JavaScript comment indicator
➔ To learn more about JavaScript comments, see “Adding Comments to Your Code,” p 29.
➔ You learn about the operator later in the book; see “Using the Decrement ( ) Operator,” p 78.
Handling Browsers with JavaScript Turned Off
Although JavaScript-ignorant browsers are a rarity these days, users who have turned off
their browser’s JavaScript functionality aren’t so rare Many people disable JavaScript
because they’re concerned about security, they don’t want cookies written to their hard
drives, and so on To handle these browsers (as well as those browsers that don’t support
JavaScript at all), place the <noscript>tag within the body of the page:
Trang 37It’s perfectly acceptable to insert multiple <script>tags within a single page, as long
as each one has a corresponding </script>end tag, and as long as you don’t putone<script>block within another one
Where Do You Put the Tag?
With certain exceptions, it doesn’t matter a great deal where you put your <script>tag.Some people place the tag between the page’s </head>and <body>tags The HTML stan-dard recommends placing the <script>tag within the page header (that is, between <head>
and </head>), so that’s the style I’ll use in this book:
<html>
<head>
<title>My First JavaScript Script</title>
<script language=”JavaScript” type=”text/javascript”>
<! Commence hiding the script from ancient browsers
JavaScript statements go here
// Stop hiding the script >
Here are the exceptions to the put-your-script-anywhere technique:
■ If your script is designed to write data to the page, the <script>tag must be positionedwithin the page body (that is, between the <body>and </body>tags) in the exact posi-tion where you want the text to appear
➔ For a script that adds data to a page, see “Example #2: Writing Data to the Page,” p 24.
■ If your script refers to an item on the page (such as a form object), then the script must
be placed after that item.
■ With many HTML tags, you can add one or more JavaScript statements as attributesdirectly within the tag
➔ To work with JavaScript within an HTML tag, see “Example #4: Handling a JavaScript Event,” p 28.
■ If you’ll be using an external file to hold the script, you leave out the <script>tag gether and just enter your statements in the file
alto-➔ I talk about external JavaScript files later in this chapter; see “Creating External JavaScript Files,” p 30.
Example #1: Displaying a Message to the User
You’re now ready to construct and try out your first script This example shows you the simplest of all JavaScript actions: displaying a simple message to the user Listing 2.1 showsthe script within an HTML file
Trang 38Listing 2.1 Displaying a Message to the User
<html>
<head>
<title>Listing 2.1: Displaying a Message to the User</title>
<script language=”JavaScript” type=”text/javascript”>
As shown in Listing 2.1, place the script within the header of a page, save the file, and then
open the HTML file within your browser:
■ In Internet Explorer, select File, Open (or press Ctrl+O) to display the Open dialog
box, click the Browse button, and then pick out the HTML file If you’ve loaded the
file previously, you should update the display by selecting View, Refresh (or by pressing
F5) tag;messages;displaying>
■ In Netscape Navigator, select File, Open Page (or press Ctrl+O), and then click
Choose File (In Netscape 6, select File, Open File or press Ctrl+O.) In the dialog
box that appears, find the HTML file and click Open To make sure you’re viewing
the latest version of the file, select View, Reload (or press Ctrl+R)
This script consists of just a single line:
alert(“Hello World Wide Web!”)
This is called a statement, and each statement is designed to perform a single JavaScript task.
Your scripts will range from simple programs with just a few statements, to huge projects
consisting of dozens or even hundreds of statements In this case, the statement runs the
JavaScript alert()method, which displays to the user whatever message is enclosed within
the parentheses (which could be a welcome message, an announcement of new features on
your site, an advertisement for a promotion, and so on) Figure 2.3 shows the message that
appears when you open the file
Trang 39➔ For more on the JavaScript alert()method, see “Displaying Messages Using the alert() Method,”
p 198.
How did the browser know to run the JavaScript statement? When a browser processes
(parses, in the vernacular) a page, it basically starts at the beginning of the HTML file and
works its way down, one line at a time If it trips over a <script>tag, then it knows one ormore JavaScript statements are coming, and it automatically executes those statements, inorder, as soon as it reads them The exception to this is when JavaScript statements are
enclosed within a function, which I’ll explain later
➔ For the function example, see “Example #3: A JavaScript Function,” p 26.
More JavaScript Examples
My goal in this chapter is not only to show you the basics of constructing scripts, but also togive you hints about the kinds of things you can do with JavaScript To that end, this sectionpresents three more simple examples that use JavaScript in different ways, and that also pro-vide you with useful techniques that you can immediately incorporate into your own pages.Example #2: Writing Data to the Page
One of JavaScript’s most powerful features is the capability to write text, data, and evenHTML tags to the Web page on-the-fly That is, the text (or whatever) gets inserted intothe page when a Web browser loads the page What good is that? For one thing, it’s idealfor time-sensitive data For example, you might want to display the date and time that aWeb page was last modified so that visitors know how old (or new) the page is Listing 2.2shows just such a script
Figure 2.3
This “alert” message
appears when you
open the HTML file
containing the
exam-ple script.
A method is a special kind of JavaScript feature You’ll learn about methods in detail
in Chapter 8, “Working with Objects.” For now, however, think of a method as a kind
of command
Trang 40All the code listings in this book are available on my Web site The address for eachpage is as follows:
Listing 2.2 Writing Data to the Page
This is a regular line of text.<br>
<script language=”JavaScript” type=”text/javascript”>
Notice how the script appears within the body of the HTML document This is necessary
whenever you want to write data to the page Figure 2.4 shows the result
Figure 2.4
When you open the
file, the text is
dis-played along with the
date and time the file
was last modified.
This script makes use ofthe Document object, which is a built-in JavaScript construct that refers
to whatever HTML file (document) the script resides in The document.write()statement
tells the browser to write whatever is within the parentheses to the Web page The
docu-ment.lastModifiedportion returns the date and time the file was last changed and saved
➔ To learn more about objects, see Chapter 8, “Working with Objects,” p 127.
➔ To get the details on the Document object, see Chapter 22, “Understanding the Document Object,” p 427.