
Beginning Javascript
Beginning JavaScript5th Editionshows you how to work effectively with JavaScript frameworks, functions, and modern browsers, and teaches more effective coding practices using HTML5. This new edition has been extensively updated to reflect the way JavaScript is most commonly used today, introducing you to the latest tools and techniques available to JavaScript developers. Coverage includes modern coding practices using HTML5 markup, the JSON data format, DOM APIs, the jQuery framework, and more. Exercises with solutions provide plenty of opportunity to practice, and the companion website offers downloadable code for all examples given in the book.
Learn JavaScript using the most up to date coding styleUnderstand JSON, functions, events, and feature detectionUtilize the new HTML5 elements and the related APIExplore new features including geolocation, local storage, and moreJavaScript has shaped the Web from a passive medium into one that is rich, dynamic, and interactive. No matter the technology on the server side, it's JavaScript that makes it come alive in the browser. To learn JavaScript the way it's used today,Beginning JavaScript, 5th Editionis your concise guide.
Introduction xix
Chapter 1: Introduction to Javascript and the Web 1
Introduction to JavaScript 1
What is JavaScript? 2
JavaScript and the Web 3
What Can JavaScript Do for Me? 4
Tools Needed to Create JavaScript Web Applications 4
Development Tools 4
Web Browsers 5
Where Do My Scripts Go? 7
Linking to an External JavaScript File 7
Advantages of Using an External File 8
Your First Simple JavaScript Program 9
Writing More JavaScript 10
A Brief Look at Browsers and Compatibility Problems 15
Summary 16
Chapter 2: Data Types and Variables 17
Types of Data in JavaScript 18
Numerical Data 18
Text Data 19
Boolean Data 20
Variables-Storing Data in Memory 20
Creating Variables and Giving Them Values 22
Assigning Variables with the Value of Other Variables 24
Using Data-Calculations and Basic String Manipulation 26
Numerical Calculations 26
Increment and Decrement Operators 29
Operator Precedence 30
Basic String Operations 35
Mixing Numbers and Strings 37
Data Type Conversion 38
Dealing with Strings That Won&t Convert 41
Arrays 43
A Multi‐Dimensional Array 47
Summary 52
Chapter 3: Decisions and Loops 55
Decision Making-The if and switch Statements 56
Comparison Operators 56
Precedence 57
Assignment versus Comparison 57
Assigning the Results of Comparisons 58
The if Statement 58
Logical Operators 62
AND 63
OR 64
NOT 64
Multiple Conditions Inside an if Statement 65
else and else if 69
Comparing Strings 70
The switch Statement 71
Executing the Same Code for Different Cases 75
Looping-The for and while Statements 76
The for Loop 76
The for…in Loop 80
The while Loop 80
The do…while loop 82
The break and continue Statements 83
Summary 84
Chapter 4: Functions and Scope 87
Creating Your Own Functions 88
Scope and Lifetime 92
Global Scope 92
Functional Scope 93
Identifier Lookup 93
Functions as Values 94
Summary 97
Chapter 5: Javascript-An Object‐Based Language 99
Object‐Based Programming 100
What are Objects? 100
Objects in JavaScript 100
Using JavaScript Objects 101
Creating an Object 102
Using an Object&s Properties 103
Calling an Object&s Methods 104
Primitives and Objects 104
JavaScript&s Native Object Types 105
String Objects 105
The length Property 106
Finding a String Inside Another String-The indexOf()
and lastIndexOf() Methods 106
Copying Part of a String-The substr() and substring() Methods 109
Converting Case-The toLowerCase() and toUpperCase() Methods 110
Selecting a Single Character from a String-The charAt() and charCodeAt() Methods 111
Converting Character Codes to a String-The fromCharCode() Method 115
Removing Leading and Trailing Whitespace-The trim() Method 115
Array Objects 116
Finding Out How Many Elements are in an Array-The length Property 116
Adding Elements-The push() Method 117
Joining Arrays-The concat() Method 117
Copying Part of an Array-The slice() Method 118
Converting an Array into a Single String-The join() Method 119
Putting Your Array in Order-The sort() Method 119
Putting Your Array into Reverse Order-The reverse() Method 121
Finding Array Elements-The indexOf() and lastIndexOf() Methods 122
Iterating through an Array without Loops 123
The Math Object 126
The abs() Method 127
Finding the Largest and Smallest Numbers-The min() and max() Methods 127
Rounding Numbers 127
The random() Method 131
The pow() Method 132
Number Objects 134
The toFixed() Method 134
Date Objects 135
Creating a Date Object 135
Getting Date Values 136
Setting Date Values 139
Calculations and Dates 140
Getting Time Values 140
Setting Time Values 143
Creating Your Own Custom Objects 144
Creating New Types of Objects (Reference Types) 148
Defining a Reference Type 149
Creating and Using Reference Type Instances 150
Summary 151
Chapter 6: String Manipulation 153
Additional String Methods 154
The split() Method 154
The replace() Method 156
The search() Method 157
The match() Method 157
Regular Expressions 158
Simple Regular Expressions 159
Regular Expressions: Special Characters 162
Text, Numbers, and Punctuation 162
Repetition Characters 165
Position Characters 166
Covering All Eventualities 170
Grouping Regular Expressions 171
Reusing Groups of Characters 173
The String Object 175
The split() Method 175
The replace() Method 177
The search() Method 179
The match() Method 180
Using the RegExp Object&s Constructor 183
Telephone Number Validation 185
Validating a Postal Code 187
Validating an E‐mail Address 189
Validating a Domain Name 189
Validating a Person&s Address 190
Validating the Complete Address 190
Summary 191
Chapter 7: Date, Time, and Timers 193
World Time 194
Setting and Getting a Date Object&s UTC Date and Time 197
Timers in a Web Page 200
One‐Shot Timer 200
Setting a Timer that Fires at Regular Intervals 202
Summary 203
Chapter 8: Programming the Browser 205
Introduction to the Browser&s Objects 206
The window Object 207
The history Object 208
The location Object 209
The navigator Object 210
The geolocation Object 210
The screen Object 213
The document Object 213
Using the document Object 214
The images Collection 216
The links Collection 218
Determining the User&s Browser 218
Feature Detection 218
Browser Sniffing 221
Summary 225
Chapter 9: DOM Scripting 229
The Web Standards 231
HTML 232
ECMAScript 233
The Document Object Model 234
The DOM Standard 234
Level 0 234
Level 1 234
Level 2 235
Level 3 235
Level 4 235
Browser Compliance with the Standards 235
Differences between the DOM and the BOM 236
Representing the HTML Document as a Tree Structure 236
What is a Tree Structure? 236
An Example HTML Page 237
The Core DOM Objects 238
Base DOM Objects 238
High‐Level DOM Objects 239
DOM Objects and Their Properties and Methods 240
The Document Object and its Methods 240
The Element Object 246
The Node Object 250
Manipulating the DOM 259
Accessing Elements 259
Changing Appearances 259
Using the style Property 259
Changing the class Attribute 262
Positioning and Moving Content 263
Example: Animated Advertisement 264
Are We There Yet? 264
Performing the Animation 265
Summary 268
Chapter 10: Events 271
Types of Events 272
Connecting Code to Events 273
Handling Events via HTML Attributes 273
Handling Events via Object Properties 280
The Standard Event Model 283
Connecting Code to Events-The Standard Way 283
Using Event Data 289
Event Handling in Old Versions of Internet Explorer 298
Accessing the event Object 298
Using Event Data 300
Writing Cross‐Browser Code 307
Native Drag and Drop 317
Making Content Draggable 318
Creating a Drop Target 319
Transferring Data 325
Summary 333
Chapter 11: HTML Forms: Interacting With the User 335
HTML Forms 336
Traditional Form Object Properties and Methods 338
HTML Elements in Forms 339
Common Properties and Methods 340
The name Property 340
The value Property 340
The form Property 340
The type Property 340
The focus() and blur() Methods 340
Button Elements 341
Text Elements 345
The Text Box 345
Problems with Firefox and the blur Event 350
The Password Text Box 351
The Hidden Text Box 351
The textarea Element 351
Check Boxes and Radio Buttons 355
Selection Boxes 364
Adding and Removing Options 365
Adding New Options with Standard Methods 369
Select Element Events 370
HTML5 Form Object Properties and Methods 375
New Input Types 376
New Elements 380
The Element 380
The and Elements 382
Summary 386
Chapter 12: JSON 391
XML 392
JSON 393
Simple Values 394
Objects 394
Arrays 395
Serializing Into JSON 396
Parsing JSON 396
Summary 400
Chapter 13: Data Storage 403
Baking Your First Cookie 404
A Fresh‐Baked Cookie 404
Viewing Cookies in Internet Explorer 404
Viewing Cookies in Firefox 409
Viewing Cookies in Chrome 411
The Cookie String 413
name and value 413
expires 413
path 414
domain 415
secure 416
Creating a Cookie 416
Getting a Cookie&s Value 419
Cookie Limitations 424
A User May Disable Cookies 424
Number and Information Limitation 425
Cookie Security and IE 425
Web Storage 426
Setting Data 427
Getting Data 428
Removing Data 428
Storing Data as Strings 428
Viewing Web Storage Content 431
Summary 432
Chapter 14: Ajax 435
What is Ajax? 436
What Can It Do? 436
Google Maps 436
Google Suggest 436
Browser Support 436
Using the XMLHttpRequest Object 438
Creating an XMLHttpRequest Object 438
Using the XMLHttpRequest Object 438
Asynchronous Requests 440
Creating a Simple Ajax Module 441
Planning the HttpRequest Module 441
The HttpRequest Constructor 442
Creating the send() Method 443
The Full Code 443
Validating Form Fields with Ajax 444
Requesting Information 445
The Received Data 445
Before You Begin 446
A Web Server 446
PHP 447
Things to Watch Out For 453
Security Issues 454
The Same‐Origin Policy 454
CORS 454
Usability Concerns 455
The Browser&s Back Button 455
Creating a Back/Forward‐Capable Form with an IFrame 455
The Server Response 456
Dealing with Delays 460
Degrade Gracefully When Ajax Fails 461
Summary 462
Chapter 15: HTML5 Media 463
A Primer 464
Scripting Media 467
Methods 468
Properties 471
Events 477
Summary 481
Chapter 16: jQuery 483
Getting jQuery 484
jQuery&s API 485
Selecting Elements 485
Changing Style 487
Adding and Removing CSS Classes 488
Toggling Classes 489
Checking if a Class Exists 490
Creating, Appending, and Removing Elements 490
Creating Elements 491
Appending Elements 491
Removing Elements 492
Handling Events 492
The jQuery Event Object 493
Rewriting the Tab Strip with jQuery 494
Using jQuery for Ajax 497
Understanding the jQuery Function 497
Automatically Parsing JSON Data 498
The jqXHR Object 498
Summary 504
Chapter 17: Other Javascript Libraries 505
Digging into Modernizr 506
Getting Modernizr 507
Modernizr&s API 508
Custom Tests 509
Loading Resources 510
Diving into Prototype 515
Getting Prototype 515
Testing Your Prototype Installation 516
Retrieving Elements 517
Selecting Elements with CSS Selectors 518
Performing an Operation on Elements Selected with $$() 519
Manipulating Style 519
Creating, Inserting, and Removing Elements 520
Creating an Element 520
Adding Content 520
Removing an Element 521
Using Events 521
Rewriting the Tab Strip with Prototype 522
Using Ajax Support 525
Delving into MooTools 531
Getting MooTools 531
Testing Your MooTools Installation 531
Finding Elements 533
Selecting Elements with CSS Selectors 533
Performing Operations on Elements 533
Changing Style 534
Creating, Inserting, and Removing Elements 535
Using Events 536
Rewriting the Tab Strip with MooTools 537
Ajax Support in MooTools 540
Summary 546
Chapter 18: Common Mistakes, Debugging, and Error Handling 549
D&oh! I Can&t Believe I Just Did That: Some Common Mistakes 550
Undefi ned Variables 550
Case Sensitivity 551
Incorrect Number of Closing Braces 552
Incorrect Number of Closing Parentheses 553
Using Equals (=) Rather than Equality (==) 553
Using a Method as a Property and Vice Versa 554
Missing Plus Signs during Concatenation 554
Error Handling 555
Preventing Errors 555
The try…catch Statements 556
Throwing Errors 557
Nested try…catch Statements 562
finally Clauses 562
Debugging 563
Debugging in Chrome (and Opera) 564
Setting Breakpoints 566
Scope Variables and Watches 566
Stepping through Code 567
The Console 571
Call Stack Window 573
Debugging in Internet Explorer 574
Setting Breakpoints 576
Adding Watches 576
Stepping through Code 576
The Console 577
Debugging in Firefox with Firebug 578
Setting Breakpoints 578
Watches 579
Stepping through Code 580
The Console 580
Debugging in Safari 580
Setting Breakpoints 583
Adding Watches 583
Stepping through Code 583
The Console 583
Summary 583
Appendix A: Answers to Exercises 587
Appendix B: Javascript Core Reference 653
Appendix C: W3C DOM Reference 683
Appendix D: Latin‐1 Character Set 715
Index 723
About the authors
Jeremy McPeak is a professional programmer and analyst who works extensively with JavaScript and C#. He coauthored both of the previous editions ofBeginning JavaScript, and authored the well-reviewedJavaScript 24-Hour Trainer. He contributes to the online, web-centric learning site Tuts+ Code, covering topics such as JavaScript, C#, and the .NET Framework.
Paul Wilton owns his own company, providing online booking systems to vacation property owners, which is largely developed using JavaScript.
Visit us at wrox.com where you have access to free code samples, Programmer to Programmer forums, and discussions on the latest happenings in the industry.
Learn the latest features and create powerful web apps with JavaScript
JavaScript has shaped the Web from a passive medium into one that is rich, dynamic, and interactive. With this comprehensive beginner's guide, you'll learn JavaScript the way it's most commonly used today#151;with the latest tools and most up-to-date techniques available so you can start creating dynamic web apps. You'll discover how to work effectively with JavaScript frameworks, functions, and modern browsers, and how to employ the most effective coding practices using HTML5.
Beginning JavaScript, 5th Edition:Presents JavaScript using the most up-to-date coding styleMakes it easy to understand JSON, functions, events, and feature detectionTeaches the fundamentals of finding, creating, and manipulating elements in the pageUtilizes new HTML5 elements and the related APIUncovers tips for new features, including geolocation, local storage, and moreDemonstrates how to use JavaScript to make HTTP requests to the web server (Ajax)Covers common mistakes, debugging, and error handlingFeatures helpful exercises with solutions that provide plenty of opportunity to practice, while the companion website offers downloadable code for all examples given in the book
Wrox Beginning guides are crafted to make learning programming languages and technologies easier than you think, providing a structured, tutorial format that will guide you through all the techniques involved.