0% found this document useful (0 votes)
26 views77 pages

Special Edition Using Javascript Mcfedries - The Complete Ebook Is Available For Download With One Click

The document provides links to download various ebooks, including 'Special Edition Using JavaScript' by Paul McFedries, along with additional suggested titles. It includes a detailed table of contents for the JavaScript book, covering topics from programming fundamentals to working with objects and forms. The document emphasizes the availability of these resources on ebookultra.com.

Uploaded by

ddsinanku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views77 pages

Special Edition Using Javascript Mcfedries - The Complete Ebook Is Available For Download With One Click

The document provides links to download various ebooks, including 'Special Edition Using JavaScript' by Paul McFedries, along with additional suggested titles. It includes a detailed table of contents for the JavaScript book, covering topics from programming fundamentals to working with objects and forms. The document emphasizes the availability of these resources on ebookultra.com.

Uploaded by

ddsinanku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Visit https://ebookultra.

com to download the full version and


explore more ebooks

Special Edition Using Javascript Mcfedries

_____ Click the link below to download _____


https://ebookultra.com/download/special-edition-using-
javascript-mcfedries/

Explore and download more ebooks at ebookultra.com


Here are some suggested products you might be interested in.
Click the link to download

DHTML Utopia Modern Web Design Using JavaScript DOM 1st


edition Edition Stuart Langridge

https://ebookultra.com/download/dhtml-utopia-modern-web-design-using-
javascript-dom-1st-edition-edition-stuart-langridge/

Pro Android Web Apps Develop for Android Using HTML5 CSS3
JavaScript 1st Edition Damon Oehlman

https://ebookultra.com/download/pro-android-web-apps-develop-for-
android-using-html5-css3-javascript-1st-edition-damon-oehlman/

IPhone 3G portable genius Paul Mcfedries

https://ebookultra.com/download/iphone-3g-portable-genius-paul-
mcfedries/

Microsoft Windows Vista Unleashed Paul Mcfedries

https://ebookultra.com/download/microsoft-windows-vista-unleashed-
paul-mcfedries/
The Essential Guide to HTML5 Using Games to Learn HTML5
and JavaScript 1st Edition Jeannie Meyer (Auth.)

https://ebookultra.com/download/the-essential-guide-to-html5-using-
games-to-learn-html5-and-javascript-1st-edition-jeannie-meyer-auth/

iPad Portable Genius 1st Edition Paul Mcfedries

https://ebookultra.com/download/ipad-portable-genius-1st-edition-paul-
mcfedries/

Excel 2010 Simplified 1st Edition Paul Mcfedries

https://ebookultra.com/download/excel-2010-simplified-1st-edition-
paul-mcfedries/

What Really Works in Special and Inclusive Education Using


evidence based teaching strategies 1st Edition David
Mitchell
https://ebookultra.com/download/what-really-works-in-special-and-
inclusive-education-using-evidence-based-teaching-strategies-1st-
edition-david-mitchell/

Stepping Out Using Games and Activities to Help Your Child


With Special Needs 1st Edition Sarah Newman

https://ebookultra.com/download/stepping-out-using-games-and-
activities-to-help-your-child-with-special-needs-1st-edition-sarah-
newman/
Special Edition Using Javascript Mcfedries Digital Instant
Download
Author(s): McFedries, Paul
ISBN(s): 9780789725769, 0789725762
Edition: Special Ed
File Details: PDF, 10.95 MB
Year: 2001
Language: english
Contents at a Glance
I 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

Using 11
12

13
Interacting with the User 197
Debugging Your Code 207

III Basic Objects


Dealing with Dates and Times: The Date Object 223

JavaScript
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
Paul McFedries 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
201 W. 103rd Street B JavaScript Reserved Words and Keywords 849
C Working with Regular Expressions 853
Indianapolis, Indiana 46290
Index 873
Special Edition Using JavaScript Acquisitions Editor
Dean Miller
Copyright © 2001 by Que
Development Editor
All rights reserved. No part of this book shall be repro- Sean Dixon
duced, stored in a retrieval system, or transmitted by any Managing Editor
means, electronic, mechanical, photocopying, recording, Thomas F. Hayes
or otherwise, without written permission from the pub- Project Editor
lisher. No patent liability is assumed with respect to the Heather McNeill
use of the information contained herein. Although every
Copy Editor
precaution has been taken in the preparation of this book, Julie McNamee
the publisher and author assume no responsibility for
Indexer
errors or omissions. Nor is any liability assumed for dam-
Tina Trettin
ages resulting from the use of the information contained
herein. Proofreader
Harvey Stanbrough
International Standard Book Number: 0-7897-2576-2
Technical Editor
Library of Congress Catalog Card Number: 2001087883 Jim O’Donnell
Team Coordinator
Printed in the United States of America
Cindy Teeters
First Printing: June 2001 Interior Designer
Ruth Harvey
04 03 02 01 4 3 2 1
Cover Designer
Trademarks Dan Armstrong
Ruth Harvey
All terms mentioned in this book that are known to be
trademarks or service marks have been appropriately capi- Page Layout
Lizbeth Patterson
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.
Contents
Introduction 1 Adding Comments to Your Code 29

What You Need to Know 3 Creating External JavaScript Files 30

How the Book Is Structured 3 Debugging and Troubleshooting Script


Problems 32
Where’s the Code? 6

Conventions Used in This Book 6 II Programming Fundamentals

3 Understanding Variables 39
I Getting Started with JavaScript
What Is a Variable? 40
1 An Overview of JavaScript 11 Declaring a Variable 40
Storing a Value in a Variable 41
JavaScript: Controlling the Machine 12
Using Variables in Statements 42
What Is a Programming Language? 12
Naming Variables: Rules and Best
Is JavaScript Hard to Learn? 14 Practices 44
Rules for Naming Variables 44
What Can You Do with JavaScript? 14 Ideas for Good Variable Names 44

What Can’t You Do with JavaScript? 15 Understanding Literal Data Types 45


Working with Numeric Literals 46
Cross-Browser Concerns 16
Working with String Literals 47
Understand Boolean Literals 49
2 Creating Your First Scripts 17

What Do You Need to Get Started? 18 4 Working with Functions 51


The Text Editor 18
What Is a Function? 52
The Browser 19
The Structure of a Function 52
Basic Script Construction 20
The <script> Tag 20 Where Do You Put a Function? 53
Where Do You Put the Tag? 22
Example #1: Displaying a Message to Using a Function 54
the User 22
Passing Values to Functions 56
More JavaScript Examples 24
Returning a Value from a Function 60
Example #2: Writing Data to the
Page 24 Understanding Local Versus Global
Example #3: A JavaScript Function 26 Variables 61
Example #4: Handling a JavaScript Working with Local Scope 62
Event 28 Working with Global Scope 64
iv Special Edition Using JavaScript

Using Recursive Functions 65 Using Strings in Comparison


Expressions 88
Debugging and Troubleshooting Script Using the Conditional (?:) Operator 89
Problems 68
Avoiding Infinite Recursion 68 Building Logical Expressions 91
The Logical Operators 91
5 Building JavaScript Expressions 71 Using the AND (&&) Operator 91
Using the OR (||) Operator 92
What Is an Expression? 72 Using the NOT (!) Operator 93
Understanding Expression Structure 72 Advanced Notes On the && and ||
Operators 94
Building Numeric Expressions 73
A Quick Look at the Arithmetic Understanding Operator Precedence 96
Operators 73 The Order of Precedence 96
Using the Addition (+) Operator 74 Controlling the Order of Precedence 97
Using the Increment (++) Operator 75
Using the Subtraction and Negation 6 Controlling Your Code I: Testing 101
(-) Operators 76 Using if() to Make True/False
Using the Decrement (--) Operator 78 Decisions 102
Using the Multiplication (*)
Operator 79 Using if()...else to Handle a false
Using the Division (/) Operator 79 Result 103
Using the Modulus (%) Operator 80
Making Multiple Decisions 105
Using the Arithmetic Assignment
Using the AND (??) and OR (||)
Operators 81
Operators 105
Building String Expressions 82 Nesting Multiple if() Statements 106
Using the switch() Statement 107
Building Comparison Expressions 84
The Comparison Operators 84 Debugging and Troubleshooting Script
Using the Equal (==) Operator 85 Problems 110
Using the Not Equal (!=) Operator 85
Using the Greater Than (>) 7 Controlling Your Code II: Looping 111
Operator 86
What Is Looping and Why Does Your
Using the Less Than (<) Operator 86 Code Need It? 112
Using the Greater Than Or Equal (>=)
Operator 86 Using while() Loops 113
Using the Less Than or Equal (<=)
Operator 86 Using for() Loops 115
The Comparison Operators and Data Using do...while() Loops 118
Conversion 87
Using the Identity (===) Operator 88
Using the Non-Identity (!==)
Operator 88
Contents v

Controlling Loop Execution: break and Using the JavaScript Events 147
continue 120 Handling When an Object Gets and
Exiting a Loop: Using the break Loses the Input Focus 148
Statement 120 The Change Event: Handling Modified
Bypassing Loop Statements: Using the Form Data 152
continue Statement 123 Handling Keyboard Events 153
Handling Mouse Events 156
Debugging and Troubleshooting Script
Problems 124 Debugging and Troubleshooting Script
Problems 163
8 Working with Objects 127
10 Working with Arrays 165
What Is an Object? 128
What Is an Array? 166
The JavaScript Object Hierarchy 129
The Window Object and Its Declaring an Array 167
Hierarchy 129
Other Built-In JavaScript Objects 131 Populating an Array with Data 168
Declaring and Populating an Array at
Manipulating Object Properties 132 the Same Time 170
Referencing a Property 132 Using a Loop to Populate an Array 170
Some Objects Are Properties 134 Using a Loop to Work with Array
Changing the Value of a Property 134 Data 172
Using for()...in to Loop Through Creating Multidimensional Arrays 173
Object Properties 135
Using the Array Object 176
Working with Object Methods 137 The Array Object’s Properties 176
Activating a Method 138 The Array Object’s Methods 178

Using with() to Shorten Object Debugging and Troubleshooting Script


Expressions 139 Problems 189

9 Handling Events 141 11 Interacting with the User 197


Understanding Events 142 Why Interact at All? 198

Constructing Event Handlers 142 Displaying Messages Using the alert()


Step 1: Add the Event Handler Setup Method 198
Attribute 142 How the Alert Boxes Appear in
Step 2: Set the Value of the Different Browsers 199
Attribute 143
Asking Questions Using the confirm()
Setting Up Event Handlers as Object Method 201
Properties 145
Using this to Refer to an Event’s Getting Input Using the prompt()
Object 146 Method 202
How the Prompt Boxes Appear in
Different Browsers 203
vi Special Edition Using JavaScript

Debugging and Troubleshooting Script Setting the Date 233


Problems 205 Determining the Day of the Week for
Don’t Overdo It 205 Any Date 234

12 Debugging Your Code 207 Performing Date Calculations 236


Determining a Person’s Age 236
What Is a Bug? 208 Performing Complex Date
Calculations 237
Understanding the Various Types of
Calculating an Age In Weeks, Days, and
Errors 208
So On 237
Syntax Errors 208
Calculating the Days Between Two
Runtime Errors 209
Dates 239
Logic Errors 209
Other Date Object Methods 240
A Debugging Strategy 210
Look for the Top 10 Most Common
14 Working with Numbers: The Math
Errors 210
Object 243
Display Expression Values 212
Display the Values of Object How JavaScript Handles Numbers 244
Properties 216 A Quick Look at the Number
More Debugging Strategies 217 Object 245
The Top 10 Most Common JavaScript Converting Between Strings and
Error Messages 217 Numbers 246
The parseInt() Function 247
The parseFloat() Function 247
III Basic Objects The eval() Function 248

13 Dealing with Dates and Times: The Date The Math Object 249
Object 223
Properties of the Math Object 249
Understanding JavaScript Dates 224
Methods of the Math Object 250
Arguments Used with the Date Rounding Numbers 251
Object 224 Rounding a Number to a Specified
Number of Decimals 252
Working with the Date Object 225
Performing Financial Calculations 253
Specifying the Current Date and
Generating Random Numbers 260
Time 225
Specifying Any Date and Time 225
15 Manipulating Text: The String Object 265
Extracting Information About a Date 227
Strings and the String Object 266
Converting getMonth() into a Month
Name 230 Determining the Length of a String 266
Converting getDay() into a Day
Name 232
Contents vii

String Object Methods 268 IV Working with Browser Windows


Formatting Strings 268
Finding Substrings 271 17 Understanding the Window Object 319
Methods That Extract Substrings
274 Revisiting the Window Object
Hierarchy 320
A Few More String Object
Methods 281 Referencing the Window Object 321
Programming a Library of Common Window Dimensions and the Screen
String Functions 283 Object 322
Extracting Characters from the Left:
The left() Method 284 Displaying Messages In the Status Bar 325
Extracting Characters from the Right: Displaying a Custom Link Message 325
The right() Method 284 Setting Up a Default Status Bar
Trimming Extra Spaces: The trim() Message 327
Method 285
Working with JavaScript Timeouts and
Converting a String to Title Case: The
Intervals 328
titleCase() Method 287
Using a Timeout to Perform a Future
Replacing One Substring with
Action Once 328
Another 289
Using an Interval to Perform a Future
Formatting a Number with Thousands
Action Repeatedly 331
Separators 291
Emulating setInterval() with
Padding a Number with Zeros 293
setTimeout() 332
Creating a Scrolling Status Bar
16 Controlling the Browser: The Navigator
Message 333
Object 297

About the Navigator Object 298 18 Opening, Moving, and Sizing Windows 337

Determining the User’s Browser Opening a Window 338


Information 304 The JavaScript Way: The window.open()
Determining the Browser Name 304 Method 338
Determining the Browser Version 305 The Simplest window.open() Method
Understanding the userAgent Syntax 338
Property 307 Controlling the Size and Position of the
Determining the Browser Name, New Window 341
Part 2 309 Displaying Toolbars, Menu Bars and
Determining the Operating Other Window “Chrome” 344
System 311 Referencing the Page That Opened a
Putting It All Together: The Browser Window 347
Sniffer 313
Closing a Window 349
viii Special Edition Using JavaScript

Moving a Window 351 ”Deframing” a Page: Getting Out of


Moving a Window to a Specific Someone Else’s Frames 395
Spot 351 ”Reframing” a Page: Putting a Child
Moving a Window by a Specified Page Back Inside a Frameset 397
Amount 355 Working with Another Frame’s Variables
and Functions 399
Resizing a Window 359 Synchronizing Frame Loading 401
Resizing a Window to a Specific
Size 359 21 JavaScript Project: Setting Up a Password-
Resizing a Window by a Specified Protected Page 405
Amount 360
Web Page Security Issues 406
19 JavaScript Surfing: The Location and
A First Attempt at Password
History Objects 361
Protection 406
Surfing Under Script Control 362 Prompting for a Password 406
Converting the Password and Filename
Using the Location Property to Change into Codes 408
the Displayed Page 362
Location Object Properties: 365 The First Real Solution: A Trick for Hiding
Surfing Using the Location Object’s the Password 411
Properties 365 Trying Out the Trick 411
Using search to Pass a Parameter to Making the Script a Bit More User-
Another Web Page 369 Friendly 412
Methods of the Location Object 372
Solving the “404 Not Found”
Programmed Surfing with the History Problem 413
Object 374 Handling Multiple Users and
Methods of the History Object 375 Passwords 418

20 Manipulating Frames 377 Debugging and Troubleshooting Script


Problems 423
Understanding Frame References 378
Parent-to-Child References 379
Child-to-Parent References 380 V Working with the Document Object
Child-to-Child References 381
Referencing Nested Frames 383 22 Understanding the Document Object 427
The top Property 391
Structure of the Document Object 428
Programming Frames 392
Properties of the Document Object 428
Loading a Page into a Frame 392
Updating Multiple Frames with One Changing Document Colors 430
Link 393 Using Color Names 431
Navigating to the Top and Bottom of a Using RGB Values 434
Frame 394
Contents ix

Methods of the Document Object 437 25 Creating and Using Cookies 495

Writing Data to the Page 437 Saving State: The Need for Truly Global
Writing to a Document at Startup 438 Variables 496
Writing Browser-Specific Code 440 What is a Cookie? 496
Writing to a Document In Another Advantages of Cookies 497
Window 442 Disadvantages of Cookies 498

Setting Cookie Data 499


23 Programming Links and Anchors 447
The Simplest Case: Setting the Cookie
Working with the Link Object 448 Name and Value 499
Using Functions in Place of URLs in a Getting the Cookie Value 500
Link 448 Handling Multiple Cookies 501
Referencing a Link Object 449 Adding an Expiration Date 504
Link Object Properties 449 Specifying the Path 505
Link Object Events 455 Setting Other Cookie Data 506
Handling All the Cookie
Working with the Anchor Object 462 Parameters 507
Referencing an Anchor Object 462 Deleting a Cookie 510
Anchor Object Properties 462
Advanced Cookie Operations 511
24 Working with Images and Storing Multiple Values in a Single
Mouseovers 467 Cookie 511
Encoding Cookie Values 513
Working with the Image Object 468 Encrypting Cookie Values 516
Referencing an Image Object 468
Properties of the Image Object 469 Debugging and Troubleshooting Script
Changing the Image Source 470 Problems 520
Cycling Through a Series of Images Building a Stronger Key 520
470
Creating a “Running” Digital Clock 26 JavaScript Project: Creating a Navigation
472 Tree 523
Preloading Images 475
The Need for Navigation 524
Preloading Images for Animation
476 Stage 1: Designing and Creating the Menu
Loading an Image into a Custom-Sized Objects 525
Window 479
Handling Image Object Events 481 Stage 2: Writing a Basic Menu 530

Creating Mouseover Effects 487 Stage 3: Expanding and Collapsing the


The Simplest Mouseover 487 Menu Items 534
Preloading Mouseover Images 490 Stage 3: Expanding and Collapsing the
Using a Text Link Mouseover to Menu Items 535
Change an Image 492
Stage 4: Adding Graphics and Other
Interface Enhancements 538
x Special Edition Using JavaScript

VI Working with Forms Programming Checkboxes 585


Getting the Checkbox State 586
27 Understanding the Form Object 549 Setting the Checkbox State 586
Using a Checkbox to Disable Form
Structure of the Form Object 550 Fields 587
Referencing a Form Object 550 Controlling the Number of Activated
Form Object Properties 551 Checkboxes 588
Understanding Form Fields 551 Programming Radio Buttons 590
Referencing a Form Field 552 Referencing Radio Buttons 591
Common Form Field Properties 553 Getting a Radio Button State 592
Looping Through Form Fields 554 Setting the Radio Button State 594
Passing Form and Field Objects to a
Function 555 Programming Selection Lists 594
The Select Object 595
Programming Buttons 556 The Option Object 595
Accepting or Rejecting a Submit 556 Referencing an Option In a Selection
Accepting or Rejecting a Reset 559 List 596
Using a Button to Process Other Getting the Currently Selected List
Code 560 Option 596
Forcing a Submit or Reset: The sub- Getting Multiple Selected Options 597
mit() and reset() Methods 562 Setting the Selected List Option 598
Restricting the Number of Form Creating a Navigation List 599
Submissions 564 Modifying a List On-the-Fly 601

28 Programming Form Fields 569 29 Performing Form Validation 605


Now For Some Real Form The Need for Browser-Based
Programming 570 Validation 606
Programming Text Fields 570 Displaying the Form Data for
The Text Object 570 Confirmation 607
The Textarea Object 571
The Password Object 572 Making Form Fields Mandatory 612
The FileUpload Object 572 First, a Trick: Adding Custom
The Hidden Object 573 Properties to an Object 613
Getting a Text Field Value 574 Checking for Empty Fields 615
Setting a Text Field Value 576 Checking for Fields that Contain Only
A More Ambitious Example: Whitespace Characters 617
A Mortgage Calculator 578
Validating the Field Data Type 618
Making a Text Field Read-Only 582
Checking for Alphabetic Data 619
Checking for Integer Data 620
Checking for Signed Integer Data 621
Checking for Floating-Point Data 622
Contents xi

Checking for Invalid Data 624 VII Working with Dynamic HTML
Checking a Numeric Range 625
Removing Extraneous Characters from 31 A Brief Overview of Dynamic HTML 673
a Field 628
Checking Alphanumeric Data Against a The Need for Truly Dynamic Pages 674
Mask 631 Dynamic HTML: Scripting for Control
Checking an E-mail Address 634 Freaks 674

30 JavaScript Project: Creating a Shopping DHTML Today: A Mess! 675


Cart 637
The Big DHTML Picture 676
Making the Move to E-Commerce 638
An Introduction to the Document Object
Creating the Project Data 638 Model 676
Designing the Data 638
The DOM: A Hierarchy of Nodes 679
Creating the Database Using
JavaScript 640
32 Version 5 DHTML: The W3C’s Document
An Overview of the Project 644 Object Model 683
Customizing This Project for Your
Dealing with Nodes in the DOM 684
Own Use 646
Specifying a Node 684
Setting Up Your Store 646 Getting Node Information 687
Working with Elements 688
Understanding the Shopping Cart 649 Working with Tag Attributes 691
Using the Shopping Cart 650 Working with Styles 694
Creating the Cart On-the-Fly Using Working with Text Nodes 697
JavaScript 650 An Example: A Text Fader 699
The Shopping Cart’s Buttons 653
Changing the Structure of the Document
Understanding the Personal Details Hierarchy 704
Page 655 Creating an Element 704
Initializing the Personal Details Creating a Text Node 705
Page 658 Appending a Child Node 705
Validating the Personal Details 660 Inserting a Child Node 709
Replacing a Child Node 713
Understanding the Credit Card Details
Cloning a Child Node 715
Page 662
Removing a Child Node 718
Writing the Invoice 662
Initializing and Validating the Credit
Card Details 666
xii Special Edition Using JavaScript

33 Version 4 DHTML: Proprietary Object 35 Cross-Browser DHTML Examples 769


Models 721
Some Notes Before We Begin 770
The Pre-DOM Dark Ages 722
Cross-Browser DHTML Text
The Internet Explorer 4 DHTML Examples 770
Document Object Model 722 A Cross-Browser Tooltip 770
Specifying Elements 723 Scrolling Text Horizontally 773
Getting and Setting Tag Attribute Scrolling Text Vertically 785
Values 725
Other DHTML DOM and W3C Cross-Browser DHTML Image
Examples 794
DOM Equivalents 725
Creating a Logo That Stays in Place as
Working with Text 726
the User Scrolls 794
The Netscape Navigator 4 Document Setting Up a Cross-Browser DHTML
Object Model 727 Slide Show 796
Programming Layers 728

34 Cross-Browser Solutions: Detection and VIII Appendixes


Generic Functions 731
A JavaScript Tools for Debugging Scripts 831
Cross-Browser Issues 732
What Does “Cross-Browser” Using the Microsoft Script Debugger 832
Mean? 732 Pausing a Script 832
Handling Different Browsers 733 Stepping Through a Script 836
Monitoring Script Values 837
Detecting the User’s Browser 735 Executing Statements in the Command
Using Browser Version Detection 735 Window 838
Using Object Detection 737
Using Netscape’s JavaScript Debugger 838
Creating a Custom Object Front-End 739 Pausing a Script 839
Examining the Object 739 Stepping Through a Script 844
Cross-Browser Style References 741 Monitoring Script Values 845
Creating the Custom Objects 742
Using a Custom Object 746 B JavaScript Reserved Words and
Defining the Custom Object Keywords 849
Methods 746
Other Cross-Browser Functions 763 JavaScript Reserved Words 850

JavaScript Keywords 850


Contents xiii

C Working with Regular Expressions 853 Using Regular Expressions in Your


JavaScript Code 865
Pattern Matching the String Object Checking the Pattern Using the test()
Way 854 Method 866
The search() Method 868
Pattern Matching the Regular Expression
The replace() Method 870
Way 854
Building Regular Expressions 854
Special Symbols Used in Regular
Index 873
Expressions 855
Summarizing the Regular Expression
Symbols 863
Example: Matching an E-mail
Address 864
xiv Special Edition Using JavaScript

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 every-
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. Paul
has written over three dozen books that have sold more than two million copies worldwide,
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:
[email protected]

Note, however, that due to time constraints, Paul regrets that he cannot provide JavaScript
technical support or custom programming.
Dedication
To 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 to
make 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 to
the folks I worked with directly: Dean Miller, Development Editor Sean Dixon, Project
Editor Heather McNeill, and Technical Editor Jim O’Donnell. And, last but proverbially
not least, I’d like to thank all the thousands of readers of my Web page book who sent me
their JavaScript suggestions and experiences. I couldn’t have written this book without you.
INTRODUCTION

In 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
2 Introduction

When 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 take
long 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 any-
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 democratized
and was no longer defined as the sole province of governments and mega-corporations.
Then reality set in.
People soon realized that merely building a Web site wasn’t enough to attract “eyeballs,” as
the marketers say. A site had to have interesting, useful, or fun content, or people would
stay away in droves. Not only that, but this good content had to be combined with a solid
site design, which meant that Web designers needed a thorough knowledge of HTML and
good design skills.
But, alas, eventually even all that was not enough. To make their Web sites work with the
world’s different browsers, to make their sites easy to navigate, and to give their sites those
extra 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 put
together a world-class Web site unless you have some scripting prowess in your site design
toolkit. You need to know how to script your way out of the basic problems that afflict most
sites, and how to use scripts to go beyond the inherent limitations of HTML. And it isn’t
enough just to copy the generic scripts that are available on the Web and paste them into
your pages. First of all, most of those scripts are very poorly written, and second of all they
invariably 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 are
suited to your site and your content. My aim is to show you that JavaScript isn’t hard to
learn, and that even the most inveterate non-programmer can learn how to put together
scripts that will amaze their friends (and themselves).
How the Book is Structured 3

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 file
system 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 sure
what 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 “hack-
ers” and other technowizards. That made some sense because the programming languages
they were using—with bizarre names such as C++ and Fortran—were exceedingly difficult
to learn, and even harder 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, Visual
Basic, 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 past
the 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 con-
cepts, I’m sorry but you won’t find it here. My philosophy throughout this book is “It’s the
4 Introduction

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 that
any verbose explanations I could muster (and believe me, I can muster verbosity with the
best).
How you approach this book depends on your current level of JavaScript expertise (or lack
thereof):
■ If you’re just starting out, begin at the beginning with Chapter 1 and work at your own
pace 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 fast
look at Chapter 2, and then working quickly through the material in Part II. You’ll
then 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 skim
through 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 can
sample as your programming taste buds dictate.

Just so you know what to expect and to help you plan your forays into the book, the next
few 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,” gives
you the big JavaScript picture and explains why JavaScript is such a fundamental tool for
Web designers. If you’re new to programming, you’ll appreciate my explanation of just
what a programming language is. Chapter 2, “Creating Your First Scripts,” gets down to
the coding brass tacks by showing you how to add scripts to your pages and by taking you
step-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 appropriate
because 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 (the
topics 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 impor-
tant techniques for getting your scripts to interact with your site visitors and how to trouble-
shoot (debug in programming lingo) script problems.
How the Book is Structured 5

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 with
dates 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 perform
lots 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 used
JavaScript 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 fig-
ure out some interesting information about the browser that a site visitor is using (such as
the name of the browser, its version number, and what operating system it’s running on).

Part IV—Working with Browser Windows


Your scripting moves into a higher gear here in Part IV. That’s because these five chapters
show you how to use JavaScript to manipulate the user’s actual browser window. You’ll learn
how to display messages in the status bar, how to get the dimensions of the window, how to
open new windows, and how to close them when they’ve served their purpose. I also show
you 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 five
chapters 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 docu-
ment, on-the-fly! If you can’t wait to learn how to do those fun “mouseover” effects that are
featured on many sites, then Chapter 24, “Working with Images and Mouseovers,” is the
place to go. I also show you how to work with cookies, and I close with another project: a
navigation “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, check
boxes, 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 phone
numbers and email addresses, and lots more. I also take you through a complete shopping
cart script.
6 Introduction

Part 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 create
many interesting effects, including text that scrolls across the page, image slide shows, and
lots more.

Part VIII—Appendixes
The book winds up with three appendixes. Appendix A, “JavaScript Tools for Debugging
Scripts,” shows you how to use Microsoft’s Script Debugger and Netscape’s JavaScript
Debugger, 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 JavaScript
words 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 useful
world 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 every
last 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:

Convention Meaning
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 help
you avoid problems or that should be considered in using the described features.
Conventions Used in This Book 7

Tip paragraphs suggest easier or alternative methods of executing a procedure. Tips


introduce techniques applied by seasoned developers to simplify tasks or to make
design and implementation decisions that produce robust and maintainable systems.

Cautions warn you of hazardous procedures (for example, activities that delete files).

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.
PART
I
Getting Started with JavaScript

1 An Overview of JavaScript 11

2 Creating Your First Scripts 17


CHAPTER
1
An Overview of JavaScript
In 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
12 Chapter 1 An Overview of JavaScript

JavaScript: Controlling the Machine


When a Web browser is confronted with an HTML file, it goes through a simple but
tedious process: it reads the file one line at a time, starting from (usually) the <html> tag at
the top and finishing with the </html> tag at the bottom. Along the way, it might have to
break 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 Web
server to ship out a copy of the graphics file specified in the src attribute.
The point here is that, at its core, a Web browser is really just a page-reading machine that
doesn’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 is
that they quickly realize they have control over this page-reading machine. Slap some text
between a <b> tag and its corresponding </b> end tag and the browser dutifully displays the
text as bold. Create a <table> structure and the browser displays your formerly haphazard
text 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 next
level. Imagine if, instead of ordering the machine to process mere tags and text, you could
issue much more sophisticated orders that could actually control the inner workings of the
page-reading machine. Who wouldn’t want that?
Well, that’s the premise behind JavaScript. It’s essentially just a collection of commands that
you can wield to control the browser. Like HTML tags, JavaScript commands are inserted
directly into the Web page file. When the browser does its line-by-line reading of the file
and 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 page-
reading machine is much greater than what you get with HTML tags. The reason is that
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 this
term, you need look no further than the language you use to speak and write. At its most
fundamental 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 people
who 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.
What Is a Programming Language? 13

■ 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- Part
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”
I
Ch
is gibberish.
1
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 window refers 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 window and open() like so:
window.open(). If you use open().window or window open or 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
14 Chapter 1 An Overview of JavaScript

some extra things that need to go along with the command for it to work properly. I tell you
about 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 as
intimidating 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 complex
pages. 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 not
going to tell you that JavaScript is as easy to learn as HTML. That would be a bald-faced
lie. However, I will tell you that there is nothing inherently difficult about JavaScript. Using
our 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 the
Web page equivalent of a roadblock. That is, there’s a certain thing they want to do, but
they 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 using
HTML; you have to use JavaScript instead.” I then supply them with a bit of code that they
can “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 to
move from “cut-and-paste” to “code-and-load.” That is, I hope you’ll end up being able to
create 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 you
can do with it:
What Can’t You Do with JavaScript? 15

■ 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. Part
■ You can calculate loan and mortgage payments and other financial data. I
■ You can determine not only the name of the user’s browser, but also its version number Ch
and the operating system it’s running on.
■ You can work with extra browser windows, which means you can open them, resize
1
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.
16 Chapter 1 An Overview of JavaScript

Cross-Browser Concerns
I mentioned earlier that your goal as a JavaScript programmer is to structure the language’s
words and rules in such a way that the browser’s page-reading machine understands and
carries out your commands. That sounds like a straightforward idea, but there’s a pretty
big fly in the JavaScript ointment: browser compatibility. As you probably know from your
HTML coding—or, even more so, from your style sheet coding—there are three problems
that 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. Some
browsers have their own proprietary tags (such as Internet Explorer’s <marquee> tag and
Netscape’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’t
support 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, under-
stood by the page-reading machine are slightly different from one browser (and one browser
version) to the next. The good news is that these differences aren’t major, so most of your
code will run fine in most browsers. However, it’s important that you never assume that just
because a script is working in one browser that it will automatically work in all browsers. In
the same way that a good Web page designer checks out his pages in different browsers and
browser 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.
CHAPTER
2
Creating Your First Scripts
In 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
18 Chapter 2 Creating Your First Scripts

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 are
not only short, but few in number. In fact, you really need only two things, both of which
are free: a text editor to enter the tags and text, and a browser to view the results. (You’ll
also need a Web server to host the finished pages, but the server isn’t necessary when you’re
creating 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 respectable
Web pages without them.
The basic requirements for JavaScript programming are exactly the same as for HTML: a
text editor and a browser. Again, there are programs available to help you write and test
your scripts, but you don’t need them.
➔ For a discussion of JavaScript debugging tools, see Appendix A, “JavaScript Tools for Debugging
Scripts,” p. 831.

For the purposes of this book, you don’t need a Web host because it’s possible to write
and test your scripts on your computer without being connected to the Internet.

The Text Editor


Any text editor will do for writing scripts. If you run some flavor of Windows, the Notepad
program is perfectly acceptable, as is the EDIT.COM DOS text editor that ships with
Windows. 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 the
format of the word-processing program. To illustrate how you do this, here’s the procedure
for saving a WordPad (the word processor that comes with Windows) document as a plain
text 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.

Figure 2.1
If you’re using a word
processor, be sure to
save the file using a
plain text format.
What Do You Need to Get Started? 19

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 .htm or .html extension.
• 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.
Part
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 I
varies from program to program. In Microsoft Word, for example, the item you choose is Ch
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).
2

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.

Figure 2.2
This page from my
Web site gives you a
browser breakdown of
the people who visit
my pages.
20 Chapter 2 Creating Your First Scripts

If you have just one computer, you should install only the most popular browsers. Since you
can 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 popular
browsers. Over time, keep an eye on these usage statistics so that you always know what
people 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’ll
see a working example that you can try out, and later you’ll move on to other examples that
illustrate 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 associ-
ated </script> end tag. For a simple script, the tag is embellished with both the language
attribute, which is set to the value “JavaScript”, and the type attribute, which is set to
“text/javascript”:

<script language=”JavaScript” type=”text/javascript”>


JavaScript statements go here
</script>

In HTML 4.0, the language attribute 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
type attribute).

You’ll almost always set the <script> tag’s language attribute to “JavaScript”. However, there
are other values that correspond to the various versions of JavaScript that have appeared over
the years. The original JavaScript was supported by Netscape 2 and Internet Explorer 3. Here
are the initial browser versions that supported subsequent JavaScript releases:
JavaScript 1.1 Netscape 3.01
JavaScript 1.2 Internet Explorer 4.01, Netscape 4.05
JavaScript 1.3 Internet Explorer 5.0, Netscape 4.61
JavaScript 1.4 Mozilla 5.0 Alpha Pre-Release M6
JavaScript 1.5 Internet Explorer 5.5, Netscape 6 Beta 1
Basic Script Construction 21

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 language value, there’s no space between JavaScript and the version
number.) The browser checks the JavaScript version (1.1, in the previous example) and, if Part
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.
I
Ch

Handling Browsers That Don’t Support JavaScript 2


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:
<noscript>
Your browser doesn’t support JavaScript, or it has JavaScript turned off.
<p>
Try this <a href=”no-js.html”>non-JavaScript version</a> of the page.
</noscript>
22 Chapter 2 Creating Your First Scripts

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 -->
</script>
</head>
<body>
</body>
</html>

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 positioned
within 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 attributes
directly 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 alto-
gether and just enter your statements in the file.

➔ I talk about external JavaScript files later in this chapter; see “Creating External JavaScript Files,” p. 30.

It’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 put
one <script> block within another one.

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 shows
the script within an HTML file.
Basic Script Construction 23

All the code listings in this chapter are available online from my Web site at the follow-
ing address:
http://www.mcfedries.com/UsingJavaScript/

Listing 2.1 Displaying a Message to the User


<html>
Part
<head>
<title>Listing 2.1: Displaying a Message to the User</title>
I
Ch
<script language=”JavaScript” type=”text/javascript”>
<!-- 2
alert(“Hello World Wide Web!”)
//-->
</script>

</head>
<body>
</body>
</html>

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.
24 Chapter 2 Creating Your First Scripts

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.

Figure 2.3
This “alert” message
appears when you
open the HTML file
containing the exam-
ple script.

➔ 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 or
more JavaScript statements are coming, and it automatically executes those statements, in
order, 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 to
give you hints about the kinds of things you can do with JavaScript. To that end, this section
presents 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 even
HTML tags to the Web page on-the-fly. That is, the text (or whatever) gets inserted into
the page when a Web browser loads the page. What good is that? For one thing, it’s ideal
for time-sensitive data. For example, you might want to display the date and time that a
Web page was last modified so that visitors know how old (or new) the page is. Listing 2.2
shows just such a script.
More JavaScript Examples 25

Listing 2.2 Writing Data to the Page


<html>
<head>
<title>Listing 2.2: Writing Data to the Page</title>
</head>

<body>
This is a regular line of text.<br>
Part
<script language=”JavaScript” type=”text/javascript”>
<!-- I
document.write(“This page was last modified on “ + document.lastModified) Ch
//-->
</script> 2
<br>This is another line of regular text.
</body>
</html>

All the code listings in this book are available on my Web site. The address for each
page is as follows:
http://www.mcfedries.com/UsingJavaScript/Number.htm
Here, Number is the listing number. For example, you can find the page with the code
from Listing 2.2 here:
http://www.mcfedries.com/UsingJavaScript/2.2.htm

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.lastModified portion 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.
26 Chapter 2 Creating Your First Scripts

Example #3: A JavaScript Function


The first two examples showed you statements that the browser executed as soon as it loaded
the page. There will be plenty of times when you don’t want your JavaScript statements to
execute right away. For example, a script that verifies form data shouldn’t run until the user
attempts to submit the form. To control when the browser runs a script, you first need to
build a function, which is a self-contained group of statements. Here’s the basic layout:
function function_name() {
JavaScript statements go here
}

Note that you need to change function_name to whatever name you want to give to your
function (don’t use any spaces in the name). Note, too, the braces—{ and }—that are used to
enclose the statements within the function (this is called a statement block). This enables the
browser to differentiate between the function’s statements and other statements within the
script. Here’s an example function:
function display_time() {
var now = new Date()
var hours = now.getHours()
var minutes = now.getMinutes()
var seconds = now.getSeconds()
var current_time = hours + “:” + minutes + “:” + seconds
alert(“The current time where you are is “ + current_time)
}

The specifics of what this function does aren’t important right now. The function’s purpose
is to display the current time to the user. The important thing to remember is that if you
insert this function within a script on your page, the browser won’t run it. That’s because
the browser more or less ignores any function until something tells the browser to run the
function. In programming parlance, this is known as calling the function. When the function
is called, the browser locates it within the script and then runs through the function line by
line, executing each statement in turn.
➔ To learn about working with times as well as dates, see Chapter 13, “Dealing with Dates and Times: The
Date Object,” p. 223.

As I mentioned earlier that it’s okay to include multiple <script> blocks within a sin-
gle page. It’s also okay to include multiple functions within a single <script> block,
or to sprinkle functions throughout multiple <script> blocks. However, every func-
tion on the page must have a unique name. If you have two or more functions with the
same name in one page, you’ll generate an error.

There are various ways to call a function, but the most straightforward is by adding a statement
that consists of nothing but the function name, followed by parentheses, as in this example:
display_time()

Listing 2.3 shows the code for a page with a script that asks the user if he wants to see the
time and, if he does, calls the display_time() function.
More JavaScript Examples 27

Listing 2.3. Calling a Function


<html>
<head>
<title>Listing 2.3: A JavaScript Function</title>

<script language=”JavaScript” type=”text/javascript”>


<!--
if (confirm(“Do you want to know the time?”)) {
display_time() Part
}
I
function display_time() { Ch
var now = new Date()
var hours = now.getHours()
var minutes = now.getMinutes()
2
var seconds = now.getSeconds()
var current_time = hours + “:” + minutes + “:” + seconds
alert(“The current time where you are is “ + current_time)
}
//-->
</script>

</head>
<body>
</body>
</html>

The key bit of code here is the following:


if (confirm(“Do you want to know the time?”)) {
display_time()
}

You use the JavaScript confirm() method to display a question to the user, which he answers
by clicking OK or Cancel. The if() statement checks the clicked button. If it was OK, then
the display_time() function is called. Figure 2.5 illustrates this by showing two browsers: The
top browser (Netscape) has just loaded the page and it displays the dialog box with the ques-
tion; the bottom browser (Internet Explorer) shows the alert box that appears if you click OK.
➔ To learn the ins and outs of the confirm() method, see “Asking Questions Using the confirm()
Method,” p. 200.
➔ For more about the if() statement, see “Using if() to Make True/False Decisions,” p. 102.
➔ I talk about functions in more detail later in the book; see Chapter 4, “Working with Functions,” p. 51.

One of the cardinal rules of JavaScript programming is “one statement, one line.” That
is, each statement must appear on only a single line, and there should be no more
than one statement on each line. I said “should” in the second part of the previous
sentence because it is possible to put multiple statements on a single line, as long as
you separate each statement with a semicolon (;). There are rare times when this is
necessary, but you should avoid it for the bulk of your programming because multiple-
statement lines are difficult to read and to troubleshoot.
28 Chapter 2 Creating Your First Scripts

Figure 2.5
The top browser
shows the question
being displayed, and
the bottom browser
shows what happens if
you click OK.

Example #4: Handling a JavaScript Event


In the JavaScript world, an event is an action that’s triggered automatically as the result of
some other action. For example, events occur—fire, in programming lingo—when a page
loads, when the user positions her mouse pointer over a link, and when the user submits a
form. As the programmer, you can create a function called an event handler that is executed
automatically when the associated event fires. You set up an event handler by first associat-
ing the name of a function with the event itself. Here’s the general syntax:
EventName=”function_name()”

Here, EventName is the name of the event and function_name is the name of the function
that you want the browser to run when the event fires. For example, an event fires when the
user leaves a page (either by surfing to a different page or by shutting down the browser).
This is called the Unload event, and in this case, you put the onUnload event handler setup
statement within the <body> tag, like this:
<body onUnload=”say_goodbye()”>

This tells the browser to run the say_goodbye() function when the user leaves the page.
Listing 2.4 shows the full HTML file, including the say_goodbye() function (which displays
a simple alert() message).

Listing 2.4 Handling a JavaScript Event


<html>
<head>
<title>Listing 2.4: Handling a JavaScript Event</title>

<script language=”JavaScript” type=”text/javascript”>


<!--
Adding Comments to Your Code 29

function say_goodbye() {
alert(“Thanks for visiting my page. Y’all come back now, yuh hear?”)
}
//-->
</script>

</head>

<body onUnload=”say_goodbye()”>
</body> Part
</html>
I
Ch
Figure 2.6 shows the message that appears.
➔ For a lot more on events, see Chapter 9, “Handling Events,” p. 141. 2

If your event handler function consists of just a single statement (as does the
say_goodbye() function in Listing 2.4), you can bypass the function altogether and
just put the statement directly in the event setup line, as shown here:
<body onUnload=”alert(‘Thanks for visiting my page.’)”>
Note the use of single quotation marks (‘) within the alert() method. You need to
use them because the alert() statement itself is surrounded by double quotation
marks (“), so using them within the alert() statement would confuse the browser
(and probably generate an error).

Figure 2.6.
When you leave the
page, the Unload
event fires and this
message is displayed.

Adding Comments to Your Code


A script or function that consists of just a few lines is usually easy to read and understand.
However, your scripts won’t stay that simple for long, and these longer and more complex
creations will be correspondingly more difficult to read. (This is particularly true if you’re
looking at the code a few weeks or months after you first programmed it.) To help you deci-
pher your code, it’s good programming practice to make liberal use of comments throughout
the script. A comment is text—it could be 1 line or 10 lines—that describes or explains a
statement or group of statements. Comments are ignored by the browser, so you can add as
many as you deem necessary.
30 Chapter 2 Creating Your First Scripts

For short, single-line comments, use the double-slash (//) that I mentioned briefly earlier in
this chapter. Put the // at the beginning of the line, and then type in your comment after it.
Here’s an example:
// Ask the user if he wants to see the time
if (confirm(“Do you want to know the time?”)) {
// If he clicks OK, call the display_time() function
display_time()
}

You can also use // comments for two or three lines of text. If you have more than that,
however, then you’re better off using multiple-line comments that begin with the /* symbol
and end with the */ symbol. Here’s an example:
/* This script demonstrates JavaScript functions
by first asking the user if she wants to see the
current time. If she does (that is, if she clicks
OK), then the display_time() function is called.

This script is Copyright 2001 Paul McFedries.


*/

Creating External JavaScript Files


Putting a script inside the page header isn’t a problem if the script is relatively short.
However, if your script (or scripts) take up dozens or hundreds of lines, it can make your
HTML code look cluttered. Another problem you might run into is needing to use the
same function (or functions) on multiple pages. Sure, you can just copy the code into each
page that requires it, but if you make changes down the road, you need to update every
page that uses the code.
The solution to both problems is to move the code out of the HTML file and into an
external JavaScript file. This reduces the JavaScript presence in the HTML file to a single
line (as you’ll see shortly), and it means that you can update the code by editing only the
external file.
Here are some things to note about using an external JavaScript file:
■ The file must use a plain text format.
■ Use the .js extension when you name the file.
■ Don’t use the <script> tag within the external JavaScript file. Just enter your statements
and functions exactly as you would within an HTML file.
■ The rules for when the browser executes statements within an external file are identical
to those used for statements within an HTML file. That is, statements outside of func-
tions are executed automatically when the page loads, and statements within a function
aren’t executed until the function is called.
Another Random Scribd Document
with Unrelated Content
Johnston’s Army, 131, 164
Jolley,
Bryant, 184
Donald J., 207
Henry B. M., 166 217
William J., 166
Jones,
Col. C. J., (Buffalo Jones) (Buffalo Bill) 139, 192, 193
Kumen, 183
Randall L., 202, 203, 205
Stephen V., 185
Jordan River, 153
Judd, Zadock, 139

K
Kaibab,
Indian derivation of name, 114
Land and Cattle Company, 191
National Forest, 164, 189-194
buggy driven to, 191
established, 191
stocked with cattle and horses, 190
used by English aristocracy, 190, 191
Plateau, 189
tribe, (Indian), 117
Kaibabit Indians, survivors of, 122
Kai-ne-sava, Indian spirit, 112, 113
Kanab,
Creek, 166
fort, 180, 181
Indian derivation of name, 114
Trail, dedicated, 208
Utah, 166, 180, 181
erosion at, 182
raided by Indians, 168, 169
region explored, 177
resettled, 179, 180
Wash, 182
Kanarra,
Indian chief, 141
source of name, 114
Utah, 133
Kane County,
expanded, 179-182
explored and settled, 164-166
protected by militia, 167
Kane Springs, 189
Kenner, Dr. S. A., 151, 153
King, Wesley, 188
Klapper, Charlie, 151, 153
Klingensmith, Philip, 148
Knell, Benjamin, 144
Knight,
Jesse, 192
Samuel, 144, 145
Knives, skinning, 118
Kolob Promontory, 133

L
Lady Mountain, Zion Canyon, 206
Lakes, (see names)
Lamb, Ed., Jr., 191
Lances, Indian, 121
Lane, Franklin K., 196
Langston,
Clarinda, 163
John, 153
LaVerkin Creek, 124, 128
promontory, 133
Leany, Hyrum, 119
Lee,
John D., 135, 148, 179
in Kaibab region, 189
leads exploration of Virgin River, 139-141
leads southern settlement, 137-144
ranch, 181
raided, 172
settles at Ash Creek, 143
Lee’s Ferry, Arizona, 166
Lemon, James, 151
Levearskin (LaVerkin) River, 139
Lewis, David, 145
Liberty pole, 134
Limestone, 133
Lion, mountain, captured, 192, 195
Little, James, 177
Littlefield, David O., 182
Little Salt Lake, 135
Livestock,
in Kaibab Forest, 190, 191
stolen by Indians, 166-179
Logan-St. George highway, 194
Long Valley, 142, 166
abandoned, 171, 172
Canyon, 142
Utah, 179, 181
Louise, Princess, 208
Lost River, 127
Lott, John, 144
Lumber transported, 161-164
Lumbering, 142
Lunt, Henry W., 197-199

M
Mail cable, 162
Maize, 117, 118
Mammoth Creek, 142
Manderfield, J. H., 198
Mangum, John (Mangram), 179
Manly, William Lewis, 132
Manti, Utah, 132
Marble Gorge Bridge of the Grand Canyon of Arizona, 209
Marysvale Canyon, 127 218
Marshall, E. J., Co., 191
Massacre, 170
Mather, Stephen T., 197, 202, 206, 208
Maxwell, W. B., 166, 171
Maxwell’s ranch raided, 172
Mabey, Charles R., 205
Mayo, Tommy (Indian), 114
McArthur, D. D., 174
McConnell, Jehiel, 179
McDonald,
Graham, 192, 193
Thomas, 208
McFate,
Jim, 153
Joe, 153
McKinnon, Major, 191
McIntyre, Robert, 168-169, 189
Means, Howard C., 205, 206
Measles among the Indians, 122
Meeks, Priddy, 142, 166
Merriam, C. H., 127
Mestes Expedition, 126
Mexican War, 130
Mill,
cotton, 154
flour, 152
molasses, 153
saw, 181
steam, 190
shingle, 163
Military posts established in Southern Utah, 173
Militia, in Southern Utah, organized against Indians, 137, 167-176
Millard County, 115
Millett,
Alma, 151
Joseph, 153
Milmey, Lord, 191
Minerals, iron, 133
Mission sites located by Escalante, 125, 126
Missionaries, Mormon, 144-149
Missionary expedition, between the Virgin and Colorado Rivers, 164-
166
Mitchell, Dr. Charles, 182
Moccasin, Arizona, 166
Springs, 180
Moencopi, 178
Molasses mill, 153
Monument, National,
Act, 187
Zion Canyon made, 164
Monuments, National, 187, 191, 193
Moqui Indians, mission to, 164-166
Mojave Desert, 127
Moran, Thomas, 190
Morgan,
Dale L., 131
John, 180
Mormon,
Battalion, 131, 153
missionaries among Indians, 144-149, 179
policy re: Indians, 137
settlement, early, 130-151
Trail, 131
Mormons,
colonize Southern Utah, 135
effect of upon Paiute government, 122
explore Southern Utah, 130-149
Morris, Hyrum, 153, 158
Mountain Meadows, 128
visited by Fremont, 129
Mountains, (see names of)
Mt. Carmel,
Highway, 209
Utah, 166, 181
Mount Zion, 206
Muddy River, 128
Mukuntuweap, (see Zion Canyon)
Munk,
Mrs. Eunice, 157
Peter, 152
Murdock,
and Fotheringham, Beaver, Utah, 191
John R., 144
Museum at Zion Canyon, 207
Musser, Milton A., 180
Mustache, Frank, (Indian), 114, 115

N
Names, place, in Zion, 199
National Monument Law, 187
National Monuments, 191, 193
Zion Canyon made, 187
National Park Transportation and Camping Company, 203
Naturalist Service, 207
Navajo Indian,
depredations, 167-179
hold peace conference, 177
raids, 166-179
Navajo Indians unfriendly to missionaries, 165
Neff, Andrew L., 131
Neihardt, J. G., 127
Neslen, C. Clarence, 202
New Harmony, Utah, 145
Newman, Elijah, 151, 153, 161
Noble, Edward A., 180 219
North Rim of the Grand Canyon of the Colorado,
early history of, 189-194
Highway in, 195
Northrop, Utah, 151, 154, 159

O
Oak Creek, 148
Oak Spring, 190
Observation Point, Zion Canyon, 187
Occupations, pioneer, 138
Old Grafton, Utah, abandoned, 151
Old Spanish Trail, established, 126, 128
Ookie berries, 120
Orderville, Utah, 183
Otter Creek, 140
Otters, 140
Owen, Jim “Uncle,” 192, 198

P
Pah-Utah Indians (Paiute), 121
Pahvant Valley, 115
Paiute Indians,
cultivation, 140, 141
depredations, 167-179
legends, 113
Mormon effect upon, 122
territory occupied by, 113, 114
mode of life, 115, 116
Palmer, William R., 114, 116, 117
Panguitch Lake, 141
Utah, 128
fortified, 170
re-settled, 181
Valley, 142
Paragonah, Utah, 128, 132, 136
Parashont Mountains, 189
Parks, Southern Utah, history of, 184-209
Park-to-Park Highway conference, 203
Paria, (Pahrea)
Indian derivation of name, 114
River, Lee’s Ferry at, 189
Utah, 114, 179
Parowan,
Canyon, 135, 141
Utah, 134, 137, 171
Par-roos River, Indians of, 117
Parrusis Indians, 117, 118
Parrusit Indians,
habits and customs, 115-122
survivor of, 122
Parunuweap Canyon, 147
Indian derivation of name, 114
settlement, 155
Parry,
Chauncey, 199, 203
Gronway, 203
Pathfinder tour to Grand Canyon, 195, 197
Peace council, Navajo, 177
Pearce, J. D. L., 173-175
Pearce’s Ferry, 166
Pendleton, Mark A., 184
Peopling of Little Salt Lake Valley, celebration, 134
Petty,
Albert, 152, 153, 159
Frank, 164
Frank, Jr., 164
George, 151
Photographer, pioneer, 179
of Zion, (Major J. W. Powell’s Exploration Party), 186
Phragmites (Indian sugar), 119, 120
Pilar River, 117
Pinchot, Gifford, 187
Pine Creek route road, 206
Pine nuts, 120
Pine Spring, 190
Pioneer,
farm instruments, 157
occupations, 138
wagon raided by Indians, 172, 173
Pipe Springs, Arizona, 166, 180
council of war at, 171
Place names,
Indian, 114, 115
in Zion Canyon, 199
Spanish, 128
Pleasant Valley, 142
Plows, hand, 157
Pollock, Samuel, 147
Polygamy, 183
Potato Valley, (Escalante), 172
Powell, Maj. J. W., 114, 177, 180, 185, 186, 190
Pratt,
Orson, 131, 150, 151
Parley P., 132, 136, 144, 148
exploration of Southern Utah, 133-134
Prunus, (choke cherries), 120

Q
Quinnarrah, Indian chief, 141

R
Railroads,
built in Southern Utah, 203
developed in Northern Utah, 138
Railroad officials visit National Parks, 197 220
Red Creek, 132, 135
Red Desert, 124
Reeves, Josiah, 147
Remy, Jules, 138, 146
Richards, Franklin D., 136
Richie, Robert, 144
Riddle, Isaac, 144
Rider, John, 180
Rigg Springs, 190
Riggs,
B. A., 162
William, 147
“Rio de Los Angeles,” 128
Rio del Pilar (Ash Creek), 124
Rio Virgin Manufacturing Company, 154
Rishel, W. D., 195, 197
Rivers, (see names)
Road,
Commission, Utah State established, 194
Commissioner, Utah State, 199
concrete, 205
convention, 196
through Zion Canyon, 158, 162
wagon, 134, 194
Roads,
to Southern Utah Parks, 204, 205
constructed, 194-209
Federal aid for, 204, 205
Robinson, Richard, 144-145
Rock Creek, 134
Rockville, Utah, 116, 151, 153, 154, 171
Rolf, John, 157, 159, 161
Roosevelt, President Theodore enacts National Monument Act, 187
in Grand Canyon, 195
Ross, George, 179
Roundy, Lorenzo W., 144, 169, 189
Rubus, (raspberries), 120
Ruesch, Walter, 200, 202, 205, 207
Russell,
family, 161
Harold, 207
Major, 173
Rust, David D., 188, 191, 192, 193

S
Salina Canyon, 128
Salt Lake Tribune sponsors auto pathfinding tour to Southern Parks,
195, 197
San Juan,
County explored, 183
River settlements, 183
Santa Clara Creek, 127, 133
dam, 145
Santa Clara,
Indian Reservation, 122
Mission, 148
River, 128, 140
route used by Jedediah S. Smith, 127
Valley, 140
Saunders, B. F., 191
Savage, C. R., (pioneer photographer), 179
Sawmill, 164, 181, 190
Scoyen, E. T., 207
Scutumpah, Utah, 181
Seegmiller,
Carol, 184
Dan, 190, 191
Emma, 184
William W., 114
Sevier River, 127, 128, 132, 141
country raided, 169
Sevy, George W., 181
Sheep stolen, 167
Shelton, Marion J., 165
Shin-na-wav (Indian Spirit), 112, 113
Shingle mill, 163
Shivwits Indians, 112, 117
survivors of, 122
“Shunes” (Indian), 151
Shunesburg, Utah, 150, 151, 153-155, 159
derivation of name, 114
Shurtz, Peter, 143, 169, 189
Silver Reef, Utah, 122
Skins, used for clothing, 118
Skull Cap Valley, 142
Slavery, Indian, 121
Smith,
George A., 135, 150, 205
visits Kanab, 179
George Albert, Jr., 165
J. C. L., 141
Jedediah Strong, 117, 128, 148
expedition, 126, 127
John L., 142
Joseph, 131, 157
Silas S., 169, 170
Thomas S., 135
Smoot, Reed, 192, 196, 202
Snow,
Erastus, 136, 150, 167
General of Militia, 173, 175
Joseph S., 198
Leo A., 187, 202
Soap Creek, 114
Southern Utah,
and Arizona Parks linked by road, 204, 205 221
colonized by Mormons, 135
early explorations of, 123-130
early Mormon settlement in, 130-151
Indians, 111-123
martial law declared in, 170
Parks, history of, 184-209
Parley P. Pratt’s exploration of, 133-134
roads constructed in, 194, 209
settlements, abandoned, 159
Spanish Fathers’ explorations, 123-126
Spanish place names, 128
Spanish Trail, Old, established, 126, 128
Spencer, D. S., 197
Spencer, Howard O., 184
Springdale, Utah, 151, 153, 154, 159, 161
Springs, hot sulphur, 124
Spry, Governor William, 194, 197, 198, 202
Squashes, 117, 143
Staples, George, 153
State of Deseret proposed, 131
Steele, John, 139, 141, 173
Stevens,
Amos, 153
Barney, 153
Charles, 153
Ezra, 152, 153
Henry, 153
Hyrum, 151, 153, 172
Stewart,
George R., 182
Isaac, 150
Levi, 178-180
ranch and sawmill, 190
Margery, 180
Quinby, 164
Scott P., surveying party, 164
St. George, Utah, settled, 149
Dixie Fruit Festival at, 194
—Logan Highway, 194
Stockraising, 138
Stocks, Henry, 151, 153
Stout,
Alfred P., 163
Eliza, 163
family, 161
Lionel, 163
Mrs. Mary Jane, 163
Strawberry Creek, 142
Strong,
Ezra, 153, 166
Hyrum, 153
Sullivan, Maurice, 117, 127
Sulphur Creek, 128
River, 124
Summit Creek Canyon, 135
Surveying,
expedition to Zion Canyon, 187
party in Zion Canyon, 164
Swains Creek, 142
Swing, Phillip D., 208

T
Tamarisk trees, 124
Taylor, Orson, 158
“Temple of Sinawava”, Zion Canyon, 155, 206
“Temples and Towers of the Virgin”, Zion Canyon, 185
Tenney, Nathan, 151
Terry,
family, (John R.) 161
Jacob E., 153
James P., 153
Thaxton, James, 153
Thompson, William, 180
Thorley, Richard A., 199, 202
Thornton,
Amos G., 144
J. W., 152
Three Patriarchs, Zion Canyon, 199
Tillohash, Tony, (Indian) 112, 115
Tobacco, wild, 156
Tonaquint, Utah, 145, 147, 148
Tonaquintit Indians, 117
Toquer, Chief, 144
Toquerville,
source of name, 114
Utah, settled, 147
settlers, move to, 171
—Cedar City road, 195
Tourist busses, 207
guide, 192
travel in Parks, 207
Trail built across Grand Canyon of the Colorado, 191, 192
Mormon, 131
Old Spanish, established, 126, 128
Trails in Zion Canyon, 206
Trappers, 126, 128
Transportation to Zion Canyon, mode of, 158
Travel in Parks, 207
Tropic, Utah, 182
Trumbull Mountains, 189
Tufts, W. O., 199
Tullis, David, 144
Tunnel in Zion Road, 206
Tut-se-gavits, Indian chief, 121
222

U
Uinkarets Indians, 117, 122
Union Pacific Railroad, 197, 198
excursion to Bryce Canyon, 208
expands in Southern Utah, 203
United Order,
for all the world, 158
Beaver, Utah, 160
Cedar City, Utah, 160
Fillmore, Utah, 160
Mt. Carmel, Utah, 183
Nephi, Utah, 160
Orderville, Utah, 183
Parowan, Utah, 160
Price City, Utah, 160
Rockville, Utah, 160
St. George Stake, 160
Springdale, Utah, 161
Virgin, Utah, 160
Washington, Utah, 160
Ungatuweep, (derivation of word) 114, 115
U.S. Biological Survey, hunters for, 192
Forest Service builds road, 195
Geological Survey of Grand Canyon of the Colorado and Zion,
184, 185
National Park Service established, 184, 185
“Utah Dixie” developed, 145, 147-150
Utah Lake, 123, 127
Utah,
Parks company, 203, 206, 208
National Park, 208
Southern, explored by Mormons, 130-149
State Penitentiary, 195
State Road Commission established, 194
Ute ford, Glen Canyon, 166
Indians, 130
depredations, 167-169
organization of Ute Nations, 115

V
“V. T. Park,” 190
Vermillion cliffs, Zion Canyon, 161
Virgin City, Utah, 154, 171
Virgin River,
Indian name for, 114
Spanish name for, 128
discovered by Escalante, 124, 127
explored, 133, 139-141, 147
ferries established on, 166
guards placed on, 175
Indians, 117
route taken by Fremont, 128, 129
traveled by Jedediah S. Smith, 127
used for irrigation, 151
Virgin,
Thomas, 128
Utah, 147

W
Wadsworth, William, 133
Wagon roads in disrepair, 194
Wagon trains raided by Indians, 172, 173
Wai-no-pits, Indian spirit, 113
Walker, Charles L., 111, 152
diary of, 168-169
Chief, 130
War, 136, 137
Wallace, Grant, 192
War,
Black Hawk, 159, 166, 167
Indian, 136, 137, 159, 166, 167
Mexican, 130
Warm Valley, 143
Wasatch Mountains crossed by Escalante, 123
Wash basin, pioneer, 156
Washington,
County, protected by Militia, 167
roads built in, 195
Fields, 140
Utah, 154
Wayne Wonderland, 201, 207
Weather, 133, 139
Webb, C. Y., 139
Wells, Junius, 190
West Rim Trail, 207
West Temple, Zion Canyon, 186
Weump berries, 120
White, Douglas, 196, 198, 199
Whitlock, Hardin, 151, 153
Whitmore, Dr. James M., 150, 166, 168, 169, 189
Whitney, F. T., 142
Wickiups, 118
Wilkins, James, 179
Willis, Joshua T., 147
Wilson,
George D., 181
Pres. Woodrow, 201
Winder, John, 163, 205, 206
Winsor, A. P., 172
Utah, 166, 181
Wittwer, Samuel, 158
Wolf-god, (Indian spirit), 112, 113
Wolfskill, William, 128
Wolves killed, 192
Woodbury, Dr. Angus M., sketch, 111, 127
Woolley,
E. D., 188, 191-193 223
Edwin G., 176, 192, 193
Franklin B., 171
Wylie,
Camp, 199, 204
Grove, Zion Canyon, 206
W. W., 203

Y
York, Asa, 153
Young, Brigham, 131, 147, 148, 157, 158, 160, 179-181, 191
John R., 184
John W., 175, 190
Willis, 147
Yount, George C., 128
Yubincariri Indians, 117

Z
“Zion—Bryce Nature Notes”, 207
Zion Canyon (see Mukuntuweap)
abandoned, 159
agricultural development of, 155
cable, 161-164
dedicated, 202
early history of, 185-209
first passable road to, 199
first settler in, 155, 156
first white man to enter, 147, 158
first white man to explore, 152
geological formation of, 155
grazing stopped in, 200
highway constructed in, 205-209
horse and buggy trip through, 188
Indian name for, 114, 115, 161
Indian superstitions re: 112-113
last families to live in, 161
lodge and cabins built in, 155, 156, 206, 207
mail service, 161, 162
modern development of, 194-209
—Mt. Carmel Highway, 209
museum, 207
named, 158
name changed, 201, 202
National Monument, 187
Naturalist Service, 207
paintings exhibited at World’s Fair, 186, 187
promontory, 133
publicized, 194
roads in, 158, 162, 188, 189, 196, 199, 200, 205, 207
scenic points named, 199
settlements of, 150-161
superintendents and rangers appointed, 207
surveyed, 164, 187
trails built in, 206
travel increases, 203
visited by Brigham Young, 157, 158
visited by Governor Spry, 195, 196
visited by railroad officials, 197
224
Enjoying Emerald Pool under the cliffs in Zion Canyon.
Courtesy Union Pacific Railroad.
Transcriber’s Notes
Silently corrected a few typos.
Retained publication information from the printed edition: this
eBook is public-domain in the country of publication.
In the text versions only, text in italics is delimited by
_underscores_.
*** END OF THE PROJECT GUTENBERG EBOOK A HISTORY OF
SOUTHERN UTAH AND ITS NATIONAL PARKS (REVISED) ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like