').dialog({ open: function(){ $(this).load('/url/to/resource'); }, title: 'A dynamically loaded dialog' });
element on the fly, and turn it into a dialog box just as if it were an existing element. The options specify its title, and a callback for dialogopen events that loads the content element (set as the function context) using the load() method. In the scenarios we’ve seen so far, regardless of whether the content already existed on the page or was loaded via Ajax, the content exists within the DOM of the current page. What if we want the dialog box body to be its own page? Although it’s convenient to have the dialog box content be part of the same DOM as its parent, if the dialog box content and the page content need to interact in any way, we might want the dialog box content to be a separate page unto itself. The most common reason may be because the content needs its own styles and scripts that we don’t want to include in every parent page in which we plan to use the dialog box. How could we accomplish this? Is there support in HTML for using a separate page as a part of another page? Of course ... the <iframe> element! Consider this: $('<iframe src="content.html" id="testDialog">').dialog({ title: 'iframe dialog', buttons: { Dismiss: function(){ $(this).dialog('close'); } } });
Here we dynamically create an <iframe> element, specifying its source and an id, and make it into a dialog box. The options we pass to the dialog() method give the dialog box its title and a Dismiss button that closes the dialog box. Is this awesome or what? But our self-admiration is short-lived when we display the dialog box and see a problem. The scrollbar for the <iframe> is clipped by the dialog chrome, as shown in the left half of figure 11.16. What we want, of course, is for the dialog box to appear as shown in the right half of the figure. Because the <iframe> appears a bit too wide, we could attempt to narrow it with a CSS rule, but to our chagrin, we find that doesn’t work. A little digging reveals that a CSS style of width: auto is placed right on the <iframe> element by the dialog() method, defeating any attempt to style the <iframe> indirectly.
Summary
413
Figure 11.16 Our victory dance was cut short by the clipping of the scroll bar shown at left—how can we fix it as shown at right?
But that’s OK. We’ll just use a bigger sledgehammer. Let’s add the following option to the dialog() call: open: function(){ $(this).css('width','95%'); }
This overrides the style placed on the <iframe> when the dialog box is opened. Bear in mind that this approach isn’t without its pitfalls. For example, any buttons are created in the parent page, and interaction between the buttons and the page loaded into the <iframe> will need to communicate across the two windows. The source for this example can be found in file chapter11/dialogs/iframe.dialog.html.
11.9 Summary Wow. This was a long chapter, but we learned a great deal from it. We saw how jQuery UI builds upon the interactions and effects that it provides, and which we explored in the previous chapters, to allow us to create various widgets that help us present intuitive and easy-to-use interfaces to our users. We learned about the button widget that augments the look and feel of conventional HTML buttons so that they play well in the jQuery UI sandbox. Widgets that allow our users to enter data types that have traditionally been fraught with problems, namely numeric and date data, are provided in the guise of sliders and datepickers. Autocomplete widgets round out the data entry widgets, letting users quickly filter through large sets of data. Progress bars give us the ability to communicate completion percentage status to our users in a graphical, easy-to-understand display. And finally, we saw three widgets that let us organize our content in varying fashions: tabs, the accordion, and the dialog box.
414
CHAPTER 11 jQuery UI widgets: Beyond HTML controls
Added to our toolbox, these widgets give us a wider range of possibilities for our interfaces. But that’s just the official set of widgets provided by jQuery UI. As we’ve seen firsthand, jQuery is designed to extend easily, and the jQuery community hasn’t been sitting on its hands. Hundreds, if not many thousands, of other plugin controls exist, just waiting for us to discover them. A good place to start is http://plugins.jquery.com/.
11.10 The end? Hardly! Even though we’ve presented the entire API for jQuery and jQuery UI within the confines of this book, it would have been impossible to show you all the many ways that these broad APIs can be used on our pages. The examples we presented were chosen specifically to lead you down the path of discovering how you can use jQuery to solve the problems that you encounter on a day-to-day basis on your web application pages. jQuery is a living project. Astoundingly so! Heck, it was quite a chore for your authors to keep up with the rapid developments in the libraries over the course of writing this book. The core library is constantly evolving into a more useful resource, and more and more plugins are appearing on practically a daily basis. And the pace of development for jQuery UI is practically exhausting. We urge you to keep track of the developments in the jQuery community and sincerely hope that this book has been a great help in starting you on the path to writing better web applications in less time and with less code than you might have ever believed possible. We wish you health and happiness, and may all your bugs be easily solvable!
appendix: JavaScript that you need to know but might not!
This appendix covers Which JavaScript concepts are important for effectively
using jQuery JavaScript Object basics How functions are first-class objects Determining (and controlling) what this means What’s a closure?
One of the great benefits that jQuery brings to our web applications is the ability to implement a great deal of scripting-enabled behavior without having to write a whole lot of script ourselves. jQuery handles the nuts-and-bolts details so that we can concentrate on the job of making our applications do what they need to do!
415
416
APPENDIX
JavaScript that you need to know but might not!
For the first few chapters in this book, we only needed rudimentary JavaScript skills to code and understand the examples. In the chapters on advanced topics such as event handling, animations, and Ajax, we must understand a handful of fundamental JavaScript concepts to make effective use of the jQuery library. You may find that a lot of things that you, perhaps, took for granted in JavaScript (or took on blind faith) will start to make more sense. We’re not going to go into an exhaustive study of all JavaScript concepts here—that’s not the purpose of this book. The purpose of this book is to get us up and running with effective jQuery in the shortest time possible. To that end, this appendix will concentrate on the fundamental concepts that we need to make the most effective use of jQuery in our web applications. The most important of these concepts is that functions are first-class objects in JavaScript, which is a result of the way JavaScript defines and deals with functions. What do we mean by that? In order to understand what it means for a function to be an object, let alone a first-class one, we must first make sure that we understand what a JavaScript object is all about. So let’s dive right in.
A.1
JavaScript Object fundamentals The majority of object-oriented (OO) languages define a fundamental Object type of some kind from which all other objects are derived. In JavaScript, the fundamental Object serves as the basis for all other objects, but that’s where the comparison stops. At its basic level, the JavaScript Object has little in common with the fundamental object defined by most other OO languages. At first glance, a JavaScript Object may seem like a boring and mundane item. Once created, it holds no data and exposes little in the way of semantics. But those limited semantics do give it a great deal of potential. Let’s see how.
A.1.1
How objects come to be A new object comes into existence via the new operator paired with the Object constructor. Creating an object is as easy as this: var shinyAndNew = new Object();
It could be even easier (as we’ll see shortly), but this will do for now. But what can we do with this new object? It seemingly contains nothing: no information, no complex semantics, nothing. Our brand-new, shiny object doesn’t get interesting until we start adding things to it—things known as properties.
A.1.2
Properties of objects Like their server-side counterparts, JavaScript objects can contain data and possess methods (well ... sort of, but that’s getting ahead of ourselves). Unlike those serverside brethren, these elements aren’t predeclared for an object; we create them dynamically as needed.
JavaScript Object fundamentals
417
Take a look at the following code fragment: var ride = new Object(); ride.make = 'Yamaha'; ride.model = 'V-Star Silverado 1100'; ride.year = 2005; ride.purchased = new Date(2005,3,12);
Here we create a new Object instance and assign it to a variable named ride. We then populate this variable with a number of properties of different types: two strings, a number, and an instance of the Date type. We don’t need to declare these properties prior to assigning them; they come into being merely by the act of our assigning a value to them. That’s mighty powerful juju that gives us a great deal of flexibility. But before we get too giddy, let’s remember that flexibility always comes with a price! For example, let’s say that in subsequent code on our scripted HTML page, we want to change the value of the purchase date: ride.purchased = new Date(2005,2,1);
No problem ... unless we make an inadvertent typo such as ride.purcahsed = new Date(2005,2,1);
There’s no compiler to warn us that we’ve made a mistake; a new property named purcahsed is cheerfully created on our behalf, leaving us to wonder later why the new date didn’t take when we reference the correctly spelled property. With great power comes great responsibility (where have we heard that before?), so type carefully! JavaScript debuggers, like Firebug for Firefox, can be lifesavers when dealing with these issues. Because typos such as these frequently result in no JavaScript errors, relying on JavaScript consoles or error dialog boxes is usually less than effective.
NOTE
From this example, we’ve learned that an instance of the JavaScript Object, which we’ll simply refer to as an object from here forward, is a collection of properties, each of which consists of a name and a value. The name of a property is a string, and the value can be any JavaScript object, be it a Number, String, Date, Array, basic Object, or any other JavaScript object type (including, as we shall see, functions). This means the primary purpose of an Object instance is to serve as a container for a named collection of other objects. This may remind you of concepts in other languages: a Java map for example, or dictionaries or hashes in other languages. Properties aren’t limited to types such as String or Number. An object property can be another Object instance, which in turn has its own set of properties, which can in turn be objects with their own properties, and so on, to any depth that makes sense for the data that we are trying to model.
418
APPENDIX
JavaScript that you need to know but might not!
Let’s say that we add a new property to our ride instance that identifies the owner of the vehicle. This property is another JavaScript object that contains properties such as the name and occupation of the owner: var owner = new Object(); owner.name = 'Spike Spiegel'; owner.occupation = 'bounty hunter'; ride.owner = owner;
To access the nested property, we write this: var ownerName = ride.owner.name;
There are no limits to the nesting levels we can employ (except the limits of good sense). When finished—up to this point—our object hierarchy is as shown in figure A.1. Note how each value in the figure is a distinct instance of a JavaScript type. There’s no need for all the intermediary variables (such as owner) that we’ve created for illustrative purposes in these code fragments. In a short while, we’ll see more efficient and compact ways to declare objects and their properties.
NOTE
Up to this point, we’ve referenced properties of an object by using the dot (period character) operator. But, as it turns out, that’s a synonym for a more general operator for performing property referencing. What if, for example, we have a property named color.scheme? Do you notice the period in the middle of the name? It throws a monkey wrench into the works because the JavaScript interpreter will try to look up scheme as a nested property of color. “Well, just don’t do that!” you say. But what about space characters? What about other characters that could be mistaken for delimiters rather than part of a name? Object
String
Yamaha
String
V-Star Silverado 1100
make model year
Number
2005
purchased owner
Date
3-12-2005
Object name occupation
String
Spike Spiegel
String
bounty hunter
Figure A.1 Our object hierarchy shows that Objects are containers for named references to other Objects or JavaScript built-in types.
JavaScript Object fundamentals
419
And most importantly, what if we don’t even know what the property name is, but we have it as a value in another variable or as the result of an expression evaluation? For all these cases, the dot operator is inadequate, and we must use the more general notation for accessing properties. The format of the general property reference operator is object[propertyNameExpression]
where propertyNameExpression is a JavaScript expression whose evaluation as a string forms the name of the property to be referenced. For example, all three of the following references are equivalent: ride.make ride['make'] ride['m'+'a'+'k'+'e']
So is this reference: var p = 'make'; ride[p];
Using the general reference operator is the only way to reference properties whose names don’t form valid JavaScript identifiers, such as this, ride["a property name that's rather odd!"]
which contains characters not legal for JavaScript identifiers, or whose names are the values of other variables. Building up objects by creating new instances with the new operator and assigning each property using separate assignment statements can be a tedious affair. In the next section, we’ll look at a more compact and easy-to-read notation for declaring objects and their properties.
A.1.3
Object literals In the previous section, we created an object that modeled some of the properties of a motorcycle, assigning it to a variable named ride. To do so, we used two new operations, an intermediary variable named owner, and a bunch of assignment statements. This is tedious—as well as wordy and error-prone—and it is difficult for us to visually grasp the structure of the object during a quick inspection of the code. Luckily, we can use a notation that’s more compact and easier to visually scan. Consider the following statement: var ride = { make: 'Yamaha', model: 'V-Star Silverado 1100', year: 2005, purchased: new Date(2005,3,12), owner: { name: 'Spike Spiegel', occupation: 'bounty hunter' } };
420
APPENDIX
JavaScript that you need to know but might not!
Using an object literal, this fragment creates the same ride object that we built up with assignment statements in the previous section. This notation, which has come to be termed JSON (JavaScript Object Notation1), is much preferred by most page authors over the multiple-assignment means of object building. Its structure is simple; an object is denoted by a matching pair of braces, within which properties are listed delimited by commas. Each property is denoted by listing its name and value separated by a colon character. Technically, JSON has no way to express date values, primarily because JavaScript itself lacks any kind of date literal. When used in script, the Date constructor is usually employed as shown in the previous example. When used as an interchange format, dates are frequently expressed either as a string containing the ISO 8601 format or a number expressing the date as the millisecond value returned by Date.getTime(). Note also that when using JSON as an interchange format, there are some stricter rules that need to be followed, such as quoting property names. See http://www.json.org or RFC 4627 (http://www.ietf.org/rfc/rfc4627.txt) for more details. NOTE
As we can see by the declaration of the owner property, object declarations can be nested. By the way, we can also express arrays in JSON by placing the comma-delimited list of elements within square brackets, as in the following: var someValues = [2,3,5,7,11,13,17,19,23,29,31,37];
As we’ve seen in the examples presented in this section, object references are frequently stored in variables or in properties of other objects. Let’s take a look at a special case of the latter scenario.
A.1.4
Objects as window properties Up to this point, we’ve seen two ways to store a reference to a JavaScript object: variables and properties. These two means of storing references use differing notation, as shown in the following snippet: var aVariable = 'Before I teamed up with you, I led quite a normal life.'; someObject.aProperty = 'You move that line as you see fit for yourself.';
These two statements each assign a String instance (created via literals) to something: a variable in the first statement, and an object property in the second. (Kudos to you if you can identify the source of the obscure quotes; no cheating with Google! There was a clue earlier in this appendix.)
1
For more information, you can visit http://www.json.org/.
Functions as first-class citizens
421
But are these statements really performing different operations? As it turns out, they’re not! When the var keyword is used at the top level, outside the body of any containing function, it’s only a programmer-friendly notation for referencing a property of the predefined JavaScript window object. Any reference made in top-level scope is implicitly made on the window instance. This means that all of the following statements, if made at the top level (that is, outside the scope of a function), are equivalent: var foo = bar;
and window.foo = bar;
and foo = bar;
Regardless of which notation is used, a window property named foo is created (if it’s not already in existence) and assigned the value of bar. Also, note that because bar is unqualified, it’s assumed to be a property on window. It probably won’t get us into conceptual trouble to think of top-level scope as window scope because any unqualified references at the top level are assumed to be window properties. The scoping rules get more complex when we delve deeper into the bodies of functions—much more complex, in fact—but we’ll be addressing that soon enough. That pretty much covers things for our overview of the JavaScript Object. These are the important concepts to take away from this discussion: A JavaScript object is an unordered collection of properties. Properties consist of a name and a value. Objects can be declared using object literals. Top-level variables are properties of window.
Now, let’s discuss what we meant when we referred to JavaScript functions as first-class objects.
A.2
Functions as first-class citizens In many traditional OO languages, objects can contain data and they can possess methods. In these languages, the data and methods are usually distinct concepts; JavaScript walks a different path. Functions in JavaScript are considered objects like any of the other object types that are defined in JavaScript, such as Strings, Numbers, or Dates. Like other objects, functions are defined by a JavaScript constructor—in this case Function—and they can be Assigned to variables Assigned as a property of an object
422
APPENDIX
JavaScript that you need to know but might not!
Passed as a parameter Returned as a function result Created using literals
Because functions are treated in the same way as other objects in the language, we say that functions are first-class objects. But you might be thinking to yourself that functions are fundamentally different from other object types like String or Number because they possess not only a value (in the case of a Function instance, its body) but also a name. Well, not so fast!
A.2.1
What’s in a name? A large percentage of JavaScript programmers operate under a false assumption that functions are named entities. Not so. If you’re one of these programmers, you’ve been fooled by a Jedi mind trick. As with other instances of objects—be they Strings, Dates, or Numbers—functions are referenced only when they are assigned to variables, properties, or parameters. Let’s consider objects of type Number. We frequently express instances of Number by their literal notation, such as 213. The statement 213;
is perfectly valid, but it is also perfectly useless. The Number instance isn’t all that useful unless it has been assigned to a property or a variable, or bound to a parameter name. Otherwise, we have no way to reference the disembodied instance. The same applies to instances of Function objects. “But, but, but ...,” you might be saying, “what about the following code?” function doSomethingWonderful() { alert('does something wonderful'); }
“Doesn’t that create a function named doSomethingWonderful?” No, it doesn’t. Although that notation may seem familiar and is ubiquitously used to create top-level functions, it’s the same syntactic sugar used by var to create window properties. The function keyword automatically creates a Function instance and assigns it to a window property created using the function “name” (what we referred to earlier as a Jedi mind trick), as in the following: doSomethingWonderful = function() { alert('does something wonderful'); }
If that looks weird to you, consider another statement using the exact same format, except this time using a Number literal: aWonderfulNumber = 213;
There’s nothing strange about that, and the statement assigning a function to a toplevel variable (the window property) is no different; a function literal is used to create
Functions as first-class citizens
423
window aWonderfulNumber
Number
213
doSomethingWonderful
Function
() { alert('does something wonderful'); }
Figure A.2 A Function instance is a nameless object like the Number 213 or any other JavaScript value. It’s named only by references that are made to it.
an instance of Function and then is assigned to the variable doSomethingWonderful in the same way that our Number literal 213 was used to assign a Number instance to the variable aWonderfulNumber. If you’ve never seen the syntax for a function literal, it might seem odd. It’s composed of the keyword function, followed by its parameter list enclosed in parentheses, then followed by the function body. When we declare a top-level named function, a Function instance is created and assigned to a property of window that’s automatically created using the so-called function name. The Function instance itself no more has a name than a Number literal or a String literal. Figure A.2 illustrates this concept. Remember that when a top-level variable is created in an HTML page, the variable is created as a property of the window instance. Therefore, the following statements are all equivalent: function hello(){ alert('Hi there!'); } hello = function(){ alert('Hi there!'); } window.hello = function(){ alert('Hi there!'); }
Although this may seem like syntactic juggling, it’s important to understanding that Function instances are values that can be assigned to variables, properties, or parameters just like instances of other object types. And like those other object types, nameless disembodied instances aren’t of any use unless they’re Gecko browsers and function names assigned to a variable, property, or Browsers based on the Gecko layout engine, parameter through which they can such as Firefox and Camino, store the name of functions defined using the top-level syntax in a be referenced. nonstandard property of the function instance We’ve seen examples of assignnamed name. Although this may not be of much ing functions to variables and propuse to the general development public, particularly considering its confinement to erties, but what about passing Gecko-based browsers, it’s of great value to functions as parameters? Let’s take a writers of browser plugins and debuggers. look at why and how we do that.
424
A.2.2
APPENDIX
JavaScript that you need to know but might not!
Functions as callbacks Top-level functions are all well and good when our code follows a nice and orderly synchronous flow, but the nature of HTML pages—once loaded—is far from synchronous. Whether we’re handling events, instituting timers, or making Ajax requests, the nature of the code in a web page is asynchronous. And one of the most prevalent concepts in asynchronous programming is the notion of a callback function. Let’s take the example of a timer. We can cause a timer to fire—let’s say in five seconds—by passing the appropriate duration value to the window.setTimeout() method. But how does that method let us know when the timer has expired so that we can do whatever it is that we’re waiting around for? It does so by invoking a function that we supply. Let’s consider the following code: function hello() { alert('Hi there!'); } setTimeout(hello,5000);
We declare a function named hello and set a timer to fire in 5 seconds, expressed as 5000 milliseconds by the second parameter. In the first parameter to the setTimeout() method, we pass a function reference. Passing a function as a parameter is no different than passing any other value—just as we passed a Number in the second parameter. When the timer expires, the hello function is called. Because the setTimeout() method makes a call back to a function in our own code, that function is termed a callback function. This code example would be considered naive by most advanced JavaScript coders because the creation of the hello name is unnecessary. Unless the function is to be called elsewhere in the page, there’s no need to create the window property hello to momentarily store the Function instance to pass it as the callback parameter. The more elegant way to code this fragment is setTimeout(function() { alert('Hi there!'); },5000);
in which we express the function literal directly in the parameter list, and no needless name is generated. This is an idiom that we’ll often see used in jQuery code when there is no need for a function instance to be assigned to a top-level property. The functions we’ve created in the examples so far are either top-level functions (which we know are top-level window properties) or assigned to parameters in a function call. We can also assign Function instances to properties of objects, and that’s where things get really interesting. Read on ...
A.2.3
What’s this all about? OO languages automatically provide a means to reference the current instance of an object from within a method. In languages like Java and C++, a variable named this points to that current instance. In JavaScript, a similar concept exists and even uses the same this keyword, which also provides access to an object associated with a
425
Functions as first-class citizens
function. But OO programmers beware! The JavaScript implementation of this differs from its OO counterparts in subtle but significant ways. In class-based OO languages, the this pointer generally references the instance of the class for which the method has been declared. In JavaScript, where functions are first-class objects that aren’t declared as part of anything, the object referenced by this—termed the function context—is determined not by how the function is declared but by how it’s invoked. This means that the same function can have different contexts depending on how it’s called. That may seem freaky at first, but it can be quite useful. In the default case, the context (this) of an invocation of the function is the object whose property contains the reference used to invoke the function. Let’s look back to our motorcycle example for a demonstration, amending the object creation as follows (additions highlighted in bold): var ride = { make: 'Yamaha', model: 'V-Star Silverado 1100', year: 2005, purchased: new Date(2005,3,12), owner: {name: 'Spike Spiegel',occupation: 'bounty hunter'}, whatAmI: function() { return this.year+' '+this.make+' '+this.model; } };
To our original example code, we add a property named whatAmI that references a Function instance. Our new object hierarchy, with the Function instance assigned to the property named whatAmI, is shown in figure A.3. Object
String
Yamaha
String
V-Star Silverado 1100
make model year
Number
2005
purchased owner
Date
3-12-2005
whatAmI
Object
String
Spike Spiegel
String
bounty hunter
name occupation
Function
() { return this.year+' '+this.make+' '+this.model; }
Figure A.3 This model clearly shows that the function isn’t part of the Object but is only referenced from the Object property named whatAmI.
426
APPENDIX
JavaScript that you need to know but might not!
When the function is invoked through the property reference, like this, var bike = ride.whatAmI();
the function context (the this reference) is set to the object instance pointed to by ride. As a result, the variable bike gets set to the string 2005 Yamaha V-Star Silverado 1100 because the function picks up the properties of the object through which it was invoked via this. The same is true of top-level functions. Remember that top-level functions are properties of window, so their function context, when called as top-level functions, is the window object. Although that may be the usual and implicit behavior, JavaScript gives us the means to explicitly control what’s used as the function context. We can set the function context to whatever we want by invoking a function via the Function methods call() or apply(). Yes, as first-class objects, even functions have methods as defined by the Function constructor. The call() method invokes the function specifying, as its first parameter, the object to serve as the function context, while the remainder of the parameters become the parameters of the called function—the second parameter to call() becomes the first argument of the called function, and so on. The apply() method works in a similar fashion except that its second parameter is expected to be an array of objects that become the arguments to the called function. Confused? It’s time for a more comprehensive example. Consider the code of listing A.1 (found in the downloadable code as appendix/function.context.html). Listing A.1
The function context value depends on how the function is invoked
Function Context Example <script> var o1 = {handle:'o1'}; var o2 = {handle:'o2'}; var o3 = {handle:'o3'}; window.handle = 'window';
B
function whoAmI() { return this.handle; }
C
o1.identifyMe = whoAmI;
D
alert(whoAmI()); alert(o1.identifyMe()); alert(whoAmI.call(o2)); alert(whoAmI.apply(o3));
E F G H
Functions as first-class citizens
427
In this example, we define three simple objects, each with a handle property that makes it easy to identify the object given a reference B. We also add a handle property to the window instance so that it’s also readily identifiable. We then define a top-level function that returns the value of the handle property for whatever object serves as its function context C and assign the same function instance to a property of object o1 named identifyMe D. We can say that this creates a method on o1 named identifyMe, although it’s important to note that the function is declared independently of the object. Finally, we issue four alerts, each of which uses a different mechanism to invoke the same function instance. When loaded into a browser, the sequence of four alerts is as shown in figure A.4.
Figure A.4 The object serving as the function context changes with the manner in which the function is called.
428
APPENDIX
JavaScript that you need to know but might not!
This sequence of alerts illustrates the following: When the function is called directly as a top-level function, the function context
is the window instance E. When called as a property of an object (o1 in this case), the object becomes the function context of the function invocation F. We could say that the function acts as a method for that object—as in OO languages. But take care not to get too blasé about this analogy. You can be led astray if you’re not careful, as the remainder of this example’s results will show. Employing the call() method of Function causes the function context to be set to whatever object is passed as the first parameter to call()—in this case, o2 G. In this example, the function acts like a method to o2, even though it has no association whatsoever—even as a property—with o2. As with call(), using the apply() method of Function sets the function context to whatever object is passed as the first parameter H. The difference between these two methods only becomes significant when parameters are passed to the function (which we didn’t do in this example for simplicity). This example page clearly demonstrates that the function context is determined on a per invocation basis and that a single function can be called with any object acting as its context. As a result, it’s probably never correct to say that a function is a method of an object. It’s much more correct to state the following: A function f acts as a method of object o when o serves as the function context of the invocation of f.
As a further illustration of this concept, consider the effect of adding the following statement to our example: alert(o1.identifyMe.call(o3));
Even though we reference the function as a property of o1, the function context for this invocation is o3, further emphasizing that it’s not how a function is declared but how it’s invoked that determines its function context. When using jQuery commands and functions that employ callbacks, this proves to be an important concept. We saw this concept in action early on (even if you didn’t realize it at the time) in section 2.3.3 of chapter 2, where we supplied a callback function to the filter() method of $ and that function was sequentially invoked with each element of the wrapped set serving as its function context in turn. Now that we understand how functions can act as methods of objects, let’s turn our attention to another advanced function topic that will play an important role in effective usage of jQuery: closures.
A.2.4
Closures To page authors coming from a traditional OO or procedural programming background, closures are often an odd concept to grasp, whereas to those with a functional
429
Functions as first-class citizens
programming background, they’re a familiar and cozy concept. For the uninitiated, let’s answer the question: What are closures? Stated as simply as possible, a closure is a Function instance coupled with the local variables from its environment that are necessary for its execution. When a function is declared, it has the ability to reference any variables that are in its scope at the point of declaration. This is expected and should be no surprise to any developer from any background. But, with closures, these variables are carried along with the function even after the point of declaration has gone out of scope, closing the declaration. The ability for callback functions to reference the local variables in effect when they were declared is an essential tool for writing effective JavaScript. Using a timer once again, let’s look at the illustrative example in listing A.2 (the file appendixA/closure.html). Listing A.2
Closures allow access to the scope of a function's declaration
Closure Example <script type="text/javascript" src="../scripts/jquery-1.2.js"> <script> $(function(){ var local = 1; window.setInterval(function(){ $('#display') .append('
At '+new Date()+' local='+local+'
'); local++; },3000); });
B
C
D
E
In this example, we define a ready handler that fires after the DOM loads. In this handler, we declare a local variable named local B and assign it a numeric value of 1. We then use the window.setInterval() method to establish a timer that will fire every 3 seconds C. As the callback for the timer, we specify an inline function that references the local variable and shows the current time and the value of local, by writing a
element into an element named display that’s defined in the page body E. As part of the callback, the local variable’s value is also incremented D. Prior to running this example, if we were unfamiliar with closures, we might look at this code and see some problems. We might surmise that, because the callback will fire off three seconds after the page is loaded (long after the ready handler has finished executing), the value of local is undefined during the execution of the callback
430
APPENDIX
JavaScript that you need to know but might not!
Figure A.5 Closures allow callbacks to access their environment even if that environment has gone out of scope.
function. After all, the block in which local is declared goes out of scope when the ready handler finishes, right? But on loading the page and letting it run for a short time, we see the display shown in figure A.5. It works! But how? Although it is true that the block in which local is declared goes out of scope when the ready handler exits, the closure created by the declaration of the function, which includes local, stays in scope for the lifetime of the function. You might have noted that the closure, as with all closures in JavaScript, was created implicitly without the need for explicit syntax as is required in some other languages that support closures. This is a doubleedged sword that makes it easy to create closures (whether you intend to or not!) but it can make them difficult to spot in the code. Unintended closures can have unintended consequences. For example, circular references can lead to memory leaks. A classic example of this is the creation of DOM elements that refer back to closure variables, preventing those variables from being reclaimed.
NOTE
Another important feature of closures is that a function context is never included as part of the closure. For example, the following code won’t execute as we might expect: ... this.id = 'someID'; $('*').each(function(){ alert(this.id); });
Remember that each function invocation has its own function context so that, in the preceding code, the function context within the callback function passed to each() is an element from the jQuery wrapped set, not the property of the outer function set to 'someID'. Each invocation of the callback function displays an alert box showing the id of each element in the wrapped set in turn.
Summary
431
When access to the object serving as the function context in the outer function is needed, we can employ a common idiom to create a copy of the this reference in a local variable that will be included in the closure. Consider the following change to our example: this.id = 'someID'; var outer = this; $('*').each(function(){ alert(outer.id); });
The local variable outer, which is assigned a reference to the outer function’s function context, becomes part of the closure and can be accessed in the callback function. The changed code now displays an alert showing the string 'someID' as many times as there are elements in the wrapped set. We’ll find closures indispensable when creating elegant code using jQuery commands that utilize asynchronous callbacks, which is particularly true in the areas of Ajax requests and event handling.
A.3
Summary JavaScript is a language that’s widely used across the web, but it’s often not deeply used by many of the page authors writing it. In this appendix, we introduced some of the deeper aspects of the language that we must understand to use jQuery effectively on our pages. We saw that a JavaScript Object primarily exists to be a container for other objects. If you have an OO background, thinking of an Object instance as an unordered collection of name/value pairs may be a far cry from what you think of as an object, but it’s an important concept to grasp when writing JavaScript of even moderate complexity. Functions in JavaScript are first-class citizens that can be declared and referenced in a manner similar to the other object types. We can declare them using literal notation, store them in variables and object properties, and even pass them to other functions as parameters to serve as callback functions. The term function context describes the object that’s referenced by the this pointer during the invocation of a function. Although a function can be made to act like a method of an object by setting the object as the function context, functions aren’t declared as methods of any single object. The manner of invocation (possibly explicitly controlled by the caller) determines the function context of the invocation. Finally, we saw how a function declaration and its environment form a closure allowing the function, when later invoked, to access those local variables that become part of the closure. With these concepts firmly under our belts, we’re ready to face the challenges that confront us when writing effective JavaScript using jQuery on our pages.
index Symbols ^ See caret character : See colon character * See asterisk character % operator, usage example 230 $ 16, 170 .ajax() function 261 list of options 261 setting defaults 264 .ajaxSetup() function 264 .browser 170 user agent detection flags 175 .browser.mozilla flag 175 .browser.msie flag 175–176 .browser.opera flag 175 .browser.safari flag 175 .browser.version flag 175 .contains() function 194 .data() function 195 .datepicker.formatDate() method 388 .datepicker.iso8601week() method 389 .datepicker.parseDate() method 388 .datepicker.setDefaults() method 387 .each() function 182 performance advantage over each() 182 .extend() function 188, 209, 365 usage example 189, 209, 227
.fn 216 usage example 270 .fx.off 170 disabling animations 170 .get() function 252 usage example 252 .getJSON() function 254 .getScript() function 200 usage example 201 .globalEval() function 199 .grep() function 183 .inArray() function 186 .isArray() function 193 .isEmptyObject() function 193 .isFunction() function 193 .isPlainObject() function 193 .isXMLDoc() function 193 .makeArray() function 186 .map() function 184 .merge() function 187 .noConflict() function 177, 180, 207 usage example 16 .noop() function 194 .param() function 190 .param() Lab Page 192 .parseJSON() function 198 .post() function 255 .proxy() function 196 .removeData () function 195 .support 170 .support object 173, 202 .support.boxModel flag 173 .support.cssFloat flag 173
433
.support.hrefNormalized flag 173 .support.htmlSerialize flag 173 .support.leadingWhitespace flag 173 .support.noCloneEvent flag 173 .support.objectAll flag 173 .support.opacity flag 173 .support.scriptEval flag 173 .support.style flag 173 .support.tbody flag 173 .trim() function 181 .unique() function 187 alias for jQuery name 177, 216 as function namespace 169 as namespace prefix 11 avoiding name collisions 207 conflicts with 207 defining locally 178 identifier 177, 180 in plugins 207 in ready handler 179 jQuery object 178 namespace 215, 229 namespace object 212 naming conflicts 16 sharing with other libraries 177 use in identifiers 142 use in Prototype 177 variables defined on 170 wrapper 15 See also dollar sign character
434 $() 9, 11, 14 adding wrapper methods 233 creating DOM elements 13, 32 creating wrappers 18 defining ready handler 11 function 9 HTML fragment 20 methods 11 multiple contexts 21 selecting elements 18 selector 20 specifying element attributes 33 supplying context 20
A a element 354 abbr element 274 absolute position selectors 29 acceptable element 317 accordion widgets 286 creating 398 example 398 accordion() method, syntax 399 accordionchange event 403 accordionchangestart event 403 accordions 397 events 402 loading using Ajax 404 options 400 styling 403 typical construct 398 Accordions Lab 402 active elements 73 ActiveX control 235, 237 ActiveX object 237 add() method 41–42 adding existing elements 44 adding new elements 44 element references 44 usage example 41 addClass() method 66 extended by jQuery UI 297 addEventListener() method 102, 104, 172 attachEvent() method 106 adding a wrapper method 219 after() method 80 aggregate selectors 41 Ajax 101, 167, 184, 234–235 accordians 404 Ajax in Action 236 Ajax in Practice 236
INDEX
as acronym 253 browser-independence 237 complicating event handling 115 comprehensive 278 comprehensive example 268 comprehensive jQuery API 261, 263 concurrent requests 268 diagrammed 236 GET 253 global events 265 global functions 268 growth catalyst 3 HTTP requests 250, 252 iframes, using 236 initializing 237–238 jQuery events 265 loading content 243 loading scripts 200 local events 265 overview 236 pain points 241 POST requests 254 progress bar 363 ready state handler 239 request life cycle 236 request parameters 239 responses 240–241 responseText 240 responseXML 241 return types 262 server-side independence 247 setting defaults 264 setting timeout 262 sortables 323 specifying content type 262 synchronous request 263 tabbed content 390 term coined 236 tracking requests 266 with live events 116 XML, not using 240 ajaxComplete() method 265–266 usage example 276 ajaxError() method 265–266 ajaxSend() method 265–266 ajaxStart() method 265–266 behavior 267 ajaxStop() method 265–266 behavior 267 ajaxSuccess() method 265–266 algorithms 213 alpha filters 70
Amazon 3 anchor elements 359 anchor tags, accordions 404 andSelf() method 53 animate() method 154, 159, 161, 170 CSS properties 292 usage example 155 animated elements 296 animated GIFs 55, 138 animated graphics, showing busy state 265 animation 138 blocking 161 frames 155 queue 159, 167 animation methods 299 simultaneous 159 animations animation engine 155 browsers 171 CSS properties 155 custom 154–156 custom drop 156–157 custom fading 155 custom puff 157, 159 custom scale 156 disabling 153, 170 easing 155 fancy 139 global flag 153 height property 155 left property 155 mobile devices 171 multiple 155, 160 non-blocking 146 opacity property 155 plugins 154 queuing 155, 159, 161–162 simultaneous 159–160 stopping 153 top property 155 width property 155 writing custom animations 154 annoying tricks, avoiding 56 anonymous event handler 97 functions 117, 178 listeners 97 Apache 242 API collisions 207 API. See jQuery API append() method 78 appending content 79
INDEX
appendTo() method 83, 86 appetizer menu 136 Apple applications 125 application layout 284 Application Programming Interface. See jQuery API application/xml 240 application/x-www-formurlencoded 262–263 array indexing 38 fetching elements by index 38 arrays array-like object 186 filtering 183–184 merging 187 testing for 193 translating 184 assigning properties 49 asterisk character 26 in selectors 26 asynchronous interfaces 93 requests 101 Asynchronous JavaScript and XML. See Ajax attachEvent() method 172 attr() method 58, 60–61 disabling form submission 63 usage example 133 attribute selectors 24 ways to use 25 attributes applying 65 correspondence to properties 57 custom 59 definition 56 diagrammed 57 fetching values 58, 60 Internet Explorer limitations 61 jQuery normalized names 59 manipulation examples 62 names 59 removing 62 setting multiple 61 setting values 60 specifying on creation 33 augmented visibility methods 296 augmenting wrapped sets 43 autocomplete widgets 287 creating 370 events 375 sources 372
autocomplete() method syntax 370 autocompletechange event 375 autocompleteclose event 375 autocompletefocus event 375 autocompleteopen event 376 autocompleters 369 events 375 options 371 source data 372 styling 376 Autocompleters Lab 373 source options 375 autocompletesearch event 376 autocompleteselect event 376 auto-progressbar plugin, testing 367 auto-progressbar widget 363 creating 364 auto-progressbar, test page 368 autoProgressbar() method 363 options 364 auto-scrolling sensitivity 312 speed 312
B background patterns 55 background sounds 55 backgroundColor property 296 bar widget 282 Basic Event Model 102 event propagation 103 See also DOM Level 0 Event Model before() method 80 beforeSend option 265 behaviors 119 cascading dropdowns 256 progression 120 separating from structure 6 best practices 16, 205 bilateral operations 58 bind() method 107, 110, 265, 313 establishing handlers on sortables 327 event handlers 266 black box 241 blind effect 293 blinking text 55 blur() method 110, 119 Boot Closet, exercises 277 borderBottomColor property 296
435 borderLeftColor property 296 borderRightColor property 296 borderTopColor property 296 bounce effect 293 branching 173 browser capability flags 173 browser detection 171–172, 175–176 alternatives 172, 175 custom support flag 176 jQuery flags 175, 177 when required 176 why to avoid 172 Browser Event Model. See DOM Level 0 Event Model browsers 8 bugs 171 caching decisions 250 differences in event models 94 effects and animations within 138 event models 93, 95 exposing events 94 family 175 identification 172 layout manager 149 modern 23 nonstandard mouse events 123 proliferation 171 standards-compliant 23, 98, 101, 103, 105, 107–108, 175 XHR implementation 237 bubble handlers 104–105 establishing 105 tracking event propagation 104 bubble phase 104 event path 105 Internet Explorer 106 bubble process 100 bubbling 98 hierarchy 265 stopping 100 button element 347 semantics 347 theming 350 types 348 Button widgets, icons 287 button() method 348 applying 349 options 350 syntax 349
436 buttons 347 events 352 icons 352 options 351 styling 353 buttonset() method 348 applying 349 syntax 349 buttonsets 347 options 351
C caching, in browsers 250 calendar controls See date pickers callback functions 374, 424 function context 58 Camino 95, 171, 423 $.support flags 174 browser flags 173 cancelBubble property 101 canned theme 286, 289 custom theme 290 capabilities detection 172 user agent 171 caption bar 140 capture handlers 104–105 establishing 105 tracking event propagation 104 usage 106 capture phase 104 event path 105 Internet Explorer 106 jQuery Event Model 107 caret character 25 in selectors 25 cascading dropdowns 255, 258 implementing 259 Cascading Style Sheets 4, 6, 8 basic selectors 22 CSS class names 22 filter selectors 29 psuedo-class 29 rules 6 selectors 23 See also CSS CGI, server side 247 chainability 10 chaining 52, 367 stack 53 chains 9 managing 52–53
INDEX
change events 134 usage example 258 change handler, establishing 133 change() method 110, 119 character patterns 385 character sets 263 checkboxes 244, 354 :checked 29 child selectors 23–24 children() method 50 Chrome 23, 171 $.support flags 174 browser flags 173 debugging with 251 class manipulation method. See switchClass() method class names adding, removing 66, 70 fetching 69 multiple 66 testing for 69 toggling 67 class transition methods animating 297 extensions 297 clearQueue() method 166 click 102, 107 click event handler 97 click events 99, 101, 120 establishing multiple event handlers 103 propagation 104 click() method 110, 119 client-side code 8 client-side libraries 11 client-side programming 212 clip effect 293 clone() method 52, 87 for templating 127 clones 87 cloning 131 cloning operation 88 closest() method 49 usage example 132 closures 64, 95, 100, 228, 233, 428, 431 Observable pattern 102 coding styles 15 cognitive ability 144 collapsible module example animated version 147 implementation 143 implementing 140 collections, iterating through 181
colon character 27 in selectors 27 color property 296 combo box 347 comma operator, in selectors 23 commerce web sites 245 complete 266 computed style 71 connected lists 329 content management system 62 content type header 240 contents() method 50 context argument to $() 20 context menus 73 context, multiple 21 controls 282 convenience methods 72 copy-and-move operation 79 copying elements 87 core animation engine 291, 296 extended 296 core interactions 306 core jQuery 282 core library 14 correspondence between attributes and properties 57 creating DOM elements 13 creating utility functions 211 cross-browser Ajax 237 problems 3 solution 173 CSS 282 !important qualifier 321 absolute positioning during animation 158 class names 66, 69 computed style 71 convenience methods 72 display property 149 hiding and showing elements 139 inline vs block 139 opacity 151, 155 position style 157 precedence rules 321 relative positioning 157 selectors 8 specifying at creation 34 style properties 155 styles 72 styling 141 styling plugin elements 272 See also Cascading Style Sheets
INDEX
CSS classes, naming 286 CSS display property 139 CSS file 284 CSS filter selectors 30 css folder 284 CSS positioning, advanced 300 CSS properties 296–297 CSS selectors 8, 22–23, 27, 29 CSS specification 27 css() method 70–71, 153, 217 usage example 147 CSS3 9, 22 style rules 288 Cupertino theme 284 cursor CSS name 310 relative position 310 custom animations 154, 159 drop animation 157 effects 158 puff animation 158 scale animation 156 custom attributes 59 data- prefixed name 59 in HTML 59 custom code 204 custom controls 347 custom data 64 Custom Effects Example 159 custom event 132 custom function $.formatDate() 213 $.toFixedWidth() 211 date formatter 212 custom handlers 133 custom method photomatic() 224 setReadOnly() 219 custom properties 64 custom selectors 29, 32 custom wrapper methods 216
D dashboard example 140 data conversion 185 data translation 184 data() method 64–65, 136, 366 usage example 228 Date 212 date formats 377 character patterns 385 pattern constants 386
date formatter 212, 214 pattern 213 tokens 213 date formatting 212–213, 216 date pickers 377 date strings 388 datepicker() method 377 datepickers callback options 387 creating 377 date options 385 defaults 387 events 387 options 381 utility functions 387 Datepickers Lab 380 dblclick() method 110, 119 debugging tool, JavaScript 251 default action blocking 107 default actions. See semantic actions defining functions 210 delay() method 166 delaying queues 166 Dell 3 dependencies 283 dependent dropdowns 255 Dequeue button 165 dequeue() method 163 usage example 167 dequeuing 163 functions 163 usage example 164 desktop applications 354 drag and drop 306 interaction styles 306 sorting 322 detach() method 86 development-bundle folder 284 DHTML 56 dialog boxes creating 405 events 410 opening 407 options 408 tricks 412 dialog() method 412 syntax 406 dialogbeforeClose event 410 dialogclose event 410 dialogfocus event 411 dialogopen event 411 Dialogs Lab 407 dialogs See dialog boxes die() method 117
437 dimensions, getting and setting 72 direct manipulation 305 disable() function 14 disabled attribute 63 disabling animations 170 disabling elements, gotchas 63 disabling form elements 14 display property 145 display state manipulation 144 toggling 143 div element 354 dialog boxes 412 document instance 12 Document Object Model 6, 12, 18 creating new elements 13 generating elements 32 sample fragment 20 sub-trees 21 See also DOM document ready handler 11 document structure 12 dollar sign character 26 in selectors 26 DOM 56, 65 API methods 77 appending content 79 cloning elements 87 copying elements 78, 87 event bubbling 98–99, 258 event propagation 103 form elements 89 hierarchy 99 in Ajax 240 inspecting with Firebug 251 manipulation 77 comprehensive example 268 moving elements 78 removing elements 86–87 replacing elements 88 setting content 77 unwrapping elements 84 wrapping elements 84 See also Document Object Model DOM elements 9, 11, 15, 21, 29, 35 attributes 56 collecting into a wrapper 9 creation 18 example 34 event handlers 96
438 DOM elements (continued) JavaScript object instances 64 listeners 96 removing attributes 62 selecting 20 selection 18 selectors 18 storing JavaScript values 64 style property 70 wrapper methods 216 DOM Level 0 Event Model 95, 97, 101–102 browser-independent 106 event handlers 95 shortcomings 101 DOM Level 1 Event Model 95 DOM Level 2 Event Model 95, 101, 172 converting to jQuery Event Model 107 establishing event handlers 102, 105 event handlers 102 event propagation 103 Internet Explorer 106 listeners 102 multiple event handlers 109 standard event model 102 DOM manipulations 56 functions 13 jQuery 56 Move and Copy Lab Page 81 unwrapping 84 wrapping 84 DOM Sample 21 DOM scripting 56 DOM tree 12, 22, 33, 149 event progression 105 event propagation 98, 100 jQuery 105 DOM-scripted applications 3, 18, 235–236 Double-Submit Problem 63 Download Theme button 290 downloads, example code for book 5 drag and drop 282, 306 in desktop applications 306 in web applications 306 drag event 312, 411 current state 313 drag operation acceptable element 317 auto-scrolling 312 constraining area 310
INDEX
constraining axis 310 delaying 310 disallowing 310 distance 311 drag event 313 flexibility 308, 312 handle 311 iframes 311 pixels to initiate 311 reverting 311 stages 312 start event 313 starting 311 stop event 313 ui-draggable-dragging 308 z-index 312 drag-and-drop operation 307 current state 319 transitions 318 draggability 307 controlling 313 disabling 307–308, 313 disabling permanently 314 events 312 options 308 re-enabling 308, 314 removing 308 draggable elements current draggable element 319 disabling draggability 308 drag helper 311 draggability 307 identifying 308 re-enabling draggability 308 draggable, how to make 308 draggable() method 307 options 308–309 options object 313 retrieving individual options 314 setting individual options 314 syntax 307 draggableDestroy() method 307 draggableDisable() method 307 draggables 307 associating with droppables 311 event handler function 311 flexibility 312 registering event handlers 312 scope 311 stacking 312 UI events 313 z-index 312
Draggables Lab page 308 control panel 309 draggable event handlers 313 dragged element 313 dragged elements opacity 311 position 320 properties 313 revert duration 311 reverting position 311 snapping 312 target elements 312 dragging accidental 311 definition 306 flexibility 312 how to 306 usefulness 314 dragstart event 312, 411 event handler 312 registering a handler 313 dragstop event 312, 411 event handler 312 drop effect 156, 158, 293 drop event, when triggered 319 dropactivate event, when triggered 318–319 dropdeactivate event, when triggered 319 dropdowns 244 cascading 255–256 instrumentation example 247 dropout event, when triggered 319 dropover event, when triggered 318–319 droppability disabling 315 enabling 315 events 318 events propogation 317 performance 317 removing 315 droppable disabling 320 elements droppability 315 recomputing positions 311 ui-droppable class 317 droppable() method making droppable 315 options 317 syntax 315 droppables 314 activating classes 317 active state 318–319
INDEX
droppables(continued) associating draggables 317 defining hovering 318 enabling 320 event handlers drop events 317 dropactivate events 317 dropover events 317 events 316, 319 handlers 318 hover class 317 hover state 318 identifying 317 inactive state 318–319 states 318 transitions 318 Droppables Lab Page Control Panel 320 control panel 316 exercises 320 droppablesevent handlers dropdeactivate events 317 dropout events 317 dropping, definition 306 DVD cataloging example 124 dyanmic element creation, example 34 dynamic components 73 dynamic data, loading 245 dynamic dimensions, example 73 dynamic elements 73 dynamic functionality 4 Dynamic HTML. See DHTML
E each() method 49, 100, 156, 182, 228, 366, 430 usage example 15 easing functions 155 linear 155 swing 155 easings 155, 292, 299 list of available 299 e-commerce 245 effect() method 291, 297 effects 138, 282, 291 augmented visibility 297 comprehensive example 268 custom 154, 158 custom drop 156 custom fading 155 custom puff 157 custom scale 156
description 292 dynamic 139 fade in 144 fade out 144 fading 149 hide 144 hide() method 139 overuse 139 purpose 139 queue 162, 166 queuing 159 show 144 show() method 139 slide down 144 slide up 144 sliding 152 speed 149 Effects Lab Page 147–150 element attributes, specifying on creation 33 element creation, example 34 element selection 14 elements 4 abbr 274 active elements 73 animated 153 animating 144, 154 applying styles 70 as data scopes 64 attributes 56, 62, 65 behavioral elements 7 cloning 87 content 77–78 copying 78, 87 creating a union 41 creating elements 126 creation by template 126 custom data 64 display state toggling 143 draggability 307 dynamic 116 emptying 86 enabled state example 119 fading 139, 149 finding index of an element 40 form elements 89 getting and setting properties 57 hiding 139 how to make draggable 308 making droppable 315 making selectable 336 making sortable 323 manipulating properties 58
439 modifying contents 77 moving 78 opacity 149 position 75 properties 56–57, 65 references 58 removing 86–87 replacing 88 resizability 331 scroll position 76 selecting 19 selecting by order 27 setting content 77 setting multiple attributes 61 showing 139 sliding 152 sorting 305 span 274 state tracking 287 structural elements 7 styling 65, 76 stylistic rendition 70 subscribing 132 text contents 77 toggling 143 tooltips 268 unwrapping 84 visible 76 width and height 72 wrapping 84 wrapping contents 85 em units 155 empty, testing for 193 empty() method 86 encodeURIComponent() function 190, 239, 244, 273 end() method 53 usage example 219 enhanced effects 282 Epiphany 173 eq() method 39 error 266 error() method 110, 119 event bubbling 99, 117, 258 avoiding repetitive code 258 event handlers 94 anonymous function 97 as attributes 97 attach method 102 automatic generation from markup 97 binding 107, 119 browser-specific detection 101 choices for binding 111
440 event handlers(continued) click event handler 108 convenience methods 115 DOM Level 0 Event Model 95, 97 establishing 102, 106 establishing mouse event handlers 123 establishing multiple 103 Event instance 107 example 108 fine-grained control 115 grouping 108 listeners 94 live 116 managing 115 multiple 106 multiple handlers 102 namespace 108 onclick 97 order 103 progression 120 removing 111 script control 96 specifying at creation 34 styles of declarations 96 testing 103 toggling 119, 121 triggering 117, 119 unbinding 119 event handling 106 hovering 121, 123 proactive 115 removing live event handlers 117 standardizing 95 event indicator 320 Event instance 98, 100 adding event listener 102 cancelBubble property 101 inspecting 112 Internet Explorer 98 Internet Explorer Event Model 106 jQuery.Event 113 normalizing 107, 112 preventing event propagation 101 properties 98 stopPropagation() method 101 target 118 event models 93, 95 Basic 95, 98 bubbling example 258
INDEX
DOM Level 0 Event Model 95, 98 DOM Level 2 103 DOM Level 2 Event Model 95, 101 Internet Explorer 106 jQuery 106, 136 Netscape 95, 98 standard event model 102 event parameter 97 event propagation affecting 100 diagrammed 104 element hierarchy 104 preventing 101, 115, 118 tracking 104 event target 100 event.srcElement 98 event.target 98 event-driven interfaces 93 event-handling browser-specific 108 model 95 models 172 event-related, methods 119 events 136 addEventListener() method 102 Ajax 265 Ajax events 265 API abstraction 106 attachEvent() method 106 behaviors 94 binding 107 bubble phase 104 bubbling 98 cancelling propagation 100 capture phase 104 comprehensive example 268 custom 132 establishing multiple 102–103 event canceling 107 Event instance 98 event names 108 exposing 94 jQuery convenience methods 119 key codes 114 modifier keys 114 name-spaced 112 propagation 99–100, 103 publishing 132 srcElement property 98 target element 98 triggering 117, 119
example code download location 5 online URL 242 expandos. See custom properties explode effect 293 extended controls 73 extending jQuery 15, 204 custom plugins 204 defining wrapper methods 216, 233 implementation functions 229, 231 in $ namespace 210–211 motivations 205 naming files 206 The Termifier 277 utility functions 210–211 extending objects 187 Extensible Hypertext Markup Language 4 external resources 12
F fade effects 170, 293 fade in effect 144 usage example 270 fade out effect 144 fadeIn() method 150 fadeOut() method 150 fadeTo() method 151 opacity 151 fading 149 feature detection 98, 172, 176 alternative to browser detection 173 feasibility 176 for Ajax 237 preferred over browser detection 175 filter selectors 32 :not 44 element expressions 32 filter() method 46 usage example 45, 219 filtering data 183–184 filtering wrapped sets 45 filters 369 adding 126 basic filters 27 child filters 27 inverse of 31 multiple 134 positional 27 removing unwanted 134 See also pseudo-classes
441
INDEX
find() method 51 Firebug 133, 251, 417 download URL 251 inspecting Ajax requests 251 Firebug Lite 251 Firefox 95, 171, 176, 417, 423 $.support flags 174 inspecting Ajax requests 250 reload vs. refresh 149 first() method 39 first-class objects 215 fixed-width output 211–212 flags 170 $ 170 detecting user agent support 171 using 170 Flash 12 flexibility 305, 374 drag operation 308 flexibility of code via loose coupling 133 flyouts 268 focus() method 110, 119 focusin event 110–111 focusout event 110–111 fold effect 294 font tag, deprecated 6 form data 244 submission 244 form elements 89 convenience functions 89 definition 89 setting value 91 unsuccessful state 89 Form Plugin 89, 91 form validation 101 form.submit() 101 formatting fixed-width output 211 forms controls 244 data validation 135, 180 query string 189 read-only fields 220 serializing 244 serializing form elements 189 submit event 101 submitting form elements 189 URL 189 frames, animation 155 Function apply() method 426 as first-class object 421
call() method 426 function keyword operation 422 naming 422–423 function context 95, 425–426 See also this function detection for Ajax 237 function literals 7 function queuing 162 Function.prototype property 188 functional language 229 functional programming 429 functions as callbacks 424 as methods 423, 428 assigning context 426 context 425 function literal 423 queuing 159 testing for 193 top-level 422 fx 162 fx queue 167
G Gallery tab 290 garbage collection 86 Garrett, Jesse James 236 Gecko 176, 423 $.support flags 174 generated event handlers 97 GET 239 body content 239 semantic intentions 250 via jQuery 252 get() method 38 negative index 38 returning an array 38 GIF 138 GIF animations 361 GIF files 277 global events 265 global flags 170 global identifier 16 global namespace 16, 229 avoid polluting 169 polluting 215 global values, scope issues 64 global variables 64–65, 130, 136 Google Chrome 171, 173, 176 Graphical User Interface drag and drop 306 See also GUI
grep 183 grip handle 336 groupings of parametric data 130 GUI 93 .NET framework 93 event dispatching 94 Java Swing 93 management systems 93 X11 93
H halting form submission 101 handles 359 single-handle case 354 handling phases 105 :has() filter 32 usage example 32 has() method 48 hasClass() method 69 is() method,comparison 69 hash as parameter 208, 210 header, Last-Modified 263 height, setting 72 height() method 72 Help tab 290 helper element 319 hide effect 144 hide() method 139, 144–145 extended by jQuery UI 296 usage example 142 highlight effect 294 horizontal slider 354 hover styles 348 hover() method 123 hovering 121 HTML as Ajax result 253 behavioral aspects 246 semantic actions 94 specification 244 HTML 4 274 controls 352 custom attributes 59 HTML 5 custom attributes 59 Draft Specification 274 W3C specification 59 HTML markup custom attributes 59 DOM elements 56–57 event handler function 96 event handlers 97
442 HTML page behavior 6 body tag 7 creating elements 13 CSS selectors 8 dynamic elements 32 head section 7 onload handler 7 readability 6 structure 6 style 6 Unobtrusive JavaScript 7 HTML Page, maintainability 6 HTML, generation 32 html() method 77 usage example 253 HTTP protocol 250 request parameters 89 requests 247 See also Hypertext Transfer Protocol HTTP method GET 238–239 POST 238–239 HTTP status code 200 238 404 238 Hypertext Transfer Protocol 254 methods 239, 244 effects on caching 250 status codes 240 See also HTTP
I IBM 3 iCab 173 icon sheet 287 icons 287 idempotent requests 250 IE 6 106, 171, 237 PNG file non-support 277 IE 7 106, 171, 237 IE 8 106, 171 IE, $.support flags 174 iframe dialog 412 styling 413 iframes for Ajax 236 masking 311 iGoogle 140 image loading 12 image resizing example 120
INDEX
images folder 284 img element dynamically creating 33 selecting 45 selecting with except type relationship 45 wrapped set 43 index.html file 284 index() method 40 info.panel property 397 inheritance 188 inline functions 7 inner HTML 77–78 innerHeight() method 75 innerHTML property 10 innerWidth() method 75 input controls 56 input element 347, 370 insertAfter() method 83, 86 insertBefore() method 83, 86 inserting dynamic HTML 84 installing jQuery 4 interactions 282 interactive applications 101, 119 multi-events 121 interfaces asynchronous 93 event-driven 93 Internet Explorer 23, 171, 176 Ajax 237 Ajax wrapper 237 alpha filters vs. opacity 70 attribute setting limitations 61 cancelBubble property 101 DOM Level 2 Event Model 95 event handling limitations 106 Event instance, proprietary 98 Event Model 106 jQuery Event Model 108 lack of DOM Level 2 Event Model 106 non-compliance with standards 175 srcElement property 98 unified events API 109 Internet Explorer 8 rounded corners 288 Internet Explorer Event Model 106, 172 attachEvent() method 106 inverting selectors 31–32 iPhone 94
is() method 52 hasClass() method, comparison 69 usage example 142 isNaN() method 185 ISO 8601 389 iterating properties and collections 181, 183 the wrapped set 49
J Java 242 server side 247 Java Server Pages. See JSP JavaScript 3–4 . operator 418 adding select options 176 animation engine 139 arrays 37, 186 attribute value 60 closure variables 429 closures 64, 95, 228, 428, 431 creating objects 416 custom properties 64 Date 212 dot operator 418 dynamic and interpretive 208 dynamic creation of properties 417 dynamic nature 56 dynamically loading scripts 199, 202 effective use 5 encodeURIComponent() function 190, 239, 244, 273 essential concepts 415 expressions 7 extending objects 187 flexibility 95 flexible nature 208 for loop 181 for-in loop 181 Function 95 function contexts 95, 217 function keyword 422 functional language 229 functions 11, 215, 421 general reference operator 419 getAttribute() method 59 global names 13 isNaN() method 185
INDEX
JavaScript (continued) libraries 3, 16, 206 modulo operator 230 NaN 185 navigator object 172 new operator 416 NodeList 186 nonstandard property names 418 Number 185 Object 95, 416, 421 object hash 208 Object instance 208 See also objects Object literals 419–420 object properties 416, 419 object property diagram 418 object-oriented 187, 217, 229 objects 56, 64 operations on wrapped elements 37 properties 58 property name 57 property references 418 prototype property 188 regular expressions 184, 215 separation of behavior 7 setAttribute() method 59 statements 7 String type 180, 186 String.match() method 184 String.split() method 186 testing objects for existence 15 top-level scope 421 Unobtrusive JavaScript 6, 8, 97 using libraries with jQuery 177, 180 var keyword explained 421 window properties 420 XML and 241 JavaScript array, from wrapped set 40 JavaScript Object Notation as Ajax response 240 jQuery 3, 8 $() 9 accessing elements 58 adding wrapper methods 216 Ajax events 265 animation queue 161 architecture 206 attribute manipulation 58 attributes handling 58
basic CSS selectors 26 bilateral methods 58 bilateral operations 58 bind() method 110 binding event handlers 107 browser detection flags 175, 177 browser disparities 106 browser-independent Event instance 113 browser-independent events 117 browsers 23 cascading dropdowns 255 chain stack 53 chainability 10 of methods 33 chaining 9, 36, 41–42, 108, 205, 217 chains 52 checkboxes 90 coding styles 15 common tasks 4 community 206 compound statements 34 core effects 144 core library 14 Core Team 89 creating dynamic elements 32 cross-browser support 8, 12 CSS convenience methods 72 CSS filter selectors 30 CSS implementation 22 CSS3 22 custom data 64 custom events 132 custom filter selectors 29–30 custom selectors 32 dimension manipulation 72 dimension methods 75 document ready handler 11 DOM manipulation functions 13 download website 4 dynamic manipulation 115 dynamically creating elements 14 effects 139 effects queue 161 element placement 80 emulating nonstandard mouse events 123 essential JavaScript concepts 415 establishing handlers 123
443 event convenience methods 119 event implementation 106 Event instance 112 Event Model 106, 108 event techniques 124 event trigger convenience methods 118 examples of extending 14 extending 14, 16, 204, 233 extending with utility functions 210 extensions 15 feature flags 176 filtering large data sets example 124 filters 32 flags 170 form element convenience functions 89 fundamentals 8 fx queue 166 GET requests 254 global names 179 grouping event handlers 108 higher-level functions 119 installing 4 JavaScript concepts 94 jQuery 1.3 175 jQuery object 177–178 less JavaScript 94 live() method 115 load() Ajax method 135 loading content 243 manipulating collections 180 manipulating JavaScript objects 180 method chain examples 124 method chains 41, 128, 231 methods 35, 206 multiple selectors 23 namespace 16 native JavaScript notation 58 Nokia 4 opacity property handling 70 opening links in external windows 62 operations 37 Operations Lab 35–36, 42–44 patterns 205 performance 52 positional filter selectors 27 positions 75 POST requests 255 queues 162
444 jQuery (continued) radio buttons 90 radio group example 5 readability 34 removing element data 65 scripting-enabled behavior 94 scroll position 76 scrolling 75 selecting by position 27 selecting elements 22 selecting elements to be wrapped 18 selector 21 selector engine 23 selector mechanism 205 selector string 20 selectors 5, 19, 27, 32, 41, 344 Selectors Lab Page 19–20 shortcut event methods 110 toggle() method 120 translating data 184 trimming strings 180 UI Draggables Lab Page 308 Unobtrusive JavaScript 7, 97 user agent classification 175 using with other libraries 16, 177, 180 utility functions 11, 169, 177, 180 versatile code 7–8 Visual Studio tool 4 why extend 205 why use 3 wrapped set 9, 206 wrapper function 14 wrapper methods 19, 37, 218 wrappers 8–9, 11, 207 jQuery 1.2 32 jQuery 1.3 32 jQuery API $.ajax() 261 $.ajaxSetup 264 $.browser.mozilla 175 $.browser.msie 175 $.browser.opera 175 $.browser.safari 175 $.browser.version 175 $.contains() 194 $.data() 195 $.each() 182 $.extend() 188 $.fx.off 170 $.get() 252–253 $.getJSON() 254 $.getScript() 200
INDEX
$.globalEval() 199 $.grep() 183 $.inArray() 186 $.isArray() 193 $.isEmptyObject() 193 $.isFunction() 193 $.isPlainObject() 193 $.isXMLDoc() 193 $.makeArray() 186 $.map() 184 $.merge() 187 $.noConflict(jQueryToo) 177 $.noop() 194 $.param() 190 $.parseJSON() 198 $.post() 255 $.proxy() 196 $.removeData() 195 $.support. noCloneEvent 173 $.support.boxModel 173 $.support.cssFloat 173 $.support.hrefNormalized 173 $.support.htmlSerialize 173 $.support.leadingWhitespace 173 $.support.objectAll 173 $.support.opacity 173 $.support.scriptEval 173 $.support.style 173 $.support.tbody 173 $.trim() 181 $.unique() 187 $() 9 add() 42 addClass() 66 after() 80 ajaxComplete() 266 ajaxError() 266 ajaxSend() 266 ajaxStart() 266 ajaxStop() 266 ajaxSuccess() 266 andSelf() 53 animate() 154 append() 79 appendTo() 83 attr() 58, 60–61 before() 80 bind() 107 blur() 110, 119 change() 110, 119 children() 50 clearQueue() 166 click() 110, 119
clone() 87 contents() 50 css() 70–71 data() 64–65 dblclick() 110, 119 delay() 166 dequeue() 163 detach() 86 die() 117 draggable() 307 draggable() method 307 droppable() 315 each() method 49 empty() 86 end() 53 eq() 39 error() 110, 119 fadeIn() 150 fadeOut() 150 fadeTo() 151 filter() 46 find() 51 first() 39 focus() 110, 119 focusin() 110 focusout() 110 get() 38 has() 48 hasClass() 69 height() 72 height(value) 72 hide() 145 hover() 123 html() 77 index() 40 innerHeight() 75 innerWidth() 75 insertAfter () 83 insertBefore () 83 is() 52 jQuery() function 9 keydown() 110, 119 keypress() 110, 119 keyup() 110, 119 last() 39 live() 115 load() 110, 243 map() 48 mousedown() 110 mouseenter() 110 mouseleave() 110 mousemove() 110 mouseout() 110 mouseup() 110 next() 50
INDEX
jQuery API (continued) nextAll() 50 nextUntil() 50 not() 45 offset() 76 offsetParent() 50 one() 111 outerHeight() 75 outerWidth() 75 parent() 50 parents() 50 parentsUntil() 50 position() 76 prepend() 79 prependTo() 83 prev() 50 prevAll() 50 prevUntil() 50 queue() 162 ready() 110 remove() 86 removeAttr() 62 removeClass() 67 removeData() 65 replaceAll () 89 replaceWith() 88 resizable() 331 resize() 110 scroll() 110 scrollLeft() 76 scrollTop() 76 select() 110, 119 selectable() 340 serialize() 244 serializeArray() 245 show() 145 siblings() 50 size() 37 slice() 47 slideDown() 152 slideToggle() 153 slideUp() 152 sortable() 322 stop() 153 submit() 110, 119 text() 78 toggle() 119, 146 toggleClass() 67–68 trigger() 117 triggerHandler() 118 unbind() 112 unload() 110 unwrap() 85 val() 90–91 width() 72
wrap() 84 wrapAll() 85 wrapInner() 85 jQuery chaining, in plugins 271 jQuery documentation 27 jQuery Event Model 106 browser differences 112 capture phase 107 DOM Level 2 Event Model 107 establishing event handlers 107, 112 features 106 Internet Explorer 107, 109 multiple event handlers 109 unified events API 109 jQuery extensions 204 code consistency 205 jQuery methods 206 leveraging existing codebase 205 Photomatic plugin 223 reusability 205 utility functions 206 why extend 205 jQuery Form Plugin 207 jQuery plugins avoiding name collisions 206 complex methods 218 filenames 207 guidelines 205 implementation functions 229 maintaining state 233 naming 206 parameters 208 patterns 205 scope 233 jQuery selectors, examples 10 jQuery UI 281, 347 $.datepicker. iso8601week () method 389 $.datepicker.formatDate() method 388 $.datepicker.parseDate() method 388 $.datepicker.setDefaults() method 387 accordion() method 399 addClass() method 297 autocomplete() method 370 button() method 349 buttons 351 changing element sizes 330 configuring 282
445 convention 307 core interactions 306 datepicker() method 378 dialog() method 406 download page 283 downloading 282 draggable() method 307 draggables 307 drop zones 320 droppables 314 Droppables Lab Page 315 effect() method 291 effects 291 events for draggables 313 hide() method 296 higher-order interaction 330 method overloading 307 mouse interactions 306 position() method 301 progressbar() method 361 removeClass() method 297 Resizables Lab 331 selectables 337 Selectables Lab Page 338 selection state 336 show() method 296 slider() method 355 sliders 357 Sortables Lab Page 324 sorting 322 switchClass() method 298 tabs() method 391 team 282 toggle() method 296 toggleClass() method 297 using 284 version1.8 283 jQuery UI Button Icons page 353 jQuery UI Buttons Lab 351 jQuery UI Easings Lab 300 jQuery UI Effects Lab 297 jQuery UI Effects Lab Page 292 jQuery UI Positioning Lab 302 jQuery UI Sliders Lab 356 jQuery wrapper 9 as array 9 methods 9 jquery, as file prefix 206 jQuery.Event 118, 265 data property 118 halting event propagation 118 stopPropagation() method 118
446 jQuery.Event object 113 methods 114 properties 113 jQuery.fx.off flag 153 jQuery() function 9, 12–13 js folder 284 JSON 420 array example 420 as Ajax result 254 JavaScript Dates and 420 object example 419 See also JavaScript Object Notation json type 262 jsonp type 262 JSP 242, 248 engine 242
K Kepler 161 Kepler's Dilemma 160 keyboard events 98 keydown events 102, 114 keydown() method 110, 119 keypress events 114 keypress() method 110, 119 keyup() method 110, 119 Konqueror 173
INDEX
left property 161 length property, applied to $() 37 leveraging jQuery 205 libraries, using with jQuery 16 linear easing 299 listeners 94, 102 binding 112 establishing 104 removing 112 toggling 119 live events 116 live selector 116 live() method 115 dynamic elements 116 establishing event handlers 116 limitations 116 similarity with bind() method 116 usage example 132 LiveScript 138 load() method 110, 243, 404, 412 forcing a GET 256 usage example 248, 256, 273 loading content 241, 243 loading dynamic data 245 local events 265 loose coupling 133
L M Lab Pages $.param() 192 Accordions 401 Autocompleters 372 Buttons 350 Datepickers 379 Dialogs 408 Draggables 308 Droppables 315 Effects 147 Move and Copy 81 Operations 35 Resizables 331 Rounded Corners 288 Selectables 338 Selectors 20 Sliders 356 Sortables 324 Tabs 392 UI Easings 299 UI Effects 291 UI Positioning 301 last() method 39 Last-Modified header 263
Mac OS X, resizable windows 336 Manning Ajax in Action 236 Ajax in Practice 236 map() method 48 markup, well-formed 33 marquees 55 matching algorithm 374 memory leaks 64 memory management 65 merging options, usage example 227 method 428 as read operation 58 as write operation 58 method attribute 25 method chain 9, 139 managing 52–53 methods, jQuery. See jQuery API Microsoft Ajax 235 XMLHTTP 236
MIME type 240 mission-critical applications 3 modal dialog boxes 405 modeless dialog boxes 405 module class 142 module, roll up state 140 modules 140 modulo operator 230 mouse core interactions 306 event instance 313, 319 pointer cursor 310 mouse events 98 limitations 121 nonstandard 123 triggering 122 mouse interactions 282 mousedown() event 110 mouseenter() event 110, 123 mouseleave() event 110, 123 mousemove() method 110 mouseout() event 68, 110, 121 mouseover event 68, 99, 102, 107, 121 mouseup() event 110 Move and Copy Lab Page 81 clone operation 88 move and copy operations 82 Mozilla Firefox 23 -moz-opacity 70 multi-binding events 110 multiple class names 66 multiple simultaneous animations 160
N name collisions 17, 207 name-spaced events 112 namespaces 108 $ namespace 170 cluttering 207 global 169, 215 grouping events 110 hierarchy 65 multiple for events 109 object 212 prefix 11 unbinding events 112 namespacing 212 naming avoiding collisions 207 collisions 207 NaN 185 navigator object 172
INDEX
Netflix 3 Netscape Communications Corporation 95 Netscape Event Model. See DOM Level 0 Event Model Netscape Navigator 138 event-handling model 95 next() method 50 nextAll() method 50 nextUntil() method 50 NodeList 186 Nokia 4 non-alphabetic character events 114 non-idempotent requests 250 normalizing event targets 98 :not() filter 31–32 not() method 44–46 removing elements 45 Number.NaN 185 numeric input 354
O Object literals 419–420 properties 416, 419 object hash 208, 210 object orientation 188 object-oriented JavaScript 187 objects extending 187 testing for 193 testing for existence 15 Observable pattern 102 Observer pattern 132 offset() method 76 offsetParent() method 50 OmniWeb 171 $.support flags 174 browser flags 173 onclick event 106 onclick handler 100 onclick property 95, 101 one() method 111 removing an event handler 111 onkeydown event 106 online retailers 245 onload handler 7 external resources 12 onload handler, alternative to 12 onload mechanism 12 onmouseover event 106 onmouseover property 95–96
onreadystatechange 239–240 opacity 296 adjustments by effects 150 during custom drop animation 156 reducing during animation 159 opacity effect 157 opacity property handling 70 opacity property, animating 155 Opera 95, 171 $.support flags 174 browser flags 173 Operations Lab Page, comparison with Selectors Lab 36 operator 419 options hash 208, 210 extensive example 224 options object 209 ordinal index of wrapped elements 40 outerHeight() method 75 outerWidth() method 75 outlineColor property 296 Outlook Web Access 235 overflow, usage example 271 OWA, Outlook Web Access 235
P page 161 pain points, Ajax 241 parameters 144, 208, 210 optional 208 parent() method 50 parents() method 50 parsing ZIP codes 184 patterns behavior 6 necessity in Scripted Applications 8 Observable 102 Observer pattern 132 options hash 210 Publish/Subscribe pattern 132 repetitiveness 204 Separation of Concerns 8 structure and 6 Photomatic plugin 223, 233 closures 228 HTML markup 226 implementation 232 syntax 224 test page 223, 225
447 PHP 192, 242, 248 server side 247 plain text response 240 plugin example, The Termifier 269 plugin, termifier() 270 plugins 8, 15 creating 204, 233 PNG files 277 PNG image, slider 360 position, during animation 157 position() method 76 extended by jQuery UI 301 options 302 overloaded 301 positional filters 27 selectors 27 positional selectors 27, 29 positions 75 POST 239 body content 239 semantic intentions 250 prefetching data 247 prepend() method 79 prependTo() method 83, 86 prev() method 50 prevAll() method 50 prevUntil() method 50 progress bar plugin 363 progress bar widget 282, 361 progress bars 360 events 363 styling 369 updating 362 when not to use 361 progressbar() method 361 options 362 progressbarchange event 363 propagation of events 103 properties definition 56 diagrammed 57 iterating through 181 of JavaScript objects 416, 419 property referencing 418 Prototype conflicts with $ 210 using with jQuery 16, 177, 180 prototype 217 Prototype JavaScript library 16–17 prototype property 188 pseudo-classes 29 See also filters
448 pseudo-classes in CSS 27 Publish/Subscribe Pattern 102, 132 puff animation 157 puff effect 157–159, 294 pulsate effect 294 pulseData option 366 pulseUrl option 366
Q qualifier controls, removing 134 query string 191, 239 queue option 155 queue() method 162 usage example 167 queues 162 dequeuing 163 distinct 162 executing 163 named 163 queuing 159 clearing 165 delay 166 functions 163, 166–167 insertions 166 QuickTime 12
R radio buttons 244, 354 radio groups example 4 range element 360 readability of pages 55 read-only status, applying 219 ready handler 142, 144 binding event handlers 108 declaring 178 establishing handlers 115 live events 116 use of $ within 178 ready state handler 240 See also onreadystatechange ready state handlers 239–240 ready() 110 usage example 12 real-time data 245 regular expressions 25, 183–184, 214 patterns 215 United States postal codes 184 Zip Codes 184 relational selectors 23 remove() method 86
INDEX
removeAttr() method 62 removeClass() method 66 extended by jQuery UI 297 removeData() method 65 removing wrapped set elements 44 rendering engine 176 repeated operations 204 replaceAll() method 89 replaceWith() method 88 replication strategy 129 replication via templates 130 request header 171 request parameters 89 requests asynchronous 235 GET vs POST 250, 254 idempotent 250 initiating 239 multiple 267 non-idempotent 250, 254 resizability disabling 331 events 334 re-enabling 331 removing 331 resizable elements 331 other elements to resize 333 Resizable widget 287 resizable() method handles 335 options 331, 333 syntax 331 resizables event handlers resize events 334 resizestart events 334 resizestop events 334 events 335 Resizables Lab Page, Control Panel 332 resize event 335, 411 resize handler 73 resize operation aspect ratio 333 constraining 333 direction 334 event handlers 334 event triggered 334 excluding elements 333 helper element 334 properties 334 translucent helper 333 via animation 333 resize() method 110
resizeStart event 411 resizestart event 335 resizeStop event 411 resizestop event 335 resizing, definition 306 resources, jQuery plugins 206 response 240–241 JSON 254 responseText property 243 RESTful principles 250 retail web sites 245 reusability 205 reusable code fragments 204 reusable components, avoiding $ collisions 180 reusable tools 204 RIA. See rich internet applications rich internet applications 3 roll-up button 141 roll-up functionality example 140 RoR 192 rounded corners 288 Rounded Corners Mini-Lab 288 Ruby on Rails 192 Ruby, server side 247
S Safari 23, 95, 171 $.support flags 174 problems loading scripts in older versions 200 sample DOM 23 say() method 160 scale animation 156 scale effect 157–158, 294 usage example 299 scope issues 64 script blocks 7 jQuery 7 performance 7 script control preventing form submission 101 removing event handlers 111 script type 262 scripting engines 138 scripting, triggering event handlers 117 scripts, dynamic loading 199, 202 scroll control methods 76 scroll() method 110
INDEX
scrolling 75 scrollLeft() method 76 scrollTop() method 76 segregating the script 7 select element 346 Select.add() method 176 select() method 110, 119 selectability disabling 340 re-enabling 340 removing 340 selectable elements, refreshing 340–341 selectable() method 336 options 341 syntax 340 selectables adding an element 338 creating 340 event handlers selectablestart events 341 selectablestop events 341 selected events 341 selecting events 341 unselected events 341 unselecting events 341 events 343 filtering 341 finding 344 results 337 selecting multiple elements 338 tolerance 341 Selectables Lab Page Control Panel 339 exercises 338, 340 selectablestart event, when triggered 343 selectablestop event, when triggered 343 selected elements 20 finding 344 submitting 344 selected event, when triggered 343 selecting check boxes 29 selecting event, when triggered 343 selecting links 25 selecting, definition 306 selection expressions 22 tag names 22 selection state 336–337 ui-selected class 338 selector filters, combining 31
selector mechanism 205 selectors 5, 8, 18–19, 32, 35 advanced 23 aggregate 41 application 22 attribute 23–24, 26 attribute ends with 26 base selector 31 basic 22–23, 26 basic selector type examples 22 chaining 44 child 23, 26 comprehensive example 268 container 23, 26 cross-browser support 9 CSS syntax 19 CSS3 9 custom 32 checkbox 30 custom filter 29 form-related 31 inverting 31–32 match attribute at beginning 26 multiple 23, 44 PDF files 26 positional 27, 29 regular expression syntax similarity 25 relational 23, 26 selector expression 49 Selectors Lab 23 Selectors Lab Page 20–21, 23–24, 26, 29, 35 filters 31 self-disabling form 63 semantic action blocking 107 semantic actions 94, 101, 117 execution 118 serialization of form elements 189 serialize() method 244 usage example 257 serializeArray() method 245 serializing form data 244 server setup for examples 241 server-side independence 247 resources for example code 241 state 254 technology 247 templating 248
449 server-side code 8, 219 responsibilities 64 servlet engine 242 setInterval() method, usage example 231 setReadOnly() method, implementation 219 shake effect 295 show effect 144 show() method 139, 145 extended by jQuery UI 296 usage example 142 simultaneous animation methods 159 simultaneous animations 159–160 size effect 295 size() method 37 slice() method 47 slide down effect 144 slide effect 295 slide event 359 slide up effect 144 slidechange event 359 slideDown() method 152 slider widgets, creating 354 slider() method, syntax 355 sliders 282, 354 events 358–359 options 357 styling 359 slideshow 223, 226 layout and styling 224 slidestart event 359 slidestop event 359 slideToggle() method 153 slideUp() method 152 snapping edge mode 312 target elements 312 tolerance 312 sniffing 171 sort event 328 sort operation 323 sort order 305 Ajax request 329 fetching 329 sorted items 329 sortability applying 323 disabling 322 enabling 323 events 327 options 324 removing 323
450 sortability actions 322 sortable() method applying sortability 323 establishing handlers 327 options 325 sort order 329 syntax 322 sortables array 323 cache information 323 connecting 327 direct-manipulation interface 327 establishing handlers 327 event handlers sort events 326 sortactivate events 325 sortbeforestop events 325 sortchange events 325 sortdeactivate events 325 sortout events 326 sortover events 326 sortreceive events 326 sortremove events 326 sortstart events 326 sortstop events 326 sortupdate events 326 events 328 exercises 330 final state 344 option for 310 properties 327 refreshing 323 serialized query string 323 Sortables Lab Page 324 Control Panel 324 sort fetch results 329 sortables list 329 sortactivate event 328 sortbeforestop event 328 sortchange event 328 sortdeactivate event 328 sorting 282, 305, 322 definition 306 sortout event 328 sortover event 328 sortreceive event 328 sortremove event 328 sortstart event 328 sortstop event 328 sortupdate event 328 importance 329 sort order 329 sort result 329 span element 353, 367
INDEX
speed of effects 149 srcElement property 98 stack 53 stacking 312 standard event model 102 status codes 240 stop() method 153, 366 stopPropagation() method 101 string trimming 180 String.match() method 184 String.split() method 186 style sheets 8 style.height property 73 style.width property 73 styles 348 applying 349 getting 70 separating from structure 6 setting 70 specifying at creation 34 stylesheets 6 styling 65, 76, 285 sublings() method 50 submit button, disabling 63 submit event 101 canceling 101 submit() method 110, 119 subsettting wrapped sets 47, 49 success 266 support user agent 171 swing easing 299 switchClass() method 298 synchronous Ajax 239
T Tab widget 286 icons 287 tabbed panels 389 alternative 405 tabs 282 creating 389 events 396 styling 397 Tabs Lab 393 tabs() method 391 options 394 tabsadd event 396 tabsdisable event 396 tabsenable event 396 tabsload event 396 tabsremove event 396 tabsselect event 396 tabsshow event 396
target elements 5, 100, 312 event propagation 103 target property 98 targets multiple 79 target element 80 template class 127 templates creating 133 replicating 128, 131, 134 replicating elements 126 replication 126 templating 248 term 374 Termifier, The 273 comprehensive example 269 exercises 277 implementation 270 testing 274 test subjects 149 test-driven development 225 testing for existence 15 testing objects 193 testSubject class 360 text type 262 text() method 78 text/xml 240 theme 282–283 creating 289 CSS file 284 images 284 reloading 290 Theme Switcher Widget 285 themed buttons, creating 349 themed icons 352 ThemeRoller tool 286, 288 usage 290 themes 285 button controls appearance 348 custom 289 predefined 286 setting up 286 switching 285 theming 350 this 424, 428 See also function context this keyword 15 thumbnail images 223 timers 94 title attribute, as tooltip 268 toArray() method 38 toggle() method 119, 146 applied individually 149 callback 147
451
INDEX
toggle() method (continued) extended by jQuery UI 296 naming 121 usage example 143, 231 toggleClass() method 67–68 extended by jQuery UI 297 toggling class names 68 display state 143 process 146 Tomcat 242, 368, 372, 392 port 8080 242 testing 242 tooltips 73, 268 custom implementation 268 top property 161 transfer effect 295 translating arrays 184 translating data 185 translation functions 214 trash icon, drag and drop 306 tree root 100 trigger() method 117 data parameter 118 example usage 131 triggerHandler() method 118 triggering events 117 trimming strings 180 Twitter 3
U ui- prefix 286 UI principles, gradual transition 144 ui-accordion class 403 ui-accordion-content class 403 ui-accordion-content-active class 404 ui-accordion-header class 403 ui-autocomplete class 376 ui-autocomplete-input class 376 ui-button-text class 353 ui-corner classes 288 ui-dialog class 411 ui-dialog-content class 411 ui-dialog-title class 411 ui-dialog-titlebar class 411 ui-dialog-titlebar-close class 411 ui-draggable class 308 adding 309 ui-draggable-dragging class 308 adding 309 ui-droppable class, adding 317
ui-icon class 287, 335 ui-icon-gripsmall-diagonal-se class 335 ui-menu class 376 ui-menu-item class 376 ui-progressbar class 369 ui-progressbar-value class 369 ui-resizable-handle class 335 ui-resizable-helper class 333–334 ui-resizable-n class 335 ui-resizable-xx class 335 ui-selected class 338, 343–344 ui-selectee class 341 ui-selecting class 343 ui-slider class 359 ui-slider-handle class 359 ui-slider-horizontal class 359 ui-slider-vertical class 359 ui-state classes 287 ui-state-active class 286, 404 ui-state-hover class 376 ui-tabs class 397 ui-tabs-nav class 397 ui-tabs-panel class 397 ui-tabs-selected class 397 ui-unselecting class 343 ui-widget class 287 ui-widget-content class 287 ui-widget-header class 287, 360 unbind() method 110, 112 unified events API 109 UNIX grep 183 unload() method 110 Unobtrusive JavaScript 6–7, 11, 97, 246 coding patterns 8 disadvantage 8 practical application 226 violation 97 unselected event, when triggered 343 unselecting event 343 unthemed display 348 unwrap() method 85 URI encoding 239, 244 URLs 189, 239 non-alphanumeric characters 190 usability 305 user agent 171 detection 171, 173 spoofing 171 string 171
user interfaces annoyances 55 behavior 94 display 94 too much information 369 user-friendliness factor 219 utility functions 11, 169, 189 $.ajax() function 261 $.ajaxSetup function 264 $.contains() function 194 $.data() function 195 $.each() function 182 $.extend() function 188 $.get() function 252 $.getJSON() function 254 $.getScript() function 200 $.globalEval() function 199 $.grep() function 183 $.inArray() function 186 $.isArray() function 193 $.isEmptyObject() function 193 $.isFunction() function 193 $.isPlainObject() function 193 $.isXMLDoc() function 193 $.makeArray() function 186 $.map() function 184 $.merge() function 187 $.noConflict() function 177 $.noop() function 194 $.param() function 190 $.parseJSON() function 198 $.post() function 255 $.proxy() function 196 $.removeData () function 195 $.trim() function 181 $.unique() function 187 adding custom 210 as jQuery extensions 206 avoiding conflict 212 creating 213, 216 custom 211 data manipulation 211 date formatter 214 namespacing 212 naming 207 on $ namespace 170 subfunctions 215 trimming strings 11
V val() method 90–91 limitations 90
452 value, getting a value 90 variable parameter lists 193 variables as part of closure 429 visibility methods, extended 296 visible elements 76, 282, 285
W W3C DOM specification, DOM level 95 W3C. See World Wide Web Consortium wastebasket icon, drag and drop 306 web applications interactive 4–5, 18 next-generation 16 separation of responsibilities 8 web development CSS 6 elements 4 jQuery 3–4 patterns 3 styles 6 web experience 56 web server document base 242 for example code 241 PHP-enabled 242 Tomcat 242 URL 242 web-based dialog box 405 WebKit $.support flags 174 engine 176 week numbering 389 well-formed markup 33 widgets 282 identifying 287 state tracking 287 width, setting 72 width() method 72 wiki 62 window object 12 window, properties 420 window.clearInterval() method 367 window.event property 98, 106, 112 window.open() method 405 window.setInterval() function 366, 429 window.setTimeout() 424 World Wide Web 189 events 93
INDEX
World Wide Web Consortium 23 Wow factor 56 wrap() method 84 wrapAll() method 85 wrapInner() method 85 wrapped element set 18 wrapped elements 35, 37 fetching as an array 38 wrapped set 9, 21, 35 add() method 43 adding elements 41, 44 adjusting elements 41 array indexing 58 as array 37 as JavaScript array 40 augmenting 41 augmenting using relationships 49 augmenting with add() method 44 determining size 37 dynamic adjustment of elements 46 filtering 45 filtering with not() method 45 finding all the elements 40 finding descendants 51 iterating over 49 manipulation 35 obtaining elements from 37, 41 programmatic filtering 45 removing elements 44, 46 removing elements with filter() method 45 selecting images 42 subsetting 47 subsetting using relationships 49 subsetting with slice() method 47 testing for matches 52 transformations 48 translating elements 48 traversing 49 wrapped sets creating 36 managing with jQuery 54 multiple 52 wrapper 9 wrapper functions, creating 216 wrapper methods 9, 19, 36, 216 adding 216–217
applying multiple operations 218, 222 chaining 52 custom 220 defining 216, 233 implementation functions 229, 231 maintaining state 227 read-only status 222 retaining state 223 techniques 218
X XHR See XMLHttpRequest XHTML 59 attribute names 59 See also Extensible Hypertext Markup Language XML as Ajax response 240 documents 187 DOM 241, 253 processing 241 XPath 8 +xml on MIME type 240 XMLHTTP 236 XMLHttpRequest 236 current state 240 fine-grained control 261 Google 236 initiating request 239 instance creation example 237 instantiating 237 making the request 239 methods 238 native example 242 parameters 239 progress 239 properties 238 ready state handler 239 responses 240–241 responseText property 240 responseXML property 241 sending 239 setting HTTP method 239 setting URL 239 specification URL 238 status 240
Z z-index 312
WEB DEVELOPMENT
jQuery IN ACTION, SECOND EDITION Bear Bibeault Yehuda Katz
A
good web development framework anticipates your needs—jQuery practically reads your mind. You’ll fall in love with it when you see 20 lines of code reduced to three. jQuery is concise and readable. And with version 1.4, there’s even more to love including new effects and events, usability improvements, and more testing options.
jQuery in Action, Second Edition is a fast-paced introduction to jQuery that will take your JavaScript programming to the next level. An in-depth rewrite of the bestselling first edition, this edition provides deep and practical coverage of the latest jQuery and jQuery UI releases. The book’s unique “lab pages” anchor the explanation of each new concept in a practical example. You’ll learn how to traverse HTML documents, handle events, perform animations, and add Ajax to your web pages. This comprehensive guide also teaches you how jQuery interacts with other tools and frameworks and how to build jQuery plugins.
What’s Inside
—From the Foreword to the First Edition by John Resig Creator of jQuery
“Clear, concise, complete— the only jQuery core book you’ll ever need.” —Christopher Haupt Webvanta, Inc
“Indispensable! A lively and detailed exploration of jQuery.” —Scott Sauyet Four Winds Software
—Michael Smolyak, SumoBrain
Bear Bibeault is a software architect and JavaRanch senior moderator and coauthor of Manning’s Ajax in Practice and Prototype and Scriptaculous in Action. Yehuda Katz is a developer with Engine Yard. He heads the jQuery plugin development team and runs Visual jQuery. For online access to the authors and a free ebook for owners of this book, go to manning.com/jQueryinActionSecondEdition
$44.99 / Can $56.99
“The best-thought-out and researched piece of literature on the jQuery library.”
“They’ve done it again— created an invaluable companion in the quest for jQuery mastery.”
In-depth jQuery 1.4 Complete coverage of jQuery UI 1.8 DOM manipulation and event handling Animation and UI effects Many practical examples
MANNING
SEE INSERT
[INCLUDING eBOOK]
“If jQuery is your religion, this book is your Bible!” —Jonas Bandi, TechTalk