www.it-ebooks.info
JavaScript Step by Step,
Second Edition
Steve Suehring
www.it-ebooks.info
Published with the authorization of Microsoft Corporation by:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, California 95472
Copyright © 2010 Steve Suehring
Complying with all applicable copyright laws is the responsibility of the user. All rights reserved. Without limiting the
rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any
purpose, without express written permission of O’Reilly Media, Inc.
Printed and bound in the United States of America.
1 2 3 4 5 6 7 8 9 M 5 4 3 2 1 0
Microsoft Press titles may be purchased for educational, business or sales promotional use. Online editions are also
available for most titles (). For more information, contact our corporate/institutional
sales department: (800) 998-9938 or Visit our website at microsoftpress.oreilly.com. Send
comments to
Microsoft, Microsoft Press, ActiveX, Excel, FrontPage, Internet Explorer, PowerPoint, SharePoint, Webdings, Windows,
and Windows 7 are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or
other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.
Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos,
people, places, and events depicted herein are ctitious, and no association with any real company, organization, prod-
uct, domain name, e-mail address, logo, person, place, or event is intended or should be inferred.
This book expresses the author’s views and opinions. The information contained in this book is provided without any
express, statutory, or implied warranties. Neither the author, O’Reilly Media, Inc., Microsoft Corporation, nor their
respective resellers or distributors, will be held liable for any damages caused or alleged to be caused either directly
or indirectly by such information.
Acquisitions and Development Editor: Russell Jones
14 Using JavaScript with Web Forms 275
15 JavaScript and CSS 297
16 JavaScript Error Handling 313
Part IV AJAXandServer-SideIntegration
17 JavaScript and XML 331
18 JavaScript Applications 341
19 A Touch of AJAX 345
20 A Bit Deeper into AJAX 367
www.it-ebooks.info
vi Contents at a Glance
Part V jQuery
21 An Introduction to JavaScript Libraries and Frameworks 383
22 An Introduction to jQuery 387
23 jQuery Effects and Plug-Ins 415
www.it-ebooks.info
vii
Table of Contents
Acknowledgements xvii
Introducing JavaScript Step by Step, Second Edition xix
Getting Help xxii
Part I JavaWhat?TheWhere,Why,andHowofJavaScript
1 JavaScript Is More Than You Might Think 3
A Brief History of JavaScript 3
Enter Internet Explorer 30 4
And Then Came ECMAScript 4
So Many Standards 5
The DOM 5
What’s in a JavaScript Program? 6
JavaScript Placement on Your Webpage 7
What JavaScript Can Do 10
Using External JavaScript Files with Eclipse 38
Writing JavaScript Without an IDE 41
Your First Web (and JavaScript) Project with Notepad 41
Using External JavaScript Files Without an IDE 44
Debugging JavaScript 46
Exercises 47
3 JavaScript Syntax and Statements 49
A Bit of Housekeeping 49
Case Sensitivity 49
White Space 50
Comments 51
Semicolons 51
Line Breaks 53
Placing JavaScript Correctly 53
JavaScript Statements 54
What’s in a Statement? 54
The Two Types of JavaScript Statements 55
Reserved Words in JavaScript 55
A Quick Look at Functions 56
JavaScript’s New Strict Mode 59
Exercises 60
www.it-ebooks.info
Table of Contents ix
4 Working with Variables and Data Types 61
Data Types in JavaScript 61
Working with Numbers 62
Working with Strings 66
Booleans 71
Null 71
Undened 71
x Table of Contents
Using the delete Operator 108
Returning Variable Types with the typeof Operator 111
The void Operator 112
Assignment Operators 113
The Comma Operator 114
Exercises 115
Part II ApplyingJavaScript
6 Controlling Flow with Conditionals and Loops 119
If (and How) 119
Syntax for if Statements 119
The prompt() Function in Internet Explorer 121
Compound Conditions 124
Using else if and else Statements 126
Working with Ternary Conditionals 131
Testing with switch 132
Looping with while 134
The while Statement 134
The do while Statement 135
Using for Loops 137
The for Loop 137
The for in Loop 140
The for each in Loop 141
Validating Forms with Conditionals 143
Exercises 145
7 Working with Functions 147
What’s in a Function? 147
Function Arguments 148
Variable Scoping Revisited 150
Return Values 151
The location Object 191
The history Object 198
Exercises 199
Part III IntegratingJavaScriptintoDesign
10 The Document Object Model 203
The Document Object Model Dened 203
DOM Level 0: The Legacy DOM 204
DOM Levels 1 and 2 204
The DOM as a Tree 205
Working with Nodes 206
Retrieving Elements 206
Retrieving Elements by ID 206
Retrieving by Tag Name 210
www.it-ebooks.info
xii Table of Contents
HTML Collections 212
Working with Siblings 212
Working with Attributes 213
Viewing Attributes 213
Setting Attributes 216
Creating Elements 217
Adding Text 217
Adding an Element and Setting an ID 219
Deleting Elements 219
Exercises 221
11 JavaScript Events and the Browser 223
Understanding Window Events 223
The Event Models 223
A Generic Event Handler 227
Detecting Visitor Information 228
Moving Backward 266
Working with Image Maps270
Exercises274
14 Using JavaScript with Web Forms 275
JavaScript and Web Forms 275
Obtaining Form Data278
Working with Form Information 279
Working with Select Boxes279
Working with Check Boxes284
Working with Radio Buttons 287
Prevalidating Form Data289
Hacking JavaScript Validation 289
Validating a Text Field293
Exercises295
15 JavaScript and CSS 297
What Is CSS? 297
Using Properties and Selectors298
Applying CSS 299
The Relationship Between JavaScript and CSS 300
Setting Element Styles by ID 300
Setting Element Styles by Type304
Setting CSS Classes with JavaScript306
Retrieving Element Styles with JavaScript 307
Modifying Style Sheets with JavaScript 308
Exercises311
www.it-ebooks.info
xiv Table of Contents
16 JavaScript Error Handling 313
Introducing Two Ways to Handle Errors 313
Using try/catch 313
www.it-ebooks.info
Table of Contents xv
20 A Bit Deeper into AJAX 367
Creating an HTML Table with XML and CSS 367
Styling the Table with CSS 371
Changing Style Attributes with JavaScript 371
Creating a Dynamic Drop-Down Box 374
Accepting Input from the User and AJAX 379
Exercises 380
Part V jQuery
21 An Introduction to JavaScript Libraries and Frameworks 383
Understanding Programming Libraries 383
Dening Your Own JavaScript Library 383
Looking at Popular JavaScript Libraries and Frameworks 385
jQuery 385
Yahoo! User Interface 385
MooTools 386
Other Libraries 386
Exercises 386
22 An Introduction to jQuery 387
jQuery Primer 387
Using jQuery 387
The Two jQuery Downloads 387
Including jQuery 388
Basic jQuery Syntax 388
Connecting jQuery to the Load Event 389
Using Selectors 391
Selecting Elements by ID 391
Selecting Elements by Class 391
Selecting Elements by Type 392
More jQuery UI 427
Exercises 428
Appendix 429
Index 459
Microsoft is interested in hearing your feedback so we can continually improve our books and learning
resources for you. To participate in a brief online survey, please visit:
www.microsoft.com/learning/booksurvey/
What do you think of this book? We want to hear from you!
www.it-ebooks.info
xvii
Acknowledgements
Every time I write a book, I get mired in a futile attempt to thank everyone who has helped
make it possible I originally thought that I should thank everyone and their respective fami-
lies in case I never wrote a book again But now that I’ve written several books, some of them
twice, there seems to be less urgency to thank everyone It’s not that people need to be
thanked less or that I did this all myself—far from it But inevitably I always forget to thank
someone, and though they may not be offended (who cares, it’s just a technology book), I
still feel bad
And yet as I sit here and write these acknowledgements, I still want to thank some people
As always, this is in no particular order and the list is incomplete Obviously, thank you to
Rebecca and Jakob and my family, who support the 16 to 20 hour days involved in getting a
book written in a short time Thanks to Russell Jones at O’Reilly for his editing and encour-
agement throughout, and thanks to Neil Salkind at Studio B as well Thanks to Chris Tuescher,
John Hein, Jeremy Guthrie, and Jim Leu, Andy Berkvam, Dan Noah, Justin Hoerter, and Mark
Little All those individuals told me that when I thank them in a book they feel compelled to
buy a copy (If it worked like that for everyone, I’d go get the phone book) While I’m shing
for people to thank, I should thank Jason, Kelly, John, and Jeff as well as the web team and all
my coworkers
Thanks to brother Bob for helping me choose music to write by Thanks as well to Jim Oliva
and John Eckendorf More than one Saturday morning was spent listening to the radio while
edition is reected in the content and was the impetus for adding jQuery and emphasizing
event handling
The introduction to the rst edition is still relevant and applicable, and so I’ve included it
here
JavaScript is an integral language for web application development, regardless of whether
you’re adding interactivity to a web page or creating an entire application Today’s web
wouldn’t be the same without JavaScript
JavaScript is a standards-based language with a formal specication; however, as any web
developer will tell you, almost every web browser interprets that specication differently,
which makes web developers’ jobs more difcult Fortunately, most web browsers are con-
verging in their support and interpretation of JavaScript’s core functions
This book provides an introductory look at JavaScript, including some of its core functions
as well as newer features and paradigms, such as Asynchronous JavaScript and XML (AJAX)
Today’s web users rely on many different platforms and many different browsers to view
web content This fact was central to development of every aspect of the book, so you’ll see
screenshots in multiple browsers and an emphasis on standards-based, rather than propri-
etary, JavaScript development
www.it-ebooks.info
xx Introduction
The rst part of the book examines JavaScript and helps you get started developing JavaScript
applications You don’t need any specic tools for JavaScript development, so you see how
to create JavaScript les in Microsoft Visual Studio, in Eclipse, and even in Notepad (or any
text editor) Next, the book examines JavaScript’s core language and functions, followed by
an exploration of the relationship between JavaScript and the web browser Finally, you see
AJAX demonstrated and see how to build dynamic search forms
The nal part of the book highlights JavaScript frameworks and libraries, giving specic focus
to jQuery and jQuery UI
WhoShouldReadThisBook?
This book is for beginning JavaScript programmers—people who are interested in learning
the basics of modern JavaScript programming: the language syntax, how it works in brows-
Code Blocks
Code b ocks are shown n a d fferent font to h gh ght the code
What’sintheCompanionContent
The downloadable companion content included with this book contains all the important
source code from the examples and exercises shown throughout the book The download
consists of projects and les laid out on a per-chapter basis—one directory for each chapter
Each chapter directory contains the step-by-step exercises used within that chapter
Because JavaScript is usually dependent on a surrounding web page, the source code for
the step-by-step exercises has been split within the directories This enables you to copy
and paste much of the repetitive HTML and concentrate on entering the JavaScript into the
example
Each chapter directory also contains a CompletedCode subdirectory that contains the entire
example You can open the les in the CompletedCode folder to see the examples as laid out
in the chapter
DownloadingtheCompanionContent
Most of the chapters in this book include exercises that let you interactively try out new
material you learn in the main text All the sample projects and les are available for down-
load from the book’s catalog page on the website for Microsoft’s publishing partner, O’Reilly
Media, at:
/>Click the Companion Content link on that page Locate and download the le
9780735645523-leszip Unzip that le into a folder on your local drive
www.it-ebooks.info
xxii Introduction
MinimumSystemRequirements
The code will work on many platforms, including Microsoft Windows, Linux, and Mac
n
Processor A Pentium 133 megahertz (MHz) or greater (Any computer capable of
running a web browser with JavaScript support)
n
Memory 64 megabytes (MB) of RAM or any amount that can run a computer capable
Chapter1:JavaScriptIsMoreThanYouMightThink
Chapter2:DevelopinginJavaScript
Chapter3:JavaScriptSyntaxandStatements
Chapter4:WorkingwithVariablesandDataTypes
Chapter5:UsingOperatorsandExpressions
www.it-ebooks.info
www.it-ebooks.info