What Readers Are Saying About Pragmatic Guide to J a v a S c r i p t
I wish I h ad o w n e d this book when I first s tarted out d oing Ja v aScript! Prag-
matic Guide t o J a v a S c r i p t will t ake you a b ig step a head in programming
real-world J av aScript b y showing y ou what i s going on behind the s cenes in
popular JavaScript l ibraries and giving y ou no-nonsense a dvice and back-
ground information o n how to d o the r ight thing. W i t h the c ondensed years
of ex p e r i e n c e of o ne of the b est J av aScript d e velopers around, it’s a must-
read with g reat reference t o e v e r y d a y JavaScript tasks.
Thomas Fuchs
Creator of the s cript.aculo.us framework
An impressive collection o f v e r y practical tips and tricks for getting t he most
out of JavaScript in today’s browsers, with topics r anging from fundamen-
tals such as form v a l i d a t i o n and J SON handling to a pplication e x a m p l e s
such as mashups and geolocation. I highly recommend this book for anyone
wa nt in g to be more productive with Jav aScript i n their web applications.
Dylan Schiemann
CEO a t SitePen, cofounder o f the Dojo T o o l k i t
There a re a number of J av aScript b ooks on the market today, b u t most of
them tend t o focus on the new or inexperienced J av aScript programmer.
Porteneuve does no such thing, and this Pragmatic Guide is a better book
for i t. If y ou’ re a novice, go elsewhere first, and then when y ou have s ome
scripting under y our b elt, c ome back; if y ou’ ve wo rked with JavaScript
before, then Pragmatic Guide to J a v a S c r i p t takes a set of techniques that
you may ha ve heard a bout or seen a nd makes t hem useful to y ou. Recom-
mended.
Stuart Langridge
kryogenix.org, @sil
Pragmatic Guide to JavaScript
Christophe Porteneuve
The P ragmatic Bookshelf
Raleigh, North Carolina Dallas, T e x a s
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. W here those d esignations appear in this b ook, and The P ragmatic P ro-
grammers, LLC was aware o f a trademark claim, the d esignations have b een printed in initial
capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic
Programming, Pragmatic Bookshelf and the l inking g device are trademarks of T he P ragmatic
Programmers, LLC.
Every precaution was taken in the preparation of this book. However, the publisher assumes no
responsibility for errors or omissions, or for damages t hat may result from the use of information
(including program listings) contained herein.
Our Pragmatic courses, workshops, and other products can help you and your team create better
software and have more fun. For more information, as well as the latest Pragmatic titles, please
visit us at .
The team that produced t his book i ncludes:
Editor: David McClintock
Indexing: Potomac Indexing, LLC
Copy edit: Kim W i m p s e t t
Layout: Steve Peter
Production: Janet Furlow
Customer support: Ellie Callahan
International: Juliet Benda
Copyright
©
2010 Pragmatic Programmers, LLC.
All rights reserved.
No part of t his publication may be reproduced, s tored in a retrieval system, or transmitted, in any
form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the
prior consent of the publisher.
Printed in the United States of America.
ISBN-10: 1-934356-67-0
ISBN-13: 978-1-934356-67-8
Printed on acid-free paper.
P1.0 printing, November 2010
V e r s i o n : 2010-11-18
Download from Wow! eBook <www.wowebook.com>
Contents
Dedication 9
Acknowledgments 10
Introduction 12
What’s This Book About, and Who Is It F o r ? . . . . . . . . 12
This Book a nd JavaScript Libraries . . . . . . . . . . . . . . 13
This Book a t a Glance . . . . . . . . . . . . . . . . . . . . . 14
How to Read This Book . . . . . . . . . . . . . . . . . . . . 15
I Bread and Butter: Pure J a v a S c r i p t 16
T a s k 1. Dynamically S electing a Method/Property 18
T a s k 2. Achieving Code P rivacy with t he Module Pa tte rn 20
T a s k 3. Using Optional, V a r i a b l e , and Named Arguments 22
II The DOM, Events, and T i m e r s 24
T a s k 4. Obtaining References to DOM Elements 26
T a s k 5. Dynamically S tyling Content 28
T a s k 6. Changing an Element’s Contents 30
T a s k 7. Running Code When t he DOM Is Loaded 32
T a s k 8. Listening f o r Events (and S topping) 34
T a s k 9. Leveraging Event Delegation 36
T a s k 10. Decoupling Behaviors with Custom Events 38
T a s k 11. Simulating Background Processing 40
Download from Wow! eBook <www.wowebook.com>
CONTENTS 6
III UI T r i c k s 42
T a s k 12. Pulling Off Classy T o o l t i p s 44
T a s k 13. Making Unobtrusive P o p - U p s 46
T a s k 14. Preloading Images 48
T a s k 15. Creating a Lightbox Effect 50
T a s k 16. Implementing an “ Infinite Scroll” 52
T a s k 17. Maintaining V i e w p o r t When Loading Content 54
IV F o r m - f u 56
T a s k 18. T e m p o r a r i l y Disabling a Submit Button 58
T a s k 19. Providing Input Length F e e d b a c k 60
T a s k 20. (Un)checking a Whole Set of Checkboxes at Once 62
T a s k 21. V a l i d a t i n g F o r m s : The Basics 64
T a s k 22. V a l i d a t i n g F o r m s : Going Further 66
T a s k 23. V a l i d a t i n g F o r m s : The Whole Nine Y a r d s 68
T a s k 24. Providing On-the-Fly Help T o o l t i p s on F o r m s 70
T a s k 25. A u t o c o m p l e t i n g Input As It’s T y p e d 72
T a s k 26. Using Dynamic Multiple File Uploads 74
V T a l k i n g with the Server Side 76
T a s k 27. Reading/Writing Cookies 78
T a s k 28. Loading Stuff Through Ajax (Same Domain) 80
T a s k 29. Using JSON 82
T a s k 30. Using JSON-P 84
T a s k 31. Cross-Domain “ A ja x ” (Take 1) 86
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
CONTENTS 7
T a s k 32. Cross-Domain “ A ja x ” (Take 2) 88
VI Making Mashups 90
T a s k 33. Syndicating Y o u r T w i t t e r Updates 92
T a s k 34. Syndicating Y o u r Flickr Updates 94
T a s k 35. Geocoding a Location and Getting P hotos F o r It 96
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
CONTENTS 8
VII A p p e n d i c e s 98
A J a v a S c r i p t Cheat Sheet 99
B Debugging J a v a S c r i p t 102
B.1 Here Be Dragons . . . . . . . . . . . . . . . . . . . 102
B.2 Firefox and Firebug . . . . . . . . . . . . . . . . . . 103
B.3 Safari and W e b Inspector . . . . . . . . . . . . . . . 107
B.4 IE6, IE7, t he IE T o o l b a r , and W e b Developer Express 109
B.5 IE8 and Developer T o o l s . . . . . . . . . . . . . . . 112
B.6 Opera a nd Dragonfly . . . . . . . . . . . . . . . . . 113
B.7 V i r t u a l Machines Are Y o u r Friends . . . . . . . . . 114
B.8 The Network May Be Y o u r E nemy . . . . . . . . . 115
C J a v a S c r i p t F rameworks 116
C.1 Prototype, script.aculo.us, a nd Scripty2 . . . . . . . 117
C.2 jQuery a nd jQuery UI . . . . . . . . . . . . . . . . 118
C.3 MooT ools . . . . . . . . . . . . . . . . . . . . . . . 120
C.4 YUI . . . . . . . . . . . . . . . . . . . . . . . . . . 120
C.5 ExtJS . . . . . . . . . . . . . . . . . . . . . . . . . 122
C.6 Dojo . . . . . . . . . . . . . . . . . . . . . . . . . . 123
D Getting Help 125
D.1 Help o n JavaScript in General . . . . . . . . . . . . 125
D.2 Help o n Frameworks . . . . . . . . . . . . . . . . . 127
E Bibliography 130
Index 132
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
Dedication
P o u r Élodie, ma femme, l’étoile de ma vie.
T o Élodie, my wife, a lways my shining star .
Download from Wow! eBook <www.wowebook.com>
Acknowledgments
Writing a book is never easy. A technical book doesn’t need a plot and spares
the a uthor the anguish of the blank page, b u t it subjects the author to a w or ld
of pressure from peers and the duties to be technically accurate and to convey
best practices. T his is why writing a book remains a significant e ndeavor and
why a uthors can use all the help they can g et.
In writing this book, I am first and foremost indebted to the amazing creators
of t he frameworks I mention a nd use. Not o nly d id they grace t he wo rl d with
their praiseworthy wo rk , b u t many a lso took the time to review this book
and make sure I didn’t unintentionally disgrace their brainchildren. I o w e
heartfelt thanks to Sam Stephenson, Thomas Fuchs, John Resig, Alex Russell,
Jack Slocum, and a large number of core developers and contributors who I
couldn’t possibly h ave enough space t o name here. I am e v e n more indebted
to the members o f the Prototype Core team. They’ve been a helpful, highly
skilled b u n c h with whom I ’ve learned so much, especially Andrew Dupont,
T o b i e Langel, and Juriy Z aytsev.
In the search for technical accuracy and ov e r a l l book bettering, a n umber of
people, some of whom I mentioned already , gracefully a greed to re view t his
book and reduce the chances of my making a fool of myself. And I was indeed
graced with an outstanding list of reviewers! I bow with r espect and gratitude
to Dion Almaer, Arnaud Berthomier, Aaron Gustafson, Christian Heilmann,
Dylan Schiemann, and Sam Stephenson.
This i s my s econd b ook with the P ragmatic Programmers. Once again, Dave
Thomas and Andy Hunt opened their virtual doors to me and l et me work
with t heir w on de rf ul staff on this new series of books, the Pragmatic Guides.
It’s been a thrill to work with t he series editor , Susannah Davidson Pfalzer;
my editor, David McClintock (making his Prag debut); the keen-eyed Kim
W i m p s e t t for copyediting; the wizardly Sara L y n n Eastler for producing a
Pragmatic-quality index; and the skillful Steve Peter, whose typesetting
makes t he book look good.
Download from Wow! eBook <www.wowebook.com>
ACKNOWLEDGMENTS 11
Last b u t by no means least, I am forever g rateful to É lodie, my b eloved wife.
She’ s p ut up with four books ov e r the past fi v e years, and she’s always been
supportive a nd loving. I am t he luckiest guy on Earth, and I could n ot d ream
of a better spouse. T his b ook, once again, is for her .
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
Intr oduction
If you’ve been paying e v e n minimal attention to JavaScript these past few
years, you’ ve heard this before: it’s the Next Big Language. Once the province
of half-baked implementations and useless s crolling messages, it has become
a wor ld -c lass, dynamic, object-oriented language with super-fast implemen-
tations o n the client and server sides.
On t he one hand, JavaScript’ s designers are endowing it with a n ew healthy
dose o f power, through the E cmaScript 5 (ES5) specification. On the other
hand, k ick-ass engines (such as V8, Ja vaScriptCore, SpiderMonkey, Rhino,
and Carakan) and emergent standards and technologies (with CommonJS
1
and Node
2
in the lead) make it usable both in b rowsers and as stand-alone,
powerful a rchitectures on the server. Ev en the u pcoming I nternet Explorer 9
is upping its Jav aScript game with the promise of huge speed boosts.
Not only i s JavaScript a powerful, dynamic language, b u t it now has a rich
ecosystem of professional-grade development tools, infrastructures, frame-
wo rk s, and tool kits. It is ve r s a t i l e , fast, and ve r y well suited t o a wide range
of programming tasks, especially when it comes t o web-based applications
and services.
It’s time t o dive in!
What’s This Book About, and Who Is It For?
This book is not really intended to t each you “JavaScript the language.” F o r
one thing, t he language itself is not ve r y complicated, so if you have prior
e x p e r i e n c e in programming any reasonably common language—even if it’s
just the basics (variables, loops, and so on)—you’ll get your bearings easily
enough. Y o u don’t need to actually know s ome JavaScript already (although
it c ould h elp), and you c ertainly don’t n eed t o be a ny sort of programming
guru.
Actually , if you’re looking for the nitty-gritty and the hardcore technical
details of JavaScript, you’ll be better off reading a dedicated resource, such as
1. />2. />Download from Wow! eBook <www.wowebook.com>
THISBOOKANDJA V A SCRIPTLIBRARIES 13
the “JavaScript core skills” section of Opera’s ex c e l l e n t W e b Standards Cur-
riculum.
3
Should you e v e r need e v e n more intricate, implementation-lev el
details, you could then head to either the official specs of the language or
one of the massive “bible” books such as David Flanagan’s J a v a S c r i p t : The
Definitive Guide [Fla06].
This book aims to provide you with quick yet qualitative solutions to common
client-side JavaScript-based tasks, f rom low-level stuff (such as getting a ref-
erence to a DOM element) to intricate features (such as Ajax-based a utocom-
pletion). This means we’ll tackle Jav aScript, CSS, the DOM, Ajax, JSON,
and more. W e won’t go deep into the server side; this book is mostly on the
client side of things ( most o ften the browser). Y o u ’ l l encounter a couple of
tiny PHP scripts along t he way, for illustration p urposes, b u t you c ould write
your server side any way you like—including in Jav aScript, for instance, with
Node!
It’s not just for copying a nd pasting, either . T he t ext f or e ach task takes care
to highlight the key concepts, the potential gotchas, and the technical t ricks
you should take awa y from the task. Ultimately, you should step awa y from
this book as a better J av aScript p rogrammer .
This Book and J a v a S c r i p t Libraries
Let’s speak plainly here. If you’re doing any sort of nontrivial JavaScript pro-
gramming and you’re not relying heavily on good, established frameworks for
it, Y o u ’ r e Doing It Wrong. On the browser side, effectively pulling off web
page scripting is a challenge. Y o u face obstacles from a ll sides: DOM incon-
sistencies, faulty language implementations, CSS quirks, weird Ajax b u g s ,
and more. On the server side, once you h ave a runtime ready, you still face
the enormous task of putting together the basic bricks of an application server
such as a datastore, a network stack, a module system, and so on.
F o r t u n a t e l y, great people already solved these challenges for you. There’s a
wealth of options, too, especially on the client side; take a look at Appendix C,
on p age 116, for details o n the main Jav aScript frameworks.
Because a ny competent and pr agmatic Jav aScript developer will rely on one
or more good frameworks, this book takes care to illustrate all the major
client-side frameworks in what I think of as “basic” tasks. I selected Proto-
type, jQuery, MooT ools, YUI, Dojo, and ExtJS, which should cover most of
the “ dev eloper mind share” in this b u s i n e s s .
3. http://www .opera.com/company/education/curriculum/
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
THISBOOKA T A GLANCE 14
F o r “nonbasic” tasks, I went mostly with my p ersonal favorite, Prototype,
4
e x c e p t for one task (the lightbox one), where the solution I deem superior
ends up being a jQuery plug-in. But really, o nce you master the basic tasks,
you can rewrite or a dapt my solutions using your framework of c hoice. And
indeed, to facilitate this, we’re putting the entire codebase for this book up
in a public GitHub repository.
5
This way, creating a v a r i a n t favoring another
framework (say , jQuery) is as easy as clicking GitHub’s F o r k b u t t o n , and
finding such d erived v e r s i o n s of t he codebase becomes a snap.
Also note that all the code for this book, besides being a v a i l a b l e in a neatly
packaged code a rchive on the book’s website,
6
is a v a i l a b l e live for y our t est-
ing a nd tweaking pleasure a t />This Book at a G lance
This book is divided into t heme-oriented parts, each with a number of tasks.
It concludes with a few appendixes, some of which you may want to read
before the main body of the book (especially the cheat sheet and the one
about debugging Jav aScript).
• P a r t 1 covers a f e w c ritical JavaScript code patterns that are too often
ignored by JavaScript developers. They’re just about the language, so
they’re framework-agnostic b u t indispensible for good coding on a
daily b asis. Be sure t o start here!
• P a r t 2 is mostly about what I refer to as “basic” tasks, focusing on
fundamental DOM and CSS manipulations, plus e v e n t handling and
timers. Because of their “basic” status, I took care to list the relevant
code for all major frameworks, so you can pick whatever suits you best.
Y o u should also check out Appendix C, on page 116, when reading this
part so you get a good picture of the framework landscape and make
informed decisions.
• P a r t 3 is a ll a bout the user interface, especially visual ef fects a nd neat
UI ideas: g ood-looking t ooltips, l ightboxes, image p reloading, infinite
scrolling, and the like.
• P a r t 4 is complementary to Pa r t 3 , because it focuses on forms, a critical
part of most web applications. Among other things, a number of tools
are t here to assist, simplify , and v a l i d a t e input.
• P a r t 5 is all about the client-server relationship, with topics such as
cookies, JSON, and Ajax ( same- a nd cross-domain).
4. Full disclosure: I’m a member of Prototype Core.
5. ascript
6. />Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
HOW TOREADTHISBOOK 15
• P a r t 6, the final part, pushes this idea further by talking with third-
party services, in t he best mashup spirit. I chose three trendy topics
here: p laying with T w i t t e r , Flickr, and geo-related APIs.
• Appendix A is my take on a Jav aScript cheat sheet; I attempted to
condense both the reference of the language and the important tips,
leaving out a fe w language elements I felt were superfluous. I hope
you find it u seful.
• Appendix B is about d ebugging JavaScript; you o w e it to yourself to
know e v e r y t h i n g inside it, if only t o spare you c ountless hours o f hair-
tearing, particularly when i t comes to I nternet Explorer.
• Appendix C tries t o provide a u seful description of the major f rame-
wo rk s I chose to include in this book. I did my best to provide an accu-
rate depiction of all of t hem, presenting them in their best light and
giving you a fe w tips about how best to choose a framework, on a case-
by-case basis.
• Appendix D acts as a quick reference to the best helpful resources
about Jav aScript itself a nd t he main frameworks; it sums up the rel-
e v a n t parts of Appendix C, plus a number of e x t r a resources, mostly
language-related. I put it a t the end of the book so it’s easier to locate.
How to Read This Book
In t he Pragmatic Guide series, each chapter c onsists o f two fa cing pages—
one with text and one with code. If you’ re reading this book o n paper, this
flows naturally. But if you’ re reading an electronic edition of this book, you
may wan t to set y our reader to display t wo pages at once, in the side-by-side
or “ two-up” mode, provided your display i s large enough. This will gi ve you
the b est results.
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
P a r t I
Bread and Butter: Pure J a v a S c r i p t
Download from Wow! eBook <www.wowebook.com>
BREADANDBUTTER: PUREJA V A SCRIPT 17
It’s time to get started. This part serves as a w a r m - u p with a cou-
ple fundamental pieces of know-how aboutbare-bones J a v a S c r i p t .
The code samples in the f o l l o w i n g tasks do not rely on any frame-
w o r k or library.
• Y o u ’ l l learn how to access object properties and methods
dynamically (once y o u r code decides what their name is) in
T a s k 1, Dynamically Selecting a Method/Property.
• In T a s k 2, Achieving Code Privacy with the Module P a t t e r n ,
y o u ’ l l find out how to ke ep internals of y o u r code enclosed
in a private scope to avoid “polluting” other code and ke ep
y o u r stuff self-contained.
• Finally, y o u ’ l l be able to create functions that can be called
with a wide v a r i e t y of arguments, using T a s k 3, Using Optional,
V a r i a b l e , and Named Arguments.
Remember that y o u can get a full source code archive f o r this book
on its online page.
7
Y o u can also access them directly at the demo
site.
8
Finally, don’t f o r g e t that a simple empty we b page (later, with
whatever libraries or frameworks y o u need loaded in), with a J a v a -
Script console open, is all y o u need to test this stuff interactively.
7. />8.
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
DYNAMICALLYSELECTINGA METHOD/PROPERTY 18
1
Dynamically Selecting a
Method/Property
Often you find yourself wanting to call one of two methods (functions
associated with a n object) depending on the situation. Or instead of
functions to call, this c ould be about r eading, or writing, to one of two
possible p roperties ( v ariables a ssociated with a n object). T he code for this
wo ul d look something like what f ollows:
if (condition) {
myObj.method1(someArg);
} else {
myObj.method2(someArg);
}
JavaScript offers a simple syntax for dynamically selecting methods and
properties, a ll relying on t he square brackets ([ ]) operator . Y o u s ee,
JavaScript has two i nterchangeable s yntaxes f or member a ccess ( that i s a
common d ynamic language trait):
obj[expressionResultingInMemberName] == obj.memberName
If you’ve e v e r plucked a v a l u e from an Array cell u sing i ts integer index,
you’ ve already u sed the square brackets operator f or dynamic member
selection! This i s because Array objects have properties named after their
numerical indices ( plus the length property). However, i n this c ase,
JavaScript won’t let you use the d ot operator (.) for d irect access. m y A r ra y. 0
is invalid syntax (too b ad, that would have made a good nerd trick).
Here’s why using the square brackets operator ([ ]) is more p o werful than dot
notation: you can put anything in between the b rackets t o obtain the name
of the member (property or method) that you want to access. Common c ases
include l iterals, v a r i a b l e s holding the member n ame, name composition
e x p r e s s i o n s (mostly s tring concatenations), and quick if/then choices in t he
form of a ternary operator (condition ? v a l u e I f T r u e : v a l u e I f F a l s e ). It’ll all be
turned into a string first and then used to look up the member you wa nt to use.
In JavaScript, functions a re objects too and can be referenced like a ny other
v a l u e . When an e x p r e s s i o n results i n a function, you can call it by u sing
parentheses, possibly with a r guments, j ust like you wo ul d on a function
you’ re calling straight by i ts name.
Note that if the a r guments you want t o pass t o the method v a r y depending on
which technique you s elect, using parentheses may quickly become too
cluttered f or easy reading. In that case, going for a regular if/else structure is
a wiser move.
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
DYNAMICALLYSELECTINGA METHOD/PROPERTY 19
Use the square b rackets ([ ]) operator.
object['propertyName'] // => object.propertyName
object['methodName'](arg1) // => object.methodName(arg1)
T o g g l e behavior.
// Call show() or hide(), depending on shouldBeVisible
element[shouldBeVisible ? 'show' : 'hide']();
// Avoid "heavy" animations on IE to favor immediate reflow
// (assumes we've got a properly set isIE variable)
element[isIE ? 'simpleEffect' : 'complexEffect']();
Compose method n ames.
element[(enable ? 'add' : 'remove') + 'ClassName']('enabled');
T r y this example code in any window.
var love = { firstName: 'Élodie', lastName: 'Porteneuve' };
var useFirstName = true;
alert(love[useFirstName ? 'firstName' : 'lastName']); // => "Élodie"
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
ACHIEVINGCODEPRIVACYWITHTHEMODULEP A T T E R N 20
2
Achieving Code Pr ivacy with the
Module P a t t e r n
The more JavaScript t here is in your codebase, the more your global scope
may g et “polluted” with numerous f unctions a nd v a r i a b l e s that would
actually be better kept p rivate to whatever set of code uses i t. W i t h this
comes the risk of name collision, with one script unintentionally o v e r w r i t i n g
another’s identifiers. This leads to b u g s .
W e need to be a ble to create s elf-contained, opaque batches of JavaScript
code, which would expose only selected i dentifiers, i f any, to t he outside
wo rl d. Indeed, this is a major requirement f or “programming in t he large,”
being a ble to b ring in framew orks a nd libraries in a ny page without r isking a
clash. T his is what t he module p attern is for.
The whole idea of the module pattern is to create a private s cope for
v a r -declared identifiers a nd functions, a scope t hat only functions defined
inside it can a ccess. T o make some o f these definitions accessible to the
outside world, o ur enclosing function has two choices. It may r eturn an
object with t hese selected v a l u e s as properties ( see the facing page); we j ust
need to assign that returned object to a v a r i a b l e in the outside scope. Another
wa y is to pass the enclosing function a scope object that it writes properties
to (to make these g lobal, y ou’ d simply pass window).
In JavaScript, identifiers fi rst u sed with the v a r declaring keyword are l ocal.
(They belong to the function c urrently d efined.) Identifiers first u sed without
v a r are global. (They’re grafted o nto the current default scope, which most
of the time means the global window object.)
In a few specific circumstances, the current default scope will not actually be
global, so there are ways to e xecute code in a context where non-v a r
identifiers will not leak into the global namespace—but that is a bit outside
the s cope of this t ask.
T e c h n i c a l l y , you do not have t o name your “public properties” e x a c t l y like
your private identifiers. Indeed, you could d efine public methods on the fly
in the returned object l iteral u sing anonymous functions. But such practices
wo ul d result in code t hat is more obscure (or misleading) to read
and—perhaps more importantly—to debug. As a rule o f thumb, whenever
possible, try t o define your f unctions using named function e x p re s s i o n s :
function myFunctionName( ) { }
This makes for clearer code and helps a lot with the readability o f the s tack
traces when debugging y our JavaScript.
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
ACHIEVINGCODEPRIVACYWITHTHEMODULEP A T T E R N 21
Use v a r s inside anonymous functions.
(function() {
var privateField = 42;
function innerFunc() {
notSoPrivate = 43;
return notSoPrivate;
}
alert(privateField); // => 42
innerFunc();
alert(notSoPrivate); // => 43
})();
alert(typeof privateField); // => undefined
alert(notSoPrivate); // => 43 (ouch!)
T r y this example: “private properties.”
var obj = (function() {
var privateField = 42;
var publicField = 'foobar';
function processInternals() { alert('Internal stuff: ' + privateField); }
function run() {
processInternals();
alert('Still private stuff: ' + privateField);
alert('Public stuff: ' + publicField);
}
return {
publicField: publicField,
run: run
};
})();
obj.run() // three alerts: Internal, still private, public
obj.publicField // foobar
obj.processInternals() // Undefined
obj.privateField // Undefined
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
USINGOPTIONAL, V ARIABLE, ANDNAMEDARGUMENTS 22
3
Using Optional, V a r i a b l e ,
and Named Arguments
T o master argument-fu, the one thing you must really grok is this: the
parameters y ou e x p l i c i t l y name do n ot constrain the arguments you actually
pass. Every f unction keeps a list of t he arguments p assed to it in a predefined
arguments local v a r i a b l e that behaves like an Array. (It h as length and a [ ]
operator .) So, declaring p arameters is equiv alent to providing local names
for t he first arguments t hat may be passed. If a rguments are indeed p assed in
these positions, these identifiers will refer t o them. I f not, the identifiers will
be undefined.
Now , pay special attention to t he beginning of the optional arguments
e x a m p l e on the facing page. W e ’ r e testing whether a second argument was
passed by u sing an undefined === r a n t test. Why the triple e qual s ign? The
answer l ies in the equivalence rules of Jav aScript. Check this out:
undefined === null // => false
undefined == null // => true
Ah. So, assuming we wou ld consider null a v a l i d v a l u e for ra n t , we need t o
check not only t he v a l u e b u t the t ype of ra n t . That’ s exactly what === does.
It’s the strict e quality operator.
Quite often, though, you’ll use a more lax definition of “missing” f or your
argument. F o r instance, r a n t is supposed to b e a usable text: empty strings,
null, undefined, 0, and f als e would likely a ll be c onsidered useless. All of
these are false-equivalent in JavaScript, s o we could g et pretty concise here:
rant = rant || 'IE6 must die!';
This broad range of false-equivalence in JavaScript is t he main reason I use
the in operator in the f ourth ex a m p l e on the facing page, to d etermine
whether the options object has a given p roperty already—instead of just
testing !options[opt]. This c ode is fairly generic, and we’d like to be able t o
use it anywhere, so we’re t aking a conservative approach and testing actual
property p resence, regardless o f the p roperty’s v a l u e .
That e x a m p l e also shows the proper use of the f o r in construct to iterate
o ver an object’ s properties.
Finally , notice the way I defined t he defaults for repeat( )’s arguments in a
public property o f the f unction itself. This a llows our user code t o modify
the d efaults without resorting to a global object that’s not syntactically
related to our function. T o generically g rab a reference to our function from
within i tself, we use the s pecial callee property of arguments.
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
USINGOPTIONAL, V ARIABLE, ANDNAMEDARGUMENTS 23
Declare parameters (name arguments).
function repeat(rant, times) {
while ( times >= 0)
alert(rant);
}
repeat('IE6 must die!', 5); // => 5 alert boxes in a row
Grab arguments (however m a n y ) .
The b u i l t - i n arguments local v a r i a b l e lets you access t hem dynamically.
This lets you emulate v a r i a b l e - l e n g t h argument l ists, o r varargs.
function repeat(times) {
while ( times >= 0) {
for (var index = 1, len = arguments.length; index < len; ++index) {
alert(arguments[index]);
}
}
}
repeat(2, 'IE6 must die!', 'So should IE7 '); // => 4 alert boxes
T a k e optional arguments with default v a l u e s .
function repeat(times, rant) {
if (undefined === rant) {
rant = 'IE6 must die!';
}
while ( times >= 0) {
alert(rant);
}
}
repeat(3); // => 3 IE6 alert boxes
repeat(3, 'So should IE7 '); // => 3 IE7 alert boxes
Use a literal object f o r p seudo-named arguments.
function repeat(options) {
options = options || {};
for (var opt in (repeat.defaultOptions || {})) {
if (!(opt in options)) {
options[opt] = repeat.defaultOptions[opt];
}
}
for (var index = 0; index < options.times; ++index) {
alert(options.rant);
}
}
repeat.defaultOptions = { times: 2, rant: 'IE6 must die!' };
repeat(); // 2 IE6 alert boxes
repeat({ times: 3 }); // 3 IE6 alert boxes
repeat({ times: 2, rant: 'Flash must die!' }); // 2 Flash alert boxes
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>
P a r t II
The DOM, Events, and Timers
Download from Wow! eBook <www.wowebook.com>
THEDOM,EVENTS, ANDTIMERS 25
So, we started stretching our J a v a S c r i p t m u s c l e s with P a r t I, f o c u s -
ing on a f e w k ey aspects of the language. It is now time to dive into
whatties Ja v a S c r i p t and our w e b pages together: m a n i p u l a t i n g the
DOM.
DOM m a n i p u l a t i o n s mostly f a l l into a f e w categories:
• Getting references to the elements we w a n t to m a n i p u l a t e ,
covered in T a s k 4, Obtaining References to DOM Elements
• Changing their appearance, either instantly or in an
animated f a s h i o n (most of the time it’s aboutshowing, hiding,
or moving them), as described in T a s k 5, Dynamically Styling
Content
• Altering their contents, which is illustrated in T a s k 6, Changing
an Element’s Contents
All of this happens either during page initialization, in reaction to
specific e v e n t s , or sometimes after some time has passed. W e will
therefore discuss the f o l l o w i n g :
• P a g e initialization in T a s k 7, Running Code When the D OM Is
Loaded. More specifically, w e ’ l l discuss how to d etect when
the DOM is loaded so w e can start tweaking it.
• How to listen on ev e n t s , looking at the basics in T a s k 8, Listening
f o r Events (and Stopping), then a iming f o r efficiency with T a s k
9, Leveraging Event Delegation, and finally ga in in g power with
T a s k 10, Decoupling Behaviors with Custom Events.
• How to play with timers (for instance to simulate background
processing), in T a s k 11, Simulating Background Processing.
And because they are such critical building blocks of any signifi-
cant w e b application, I’m going to show y o u code f o r them in all
the ma j o r frameworks I selected f o r this book; at this level, they’re
all functionally equivalent anyway. Compared anatom y w a s all the
r a g e a couple centuries ago; it still remains a g ood w a y to get a
wider perspective on things.
Report erratum
this copy is (P1.0 printing, November 2010)
Download from Wow! eBook <www.wowebook.com>