407 Part III Document Object Model for HTML Documents 415 20 Core DOM Objects.. 908 Creating and Using Event Model Objects.. A Brief History of Time or This Project, Anyway This book, or
Trang 2800 East 96th Street, Indianapolis, Indiana 46240
D E V E L O P E R ’ S D I C T I O N A R Y JavaScript
A L E X A N D E R J V I N C E N T
Trang 3JavaScript Developer’s Dictionary
Copyright 2002 by Sams Publishing
All rights reserved No part of this book shall be reproduced, stored in a
retrieval system, or transmitted by any means, electronic, mechanical,
photocopying, recording, or otherwise, without written permission from the
publisher No patent liability is assumed with respect to the use of the
information contained herein Although every precaution has been taken in
the preparation of this book, the publisher and author assume no
responsi-bility for errors or omissions Neither is any liaresponsi-bility assumed for damages
resulting from the use of the information contained herein.
International Standard Book Number: 0-672-32201-3
Library of Congress Catalog Card Number: 2001094226
Printed in the United States of America
First Printing: June 2002
Trademarks
All terms mentioned in this book that are known to be trademarks or service
marks have been appropriately capitalized Sams Publishing cannot attest to
the accuracy of this information 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 authors 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 contained in this book
Acquisitions Editors
Patricia Barnes Shelley Johnston
Trang 4Contents at a Glance
Introduction 1
Part I Core JavaScript 7 1 Object( ) 9
2 Function( ) 37
3 Array( ) 57
4 String( ) 77
5 Boolean( ) 103
6 Date( ) 111
7 Number( ) 137
8 Math 157
9 RegExp( ) 171
10 Error( ) 201
11 The Global Object and Statements 213
12 Operators 237
13 JavaScript Syntax 255
14 Conditional Compilation in Internet Explorer 265
Part II Window and Client Objects 273 15 window 275
16 location 363
17 history 375
18 navigator 381
19 screen 407
Part III Document Object Model for HTML Documents 415 20 Core DOM Objects 417
21 HTMLElement 477
22 HTMLHtmlElement 509
23 HTMLDocument/document 515
Trang 5iv J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
25 Form Elements 579
26 Form Input Elements: HTMLInputElement 649
27 List Elements 667
28 Text Formatting Elements 691
29 Table Elements 777
30 Image Elements 835
31 Programmable Elements 863
32 DOM-2 Events and Event Handlers 907
33 Styling for HTML Elements 985
34 DOM-2 Range 1017
35 Cookies 1057
Part IV The Future 1069 36 XML-Related Technologies and Their DOMs 1071
Index 1099
Trang 6Table of Contents
Description 10
Creating a New Object 10
Getters and Setters of Netscape 6 11
Adding Properties and Methods to an Object 13
Objects Are Typically Unique 13
Returning New Objects Outside of a Function 13
Preparing Your Objects for Others 15
Most Objects You Create Have a Parent Object 17
Properties 18
Methods 21
Example: Creating a Persistent Reference to this 32
2 Function( ) 37 Description 38
Executing a Function 38
Declaring Objects Inside Functions 39
Browser Differences in Properties Returned 39
Functions Defined Within Functions 40
Functions Can Call Themselves: Recursion 40
Exiting from a Function Gracefully 43
The return Statement Exits a Function 45
Properties 46
Methods 50
Example: Using the Function( ) Objects’ Source Codes 53
3 Array( ) 57 Description 58
Numbered and Unnumbered Properties of Arrays 59
An Array’s Elements Can Be Any Object or Value 60
Populating an Array Automatically 61
Trang 7vi J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
Properties 61
Methods 63
Example: An Extensible switch Function 73
4 String( ) 77 Description 78
HTML and Strings: The Connection 79
JavaScript and Strings: The Other Connection 79
String HTML-Related Methods Are Not XHTML-Compliant 80
Errata in JScript Documentation Regarding Strings 81
Properties 82
Methods 82
Example: Strings in HTML 99
5 Boolean( ) 103 Description 104
Defining Boolean( ) Objects by Comparison 104
Defining Boolean( ) Object Values by the Boolean( ) Function 105
Properties 106
Methods 107
Example: Shorthand for an if Statement 108
6 Date( ) 111 Description 112
A Special Number Line for Time 112
JavaScript’s Interpretation of This Timeline 113
Determining a Specific Date 113
Instances of Date( ) Obey the Rules of Number Arithmetic 114
Properties 115
Methods 115
Example: Detecting Daylight Savings Time 134
7 Number( ) 137 Description 138
Numbers Are Everywhere in JavaScript 138
JavaScript Supports Scientific Notation 141
Accessing Properties and Methods of Number Literals 141 The Number( ) Function Performs a Type Change 142
Trang 8C ONTENTS
Properties 143
Methods 146
Example: Implementing Complex Numbers in JavaScript 149
8 Math 157 Description 157
Properties 158
Methods 161
Example: A Logarithm Function for Multiple Bases 168
9 RegExp( ) 171 Description 173
The Special Characters of Regular Expressions 173
The Literal Notation of RegExp( ) Objects 178
The Flags of Regular Expressions 183
Properties 185
Methods 194
Example: Regular Expressions and Text Exercises 197
10 Error( ) 201 Description 202
Properties 203
Methods 208
Example: Creating and Using Errors 209
11 The Global Object and Statements 213 Top-Level Objects 214
Top-Level Functions 215
Statements 221
Controlling How a Script Runs 233
12 Operators 237 The Primary Assignment Operator 238
Arithmetic Operators 238
Comparison Operators 242
Boolean Operators 245
Bitwise Operators 247
Word Operators 250
Trang 9viii J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
Parentheses, Square Brackets, and Curly Braces 256
Parentheses ( ) 256
Square Brackets [ ] 257
Curly Braces { } 257
Quote Marks 258
Semicolons, Colons, Commas, and Periods 259
Semicolons ; 259
Commas , 260
Colons : 260
Periods 260
Literals 261
ASCII and Unicode 262
Comment Lines //, /* */ 262
14 Conditional Compilation in Internet Explorer 265 Description 266
Statements 267
Objects 269
Compatibility with Netscape Browsers 270
Part II Window and Client Objects 273 15 window 275 Description 276
Common window Object Names 276
Order of Operations in Loading Scripts 279
Sending Objects and Values Between Windows 283
The window Object, Event Handlers, and the W3C DOM 285
Windows Have Two Names 285
Properties 286
Methods 306
Event Handlers 338
HTMLFrameSetElement /<frameset> </frameset> 339
Description 340
Properties 341
Methods 344
Event Handlers 344
Trang 10C ONTENTS
HTMLFrameElement/<frame /> 345
Description 346
Methods 353
Event Handlers 354
HTMLIFrameElement/<iframe /> 354
Description 355
Properties 355
Methods 357
Event Handlers 357
Example: A Basket of Windows 358
16 location 363 Description 364
Properties 364
Methods 369
Example: Sending Information from One Page to Another 370
17 history 375 Description 376
Properties 376
Methods 377
Example: Moving a Separate Frame Back 378
18 navigator 381 Description 382
Browser Sniffing, the Incorrect Way 382
Properties 384
Methods 396
Example: Browser Sniffing, the Correct Way 397
19 screen 407 Description 408
Properties 408 Example: Redirecting Based on Screen Resolution 413
Trang 11x J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
Attr 419
Description 419
Properties 419
Methods 421
CDATASection 421
Description 421
Properties 422
Methods 422
CharacterData 422
Description 422
Properties 422
Methods 423
Example: Manipulating Character Data 425
Comment 426
Description 426
Properties 426
Methods 427
Document 427
Description 427
Properties 427
Methods 429
Example: Indenting All Paragraphs, the Hard Way 434
DocumentFragment 435
Description 436
Properties 436
Methods 436
Example: Pasting a Series of Nodes Repeatedly 436
DocumentType 437
Description 438
Properties 438
Methods 440
DOMImplementation 440
Description 440
Properties 441
Trang 12C ONTENTS
Element 442
Description 442
Properties 443
Methods 443
Example: Descendant Nodes (Not Just Child Nodes) 448
Entity 449
Description 450
Properties 450
Methods 451
EntityReference 451
Description 452
Properties 452
Methods 452
Node 452
Properties 453
Methods 460
Example: Navigating a Tree of Nodes 463
NamedNodeMap 466
Properties 466
Methods 467
NodeList 469
Properties 470
Methods 470
Notation 470
Description 471
Properties 471
Methods 472
ProcessingInstruction 472
Description 472
Properties 472
Methods 473
Text 473
Description 473
Properties 474
Methods 474 Example: Inserting Hypertext Inside Plaintext 474
Trang 13xii J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
Description 478
Elements That Are HTMLElement Objects 478
Properties 483
Methods 485
Methods 495
Event Handlers 506
22 HTMLHtmlElement 509 Description 510
Properties 510
Methods 514
23 HTMLDocument/document 515 Description 516
One Method, Two Properties, and Compatibility with Three Browsers 516
The Impact of the Standards 517
The Second Browser War: 6.x 518
Collections: A Holdover from 3.x Browsers 518
The Body and Document Are Now Separate 519
Properties 519
Methods 536
Event Handlers 552
HTMLBodyElement/<body> </body> 553
Description 553
Properties 553
Methods 559
Event Handlers 559
24 Head Elements 561 HTMLHeadElement Interface/<head> </head> 563
Description 563
Properties 564
Methods 567
Event Handlers 567
HTMLBaseElement/<base /> 567
Description 568
Trang 14C ONTENTS
HTMLMetaElement/<meta /> 570
Description 570
Properties 571
Methods 573
Event Handler 573
Example: Automatic Refreshing 573
HTMLTitleElement Interface/<title> </title> 575
Description 575
Properties 576
Methods 577
Event Handlers 578
25 Form Elements 579 HTMLFormElement interface/<form>…</form> 580
Description 580
Referencing a Form 580
Validation of Forms 583
Where a Form Sends Data and How 584
Properties 585
Methods 592
Event Handlers 593
HTMLButtonElement Interface/<button>…</button> 594
Description 594
Properties 595
Methods 600
Event Handlers 600
HTMLFieldSetElement Interface/<fieldset>…</fieldset> 601
Description 602
Properties 603
Methods 605
HTMLIsIndexElement Interface/<isindex /> 605
Description 606
Properties 607
Methods 610
Event Handlers 610
HTMLLabelElement/<label>…</label> 610
Description 611
Properties 612
Methods 615
Event Handlers 616
Trang 15xiv J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
HTMLLegendElement/<legend>…</legend> 616
Description 617
Properties 617
Methods 620
HTMLOptGroupElement/<optgroup>…</optgroup> 620
Description 621
Properties 621
Methods 622
HTMLOptionElement/<option /> 622
Description 623
Properties 623
Methods 626
Event Handlers 626
Description 627
Properties 629
Methods 634
Event Handlers 637
HTMLTextAreaElement/<textarea>…</textarea> 638
Description 638
Properties 639
Methods 645
Event Handlers 646
26 Form Input Elements: HTMLInputElement 649 Description 650
The Various Types of Inputs 650
Properties 653
Methods 661
Event Handlers 663
27 List Elements 667 HTMLDirectoryElement Interface 669
Properties 669
Methods 671
Event Handlers 671
HTMLDListElement Interface 672
Properties 673
Methods 674
Event Handlers 674
Trang 16C ONTENTS
HTMLLIElement Interface 675
Properties 676
Methods 678
Event Handlers 678
HTMLMenuElement Interface 679
Properties 680
Methods 682
Event Handlers 682
HTMLOListElement Interface 683
Properties 683
Methods 686
Event Handlers 686
HTMLUListElement Interface 687
Properties 687
Methods 690
Event Handlers 690
28 Text Formatting Elements 691 Five Unusual But Significant Text Formatting Elements 694
HTMLAnchorElement/<a>…</a> 699
Description 699
Properties 700
Methods 711
Event Handlers 712
HTMLBaseFontElement Interface/<basefont> </basefont> 713
Description 713
Properties 714
Event Handlers 715
HTMLBRElement/<br /> 715
Description 715
Properties 716
Event Handlers 716
HTMLDivElement/<div> </div> 717
Description 717
Properties 718
Event Handlers 719
HTMLFontElement Interface/<font> </font> 720
Description 721
Properties 721
Event Handlers 724
Trang 17xvi J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
HTMLHeadingElement Interface / <hN> </hN> 724
Description 726
Properties 727
Methods 729
Event Handlers 729
HTMLHRElement Interface / <hr /> 730
Description 730
Properties 730
Event Handlers 733
Layer( )/<layer> </layer> / <ilayer> </ilayer> 734
Description 734
Properties 735
Methods 742
Event Handlers 746
<marquee>…</marquee> 746
Description 746
Properties 747
Methods 752
Event Handlers 752
HTMLModElement Interface/<ins> </ins>/<del> </del> 753
Description 754
Event Handlers 757
<nobr>…</nobr> 757
Description 758
Properties 758
Methods 759
Event Handlers 759
HTMLParagraphElement/<p>…</p> 760
Description 760
Properties 760
Methods 762
Event Handlers 762
HTMLPreElement Interface / <pre>…</pre> 763
Description 764
Properties 764
Methods 767
Event Handlers 767
HTMLQuoteElement Interface / <q>…</q> 768
Description 768
Trang 18C ONTENTS
Properties 768
Methods 770
Event Handlers 771
<wbr /> 772
Description 772
<xmp>…</xmp> 773
Description 774
Properties 774
Methods 775
Event Handlers 776
29 Table Elements 777 HTMLTableElement / <table> </table> 778
Description 778
The DOM and HTML Tables 778
Other Features of HTML Tables 779
Properties 780
Methods 795
Event Handlers 798
HTMLTableCaptionElement/<caption>…</caption> 799
Description 799
Properties 800
Methods 802
Event Handlers 802
HTMLTableCellElement/<td>…</td> / <th>…</th> 803
Description 803
Properties 804
Methods 812
Event Handlers 812
HTMLTableColElement/<colgroup>…</colgroup> / <col /> 813
Description 813
Properties 814
Methods 817
Event Handlers 817
HTMLTableRowElement/<tr>…</tr> 817
Description 818
Properties 818
Methods 824
Event Handlers 825
Trang 19xviii J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
HTMLTableSectionElement/<thead>…</thead> / <tfoot>…</tfoot> /
<tbody>…</tbody> 826
Description 827
Properties 827
Methods 832
Event Handlers 833
30 Image Elements 835 HTMLImageElement/<img /> 836
Description 836
Animation and Caching of Images in HTML 837
Properties 840
Methods 847
Event Handlers 848
HTMLInputElement/<input type=”image” /> 848
Description 849
Properties 849
Methods 850
Event Handlers 852
HTMLMapElement/<map>…</map> 852
Description 853
Properties 853
Methods 855
Event Handlers 856
HTMLAreaElement/<area /> 856
Description 857
Properties 858
31 Programmable Elements 863 LiveConnect: Netscape’s Bridge to Java 864
HTMLAppletElement/<applet> </applet> 865
Description 866
Properties 868
Methods 872
Event Handlers 872
HTMLEmbedElement/<embed> </embed> 873
Description 873
Properties 874
Methods 876
Trang 20C ONTENTS
HTMLObjectElement/<object> </object> 877
Description 877
Properties 881
Methods 888
Event Handlers 888
HTMLParamElement/<param /> 888
Description 889
Properties 889
Methods 890
HTMLScriptElement/<script> </script> 891
Description 891
Properties 894
Methods 897
Event Handlers 897
Example: Reorganizing a Script 898
32 DOM-2 Events and Event Handlers 907 DOM-2 Events Introduced: Listeners and Interfaces 908
Creating and Using Event Model Objects 909
Event Capturing and Bubbling 912
Canceling an Event’s Propagation 916
Canceling an Event’s Default Action 918
Use Event Listeners Carefully 918
Creating and Throwing Custom Events 920
Who Supports DOM-2 Events? 924
Events in Internet Explorer 924
Event Handlers Are Also Available as Methods 925
Event Bubbling and Canceling in Internet Explorer 926
Mouse Capture in Internet Explorer 927
Netscape 4 and Events 928
Event Interface (DOM)/Event 931
Description 931
Properties 931
Methods 953
EventTarget Interface (DOM) 958
Description 958
Properties 959
Methods 959
Trang 21xx J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
Description 960
Properties 961
Methods 961
Events in Netscape and Internet Explorer 961
33 Styling for HTML Elements 985 The Basics of CSS 987
Simple Selectors in CSS 988
Compound Selectors in CSS 991
The Order of Precedence in Styling, from Elements 992
The Order of Precedence in Styling, from Style Sheets 993
Activating and Deactivating Style Sheets 995
The !important Style Sheet Attribute 997
Style Sheet Property Names in JavaScript 998
Object Models and Cascading Style Sheets 998
Netscape 4 and JavaScript Styling 1003
Twelve CSS Properties 1005
HTMLStyleElement/<style> </style> 1008
Properties 1008
Methods 1010
HTMLLinkElement/<link />/<?xml-stylesheet ?> 1011
Properties 1012
Methods 1016
34 DOM-2 Range 1017 What Is A Range? 1018
Boundary Points for Element and Document Nodes 1018
Boundary Points for Text Nodes 1020
Range 1021
Description 1021
Properties 1026
Methods 1029
DocumentRange Interface (DOM) 1049
Description 1049
Properties 1049
Methods 1049
nsISelection Interface 1050
Description 1050
Properties 1054
Trang 22XML 1.0 1072 Elements 1072 Attributes 1072 Document Structure 1073 DTD 1074 Elements 1075 Attributes 1076 Entities 1077 Conditional Sections 1078 XHTML 1.0: eXtensible HyperText Markup Language 1079 Namespaces in XML 1080 Scripting an XML Document: <html:script /> 1083 Internet Explorer and XML Data Islands 1084 Modularization of XHTML and XHTML 1.1 1085 XLink 1087 XSLT 1.0: eXtensible Stylesheet Language, Transformations 1088 XML Schemas 1089 MathML 2.0: Mathematics Markup Language 1090 SVG 1.0: Scalable Vector Graphics 1091 XForms 1095 XQuery 1096 SOAP: Simple Object Access Protocol 1096 Other XML Languages 1096
Conclusion to the JavaScript Developer’s Dictionary 1097
Trang 23About the Author
Alexander James Vincent is a 24-year-old Web design expert based in Vallejo, CA.
Born and raised in Seattle, WA, he served 23 months in the United States Navy as aSeaman Journalist Following his tour of duty, he returned to the field of computers hegrew up around and discovered JavaScript Since then he has become a standardsevangelist for Web design, and works to encourage best practices in coding for all Weblanguages, client- and server-side He moderates the JavaScript Programming Help
also contributes Quality Assurance efforts to the Mozilla.org project He is currently
in the process of completing the design of his JavaScript Laboratory site at
http://www.jslab.org, a project he set aside for the JavaScript Developer’s Dictionary.
He is a huge fan of the Seattle Mariners, and hopes to see them in a World Series oneday soon
Trang 24To the Nathan Hale High School faculty members; particularly, Principal Eric Benson, and Language Arts teacher Victoria Carver Also, the Mathematics team at Nathan Hale—particularly Mr Dong, Mr Coon,
and Mr Wiegand
Numerous other departments (and the lunchroom cooks) may never forgive
me for leaving them out But I will say what I told Mr Benson a couple years after my graduation; Nathan Hale High School was an average school when I entered it as a freshman, in Mr Benson’s first year as a principal.
By the time I had left four years later, it was a first-class high school.
Acknowledgments
There are a number of people I wish to say “Thank You” to First on that list is God
It may sound trite, but it isn’t I would have died at sea were it not for Him, beforethis book even became an idea in my head
Next would be Arun Ranganathan at Netscape, for pointing me to those IDL files at
lxr.mozilla.org Without his help in at least pointing me to them, this book wouldhave died halfway through
Then there are the numerous people on the Sams Publishing team: Shelley Markanday, Jon Steever, Patricia Barnes, the Technical Editors for this book, MartinHonnen and Jason Byers, and several other behind-the-scenes people I haven’t yet met
Johnston-or e-mailed
John Krutsch, a longtime friend and fellow moderator at Website Abstraction, for hiswork on cookies
Jason Karl Davis, Ryan Frishberg (a.k.a “Arielladog”), and Andrew Shults (a.k.a
“thejavaman1”), for second opinions on my occasional guessing
Several Mozilla.org engineers and QA people whose names I can’t even begin to recall.What goes around comes around, ladies and gentlemen, and I’ll be coming aroundquite a bit in the future
George Chiang, owner and operator of Website Abstraction(http://www.wsabstract.com), the first place I found a home in Web site design
Trang 25The various journalism instructors at Defense Information School at Fort Meade,
MD Particularly then-Gunnery Sergeants Beyer and Roberts of the United StatesMarine Corps, in the radio and public affairs departments respectively, and Sergeant1st Class Sizer who put up with my attitudes (barely) in print journalism class in thewinter of 1996–1997 I don’t think I could have written this book as well as I didwithout your teachings, and you’ve definitely impacted my writing style The sameapplies to all the non-commissioned officers, petty officers, and chief petty officers atDINFOS during that time
James LeBlance at Smart Scents, and Dimple Sayles at D & R Hauling, for doingeverything they could to keep a roof over my head and food in my stomach
Who could forget Mom and Dad, who will be celebrating 25 years of marriage inApril 2002? I couldn’t
Trang 26Tell Us What You Think!
As the reader of this book, you are our most important critic and commentator We
value your opinion and want to know what we’re doing right, what we could do better,what areas you’d like to see us publish in, and any other words of wisdom you’rewilling to pass our way
You can e-mail or write me directly to let me know what you did or didn’t like aboutthis book—as well as what we can do to make our books stronger
Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.
When you write, please be sure to include this book’s title and author as well as yourname and phone or e-mail address I will carefully review your comments and sharethem with the author and editors who worked on the book
Associate PublisherSams Publishing
800 East 96th StreetIndianapolis, IN 46240 USA
Trang 28JavaScript The term itself implies a scripting language, a
“patchwork” for whatever Web page you have in mind But, likemany scripting languages, it’s not necessarily a simple one
What Is JavaScript?
The word “JavaScript” is really a name for a language withseveral different flavors Microsoft Internet Explorer (IE)implements JavaScript under the name “JScript,” and withbrowser-specific code in certain areas Netscape Navigator 4(Nav4) interacts with Web documents quite differently thanNetscape 6 (Nav6), its successor There have been six revisions
of JavaScript alone for Netscape, which invented the language.Within the next few years, JavaScript 2.0 will enter the WorldWide Web
With all these variants on the same theme, Netscape andMicrosoft leave a lot of developers scrambling to write codethat works in all the major browsers Furthermore, documen-tation can be found from a variety of sources in various formats,some of which may be incomplete or outdated The result is alot of developers who cannot easily find the information forwhich they are looking
A Brief History of Time (or This Project, Anyway)
This book, or at least the concept behind it, truly started in
1999, when I asked for documentation on the currentMozilla.org JavaScript Engine and Document Object Model.This was long before Netscape 6 began its beta releases andbefore 6.0 was released At the time, Mr Steve Rudman asked
me if I was willing to work for him, for hire, to do thedocumentation on JavaScript 1.5 I refused, feeling I was not up
to the task
Trang 292 J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
Eight months later, I remembered some of the words of inspiration of several sionals in life changes, notably Anthony Robbins (Thanks, Tony, though we’ve nevermet and I’ve yet to attend one of your seminars “Awaken the Giant Within” was veryinteresting.) Effectively, I realized I had thrown away an opportunity for which I wasvery competent I replied to the newsgroup, offering my services, but it was too late.Sams Publishing’s Acquisitions department, however, watches the newsgroups as well
profes-After numerous unspeakable delays, the result is the JavaScript Developer’s Dictionary.
(I’ve also discovered about 15 errata in the JavaScript 1.5 Core documentation Irefused to do…)
In a sense, this book is for me as well as for you You’d be surprised how much youlearn about a language by writing and researching a book about it One fact I can takepride in about this book is I could regularly turn back to earlier draft chapters in thisbook when I needed to build a code listing in later chapters—without going to theofficial references I used as starting points
Nonetheless, in our modern age, even a book such as this is a work in progress.Therefore, before we get into the chapters themselves, I have already set up adirectory on my Web site for errata, new discoveries, and so on that I, you, or other
XHTML as HTML: The Dictionary Standard
In the process of editing chapters, I made a decision to re-create each listing asXHTML 1.0 Transitional documents whenever possible When you examine and
XHTML 1.0 is a “reformulation of HTML as XML,” as the W3C puts it This meansthat HTML follows a very rigid structure, from which you should not deviate
Keeping to this structure gives you a solid, reproducible, and uniform DOM for eachdocument, and subsequently each listing in this book
state of affairs Even now, we are still very much in a transition from pre-standardsbrowsers to post-standards browsing Internet Explorer, upon receiving an XHTMLdocument as XML, treats it as XML and ignores the HTML features entirely (Ireference a workaround for this in Chapter 33, “Styling for HTML Elements.”) AsHTML, Internet Explorer often expects closing tags when an empty element tag
Trang 30I NTRODUCTION
Netscape 6 treats it as XML, running it through the XML parser, but also does notexpose the full HTML DOM for the document This is even true when you serve the
For your own coding efforts, I strongly recommend you get into the habit of writingvalid XHTML code as soon as possible, not only because it works in a wide variety ofbrowsing platforms, but also because it makes your DOM much more stable andpredictable If you already know HTML (pretty much a prerequisite to this book),learning XHTML is not difficult at all First, you learn how to write valid HTML4.01 Transitional code (somewhat easy), and then you learn to write XHTML 1.0Transitional code from HTML 4.01 Transitional (easy, once you get the hang of it)
should trust
What Does this Book Cover?
JavaScript Developer’s Dictionary is a reference to complete and enhance the
documen-tation for the JavaScript language As the vast majority of Internet users use Nav4,
IE4, and later generations of these two browsers, the Dictionary shall focus on
JavaScript, starting primarily at this level: JavaScript 1.2 for Netscape browsers, andJScript version 3 for Internet Explorer browsers I also cover the added and deprecatedfeatures of Internet Explorer 5.0, Internet Explorer 5.5, and Netscape 6, to JScriptversion 5.5 and JavaScript 1.5
This book covers every object available to the developer in typical client-side use It
Function(), in Part I
In Part II, we enter an area of JavaScript for which there are no standards per se, butwhich the two browser companies mentionned previously have paralleled each other
Part III covers the Document Object Model for HTML documents—both within thestandards defined by W3C and proprietary, non-standard definitions of each HTMLelement It begins with core DOM definitions as provided by the W3C DOM fornodes, attributes, document fragments, and the like Then the book dives into thespecific properties and methods associated with each element of the HTML language.Finally, we explore events and event handlers, styling, cookies, and the DOM Level 2Range specification
I wrap it up in Part IV with styling several significant XML-based technologies tokeep an eye on (As you’ll see, you can use JavaScript with XML documents as well.)
Trang 314 J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
This book does not cover signed scripts, the security model of either browser, orserver-side scripts in the JavaScript language For the most part, these features areoften far more trouble than they are worth Signed scripts and the security modelinvolve a fairly intimidating warning for Web site visitors, who often deny permissionfor what the scripts request These areas are insignificant for most JavaScripters, andthus this book offers no emphasis on the limited features these subsets of JavaScriptprovide
One feature of JavaScript I want to emphasize quite heavily at this point is theinheritance of properties and methods of some objects in other objects For instance,
organized the chapters of this book to present fundamental object chapters beforeobjects inheriting their properties For each element I note specifically what element it
chapter) indicates from which object it descends
In case you’re wondering, there will be examples of each object in active use Manytimes, these examples will cover innovative concepts I find extremely useful and under-used More than that, the examples are not written for the novice JavaScripter
This book assumes you have some familiarity with the JavaScript language, and is notintended to teach you JavaScript The examples are just that: examples Sometimes theexamples demonstrate good coding practices, and sometimes they may be quiteimpractical Nonetheless, if you are just beginning to learn JavaScript, I recommend
you read Sams Teach Yourself JavaScript in 24 Hours from Sams Publishing before you
read this book
Formatting of Script Examples
Throughout the rest of this book, you will notice several conventions NetscapeNavigator 4 and Netscape 6 browsers are abbreviated Nav4 and Nav6, respectively.Internet Explorer browsers are abbreviated IE4, IE5, IE5.5, and IE6, depending onthe version of browser Other abbreviations you see frequently in this book includeW3C for the World Wide Web Consortium, DOM for Document Object Model, andECMA for ECMAScript
Trang 32alert(“Goodbye, cruel world”) }
return false }
The primary reason for this is visual formatting, to ensure you can follow the codeexamples within The browser ignores such formatting, but it makes code far easier toread I generally do not have anything that is not indented, except for function and
Chapters 1 and 15, “Object( )” and “window”.)
I introduce each feature of the language with a table indicating what browsersimplement it, and in which standard, if any, a feature also belongs to: ECMAScript orthe DOM Features that are implemented in DOM Level 2 (DOM-2) but not inDOM Level 1 (DOM-1) are noted as such Likewise, if a basic constructor or node has been deprecated, the table notes this The primary focus of this book is onJavaScript 1.2 and JScript version 3.0 and later, but earlier versions of JavaScriptreceive mention as well
All this being said, welcome to the JavaScript Developer’s Dictionary Prepare for a few
surprises, and a lot of fun
“The first step to confirming there is a bug in someone else’s work is confirming there
are no bugs in your own.”–Alexander J Vincent
Trang 36C HAPTER 1
Object( )
D E V E L O P E R ’ S D I C T I O N A R Y
Trang 3710 J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
P ART I Core JavaScript
Browser/JavaScript Version Created By
Creating a New Object
You can create an object using the following syntax:
[var] x = new Object()
Trang 38C HAPTER 1 Object( )Creating a New Object
constructor functions as well, defined later in this chapter and in Chapter 2,
are the values you assign to them
Getters and Setters of Netscape 6
Netscape 6 supports the capability for you to use getter and setter functions to set andretrieve properties of objects at will With these functions, you can modify any otherproperties of the object simultaneously, and still return the correct result
Defining a getter is simple You first define the function you want to act as a getterfunction to return the value you want the function to get, and then use the
defineGetter ()method of the object to activate it The first argument of
defineGetter ()is the property name the object is getting, in quotes The second
is the function you want to assign as a getter, without parentheses or arguments
Alternatively, you could use the function operator, which I cover in Chapter 2,
“Function( )” and a little in Chapter 12 This operator would allow you to define thegetter function directly as the second argument (I prefer not to do this, but it can besmarter to code this way.)
Defining a setter is equally simple You first define the function you want to act as asetter function by assigning values to other properties as appropriate, and then usethe defineSetter ()method of the object to activate it The first argument of
Note
The literal syntax for objects is not available to Netscape browsers prior to version 4, or Internet Explorer browsers prior to version 4.0.
Trang 3912 J AVA S CRIPT D EVELOPER ’ S D ICTIONARY
P ART I Core JavaScript
defineSetter ()is the property name the object is setting, in quotes The second
is the function you want to assign as a setter, without parentheses or arguments
In Listing 1.1 the setter function returns the value it sets to the given reference
<! function book_setName(x) { this._author = x return this._author }
var book = { _author: “Alex Vincent”};
The author is Alexander J Vincent.
// >
</body>
</html>
Trang 40C HAPTER 1 Object( )Creating a New Object
Adding Properties and Methods to an Object
JavaScript-defined constructor, you will find you can add and change properties andmethods of the object at will For instance, if you were to say:
myArray = new Array()
you could still add properties and methods to the array object at will:
myArray.color = “red”
The addition of methods, in particular, can be very useful when the methods use the
Chapter 13, “JavaScript Syntax”), you cannot add properties and methods so easily
Object.constructor()method
Objects Are Typically Unique
Note the following code:
var x = new Object() var y = new Object() alert(x == y) // returns false
explicitly set to reference one another, or a common value, they are unequal You
This becomes useful in a few situations For instance, any object I create using the
Object()constructor I can use as a flag The word “flag” is a term programmers and
scripters use to indicate an object the programmer uses to indicate some status orspecial use, but which has no meaning outside its context Like all other argumentsand variables in a function, they indicate to the function what it should do; unlikeother arguments and variables in a function, flags relevant to the function they areapplied against are largely irrelevant to the script and other functions at large (To put
loop Would that variable have any meaning outside the loop?)
Returning New Objects Outside of a Function
A constructor function is a function specifically designed to return an object to theoutside world, where the object returned can then be assigned a name outside the