ptg8286261
ptg8286261
Praise for Learning JavaScript
“Between modern web interfaces, server side technologies, and HTML5 games,
JavaScript has never been a more important or versatile tool. To anyone just starting
out with JavaScript or looking to deepen their knowledge of the practical core of the
language, I would highly recommend Learning JavaScript.”
—Evan Burchard, Independent Web Developer
“Although I’ve read a couple of books about JavaScript before, as a backend developer,
I was thrilled to see Tim Wright’s Learning JavaScript. The nuances of progressive
enhancement versus graceful degradation are finally explained in a manner that
someone new to front-end coding can understand. Bravo, Tim.”
—Joe Devon, Cofounder, StartupDevs.com
“Tim Wright has written a delightfully practical book for the novice front-end
developer who wants to learn JavaScript. This book’s strength is in providing a good
introduction to JavaScript while also illustrating the context of when and where it
should be used.”
—R. S. Doiel, Senior Software Engineer, USC Web Services
“Learni ng JavaScript is a great introduction into modern JavaScript development. From
covering the history to its exciting future, Learning JavaScript equips the novice developer
to practical application in the workforce. I wish this book came along when I was a novice!”
—Hillisha Haygood, Senior Web Developer, Sporting News
“Tim presents invaluable techniques for writing JavaScript with progressive
enhancement at the forefront. If you are new to JavaScript then this book will prove
to be a great asset in your learning. Covering all the basics and then right through to
touch events, AJAX, and HTML5 APIs, the examples are clear and easy to follow. Using
this book, you will learn when and how to use JavaScript to great effect.”
—Tom Leadbetter, Freelance Web Designer
“Learning JavaScript is valuable for both new and veteran developers. It is great for new
developers because it is easy to read and provides a step-by-step process to becoming
great at JavaScript. Veteran developers will be reminded of many of the best practices
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Cape Town • Sydney • Tokyo • Singapore • Mexico City
ptg8286261
Editor-in-Chief
Mark Taub
Acquisitions Editor
Laura Lewin
Development
Editor
Songlin Qiu
Managing Editor
Kristy Hart
Project Editor
Anne Goebel
Copy Editor
Barbara Hacha
Indexer
Lisa Stumpf
Proofreader
Debbie Williams
Technical
Reviewers
Evan Burchard
Alex Moffat
Publishing
Coordinator
Olivia Basegio
Cover Designer
Chuti Prasertsith
005.2’762--dc23
2012019351
Copyright © 2013 Pearson Education, Inc.
All rights reserved. Printed in the United States of America. This publication is protected by
copyright, and permission must be obtained from the publisher prior to any prohibited repro-
duction, storage in a retrieval system, or transmission in any form or by any means, elec-
tronic, mechanical, photocopying, recording, or likewise. To obtain permission to use mate-
rial from this work, please submit a written request to Pearson Education, Inc., Permissions
Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your
request to (201) 236-3290.
ISBN-13: 978-0-321-83274-0
ISBN-10: 0-321-83274-4
Text printed in the United States on recycled paper at Edwards Brothers in Ann Arbor,
Michigan.
First printing, August 2012
ptg8286261
❖
For Ma.
❖
ptg8286261
Contents
Introduction 1
Chapter 1: Progressive Enhancement 3
Chapter 2: JavaScript in the Browser 21
Chapter 3: JavaScript Terminology 39
Chapter 4: Accessing the DOM 57
Chapter 5: Storing Data in JavaScript 81
Chapter 6: Variables, Functions, and Loops 103
Chapter 7: Interacting with the User Through Events 123
Chapter 8: Communicating with the Server Through Ajax 149
The Touch Interface 18
Final Words on Progressive Enhancement 19
Summary 20
Exercises 20
Chapter 2: JavaScript in the Browser 21
A People’s History of JavaScript 21
Origins 22
Progressive Enhancement 23
The Behavior Layer 24
Moving Past Today 24
Browser Interactions with JavaScript 25
HTTP Requests 26
JavaScript and Rendering Engines 29
ptg8286261
x
What JavaScript Can Do 30
Modifying HTML 31
Communicating with the Server 31
Storing Data 31
How You Should Use JavaScript 32
Improving User Experience 32
Using JavaScript Responsibly 32
Creating Fallbacks 34
Tools to Help You Use JavaScript 36
Tools Built into the Language 36
Tools Built into the Browser 37
Summary 38
Exercises 38
Chapter 3: JavaScript Terminology 39
Basics 39
Exercises 55
Chapter 4: Accessing the DOM 57
What Is the DOM? 57
The DOM Tree 58
Element Nodes 59
Text Nodes 60
Attribute Nodes 62
Working with the Element Node 62
Targeting by ID 63
Targeting by Tag Name 64
Targeting by Class 67
Using CSS Selectors in JavaScript to Target Nodes 68
Working with the Attribute Node 70
Getting an Attribute 71
Setting an Attribute 72
Removing an Attribute 73
Working with the Text Node and Changing Content 73
Moving Around the DOM 74
Accessing First and Last Child 76
Dynamically Adding and Removing Nodes from the
DOM 77
Adding Elements to the DOM 77
Removing Elements from the DOM 78
Summary 79
Exercises 79
Chapter 5: Storing Data in JavaScript 81
Variables 81
Strings 82
Numbers 83
Boolean 84
Chapter 6: Variables, Functions, and Loops 103
Defining Variables 103
Grouping Variables 104
Reserved Terms 104
Functions 105
Basic Functions 106
Anonymous Functions 107
Scope 108
Calling a Function with a Function 109
Returning Data 110
A Function as a Method 112
ptg8286261
xiii
Contents
Loops 113
for Loop 114
Conditionals 116
if Statement 116
if/else Statement 117
switch Statement 118
if versus switch 119
Putting It All Together 120
Summary 121
Exercises 122
Chapter 7: Interacting with the User Through Events 123
Attaching an Event 124
Event Handlers 124
Event Listeners 125
Binding Events 128
Unbinding Events 129
Ajax Data Formats 164
XML 165
HTML 166
JSON 167
Ajax Accessibility 168
Live Regions and ARIA 169
Common Ajax Mistakes 170
Providing Feedback 170
Putting It All Together 172
Where Is Ajax Going? 177
Summary 177
Exercises 178
Chapter 9: Code Organization 179
General Coding Style Rules 180
Scope 181
Failing Quickly 183
User Experience 185
Code Design 185
Files and Directories 186
In-document Script 187
Variable Declarations 188
Variable and Function Naming 189
Comments 190
Indentation 192
Whitespace 193
Statement Spacing 194
ptg8286261
xv
Contents
Line Breaks 195
Extending Libraries Through Plug-ins 233
Building a Plug-in 234
The Good of Libraries 236
Popularity and Community 236
Efficient Code 237
ptg8286261
xvi
Contents
The Bad of Libraries 238
Overhead 238
Performance 239
Overreliance and Shelf Life 239
Using Microlibraries 240
The Good 240
The Bad 241
Summary 242
Exercises 242
Chapter 11: HTML5 JavaScript APIs 243
What Is HTML5? 244
The Markup (aka HTML) 244
Creating Better Semantics 245
Building More Accessible Content 245
The JavaScript APIs 248
The navigator Object 248
Geolocation 249
Audio and Video 251
History API 254
Web Workers 259
Device API 265
The Battery Status API 266
of all, I want to thank the folks at Pearson for giving me the opportunity to not only write
this book, but structure it in a way that truly reflects how I believe the topic should be taught.
The book would not have stayed on track without them. My technical editors were also
instrumental to the process in pointing out any missteps, giving praise when needed, and
making sure every detail of the book was written with accuracy and precision; I could not have
done it without you (Evan Burchard and Alex Moffat). I would also like to give special thanks
to my parents, friends, and family for the continued support, encouragement, and patience
throughout this long process and for pulling me out of my “writing cave” for fresh air every
once in a while. Without you all, nothing would have been possible.
ptg8286261
About the Author
Tim Wright has been a Web designer and front-end developer since 2004, primarily focusing
on CSS, HTML5, accessibility, user experience, and building applications with the capability
to scale seamlessly from desktop to mobile device. He has worked at various universities
nationwide and fostered the advancement of Web standards at each stop along the way.
Tim has written many articles for popular Web design online publications, such as Smashing
Magazine , SitePoint, and Web Designer Depot , on all facets of front-end development from
HTML5 and CSS3 to user experience and advanced JavaScript techniques. He also writes many
articles via his personal blog at csskarma.com. Tim holds a Bachelor’s Degree in Marketing
Management from Virginia Tech, with a specialization in Graphic Design.
ptg8286261
Introduction
W
hen I decided to write a book about JavaScript, I wanted to create it in a way that felt
natural to how I learned the language. I didn’t learn it from school or a book; my JavaScript
knowledge comes from real-world application, trial and error, and self-motivation. I wanted
to present the information in a unique way so that you could get up to speed quickly, but still
develop a solid base for the language and move forward without feeling overwhelmed with
too much information. I combined my teaching experience with how I felt while I was learn-
ing to create an environment that moves quickly but has built-in break points and reviews to
The audience for this book is anyone starting out in Web design and development who wants
to learn about JavaScript. Before reading this book, you should be knowledgeable in HTML and
CSS, and be familiar with the concepts behind progressive enhancement.
This book can equally serve absolute beginners and seasoned Web veterans who are expanding
their knowledge into JavaScript. All the while, I hope it instills enthusiasm to learn more about
this rapidly moving industry.
Code Samples for This Book
The code samples for this book are available on the book’s website at
http://learningjsbook.com .
ptg8286261
1
Progressive Enhancement
A
s much as we’d like to think that people visit our sites to look at the majestically created
intricate graphics, slick CSS animations, and semantic HTML, I can confidently tell you that,
unfortunately, that is not true. I certainly visit some sites because of that—you may even do
it as well—and it’s possible that it’s a topic of conversation over drinks after work, but real
Internet users (we’re not real users; we’re developers and designers—we’re “edge cases”) don’t
notice that stuff. All they care about is how efficiently they can do what they need to do,
whether it’s checking email and the weather, downloading a song, or watching a movie. But
that’s the point: We’re supposed to be designing things so well that the techniques go virtu-
ally unnoticed to an untrained eye. When they start to stand out, the overall goals tend to get
blurred.
People come to your site, my site, Yahoo!, Google, or MSN for the same reason: content .
Everyone wants the content; content is king. It’s the most important aspect of any website or
application. Think about it next time you visit a site. Why are you there? The answer is almost
always “content.” In the Web design community, we have a guiding principle that stresses the
importance of content. It guides the way we approach all our projects, big and small, and it’s
called progressive enhancement .
Defining Progressive Enhancement
site: the content.
As long as you keep your layers separate, make your site work with only HTML, pretty it up
with CSS, and then smooth out the behavior with JavaScript, you will make sure that your
content is always accessible.
History
In 2003 in Austin, TX, at South by Southwest, a new term was coined that realigned the Web
with the original path of Tim Berners-Lee; this term was announced as progressive enhance-
ment , and ever since, the face of Web design has been changed. The way we build and think
moved from focusing on machines (browsers) to a more friendly model, which centered around