Jquery Fundamentals Book PDF
Jquery Fundamentals Book PDF
jQuery Fundamentals
Rebecca Murphey [http://www.rebeccamurphey.com] Copyright 2010
Licensed by Rebecca Murphey under the Creative Commons Attribution-Share Alike 3.0 United States license [http://creativecommons.org/licenses/ by-sa/3.0/us/]. You are free to copy, distribute, transmit, and remix this work, provided you attribute the work to Rebecca Murphey as the original author and reference the GitHub repository for the work [http://github.com/rmurphey/jqfundamentals]. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license. Any of the above conditions can be waived if you get permission from the copyright holder. For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to the license [http://creativecommons.org/licenses/by-sa/3.0/us/].
Table of Contents
1. Welcome ....................................................................................................................... 1 Getting the Code ........................................................................................................ 1 Software ................................................................................................................... 1 Adding JavaScript to Your Page ................................................................................... 1 JavaScript Debugging .................................................................................................. 2 Exercises ................................................................................................................... 2 Conventions used in this book ...................................................................................... 2 Reference Material ...................................................................................................... 3 I. JavaScript 101 ................................................................................................................ 4 2. JavaScript Basics .................................................................................................... 5 Overview .......................................................................................................... 5 Syntax Basics .................................................................................................... 5 Operators .......................................................................................................... 5 Basic Operators .......................................................................................... 5 Operations on Numbers & Strings ................................................................. 6 Logical Operators ....................................................................................... 6 Comparison Operators ................................................................................. 7 Conditional Code ................................................................................................ 7 Truthy and Falsy Things .............................................................................. 8 Conditional Variable Assignment with The Ternary Operator .............................. 9 Switch Statements ...................................................................................... 9 Loops ............................................................................................................. 10 The for loop ............................................................................................ 10 The while loop ......................................................................................... 11 The do-while loop ..................................................................................... 11 Breaking and continuing ............................................................................ 12 Reserved Words ............................................................................................... 12 Arrays ............................................................................................................. 14 Objects ............................................................................................................ 15 Functions ......................................................................................................... 16 Using Functions ........................................................................................ 16 Self-Executing Anonymous Functions ........................................................... 17 Functions as Arguments ............................................................................. 17 Testing Type .................................................................................................... 17 Scope .............................................................................................................. 18 Closures .......................................................................................................... 20 II. jQuery: Basic Concepts ................................................................................................. 21 3. jQuery Basics ....................................................................................................... 22 $(document).ready() .......................................................................................... 22 Selecting Elements ............................................................................................ 22 Does My Selection Contain Any Elements? ................................................... 24 Saving Selections ...................................................................................... 24 Refining & Filtering Selections ................................................................... 25 Selecting Form Elements ............................................................................ 25 Working with Selections .................................................................................... 26 Chaining .................................................................................................. 26 Getters & Setters ...................................................................................... 27 CSS, Styling, & Dimensions ............................................................................... 27 Using CSS Classes for Styling .................................................................... 27 Dimensions .............................................................................................. 28 Attributes ........................................................................................................ 28
iii
jQuery Fundamentals
4.
5.
6.
7.
Traversing ....................................................................................................... Manipulating Elements ...................................................................................... Getting and Setting Information about Elements ............................................. Moving, Copying, and Removing Elements ................................................... Creating New Elements ............................................................................. Manipulating Attributes ............................................................................. Exercises ......................................................................................................... Selecting ................................................................................................. Traversing ............................................................................................... Manipulating ............................................................................................ jQuery Core ......................................................................................................... $ vs $() ........................................................................................................ Utility Methods ................................................................................................ Checking types ................................................................................................. Data Methods ................................................................................................... Feature & Browser Detection .............................................................................. Avoiding Conflicts with Other Libraries ............................................................... Events ................................................................................................................. Overview ......................................................................................................... Connecting Events to Elements ........................................................................... Connecting Events to Run Only Once .......................................................... Disconnecting Events ................................................................................ Namespacing Events .................................................................................. Inside the Event Handling Function ..................................................................... Triggering Event Handlers .................................................................................. Increasing Performance with Event Delegation ....................................................... Unbinding Delegated Events ....................................................................... Event Helpers .................................................................................................. $.fn.hover .......................................................................................... $.fn.toggle ........................................................................................ Exercises ......................................................................................................... Create an Input Hint .................................................................................. Add Tabbed Navigation ............................................................................. Effects ................................................................................................................. Overview ......................................................................................................... Built-in Effects ................................................................................................. Changing the Duration of Built-in Effects ..................................................... Doing Something when an Effect is Done ..................................................... Custom Effects with $.fn.animate ................................................................. Easing ..................................................................................................... Managing Effects .............................................................................................. Exercises ......................................................................................................... Reveal Hidden Text .................................................................................. Create Dropdown Menus ............................................................................ Create a Slideshow ................................................................................... Ajax .................................................................................................................... Overview ......................................................................................................... Key Concepts ................................................................................................... GET vs. Post ........................................................................................... Data Types .............................................................................................. A is for Asynchronous ............................................................................... Same-Origin Policy and JSONP .................................................................. Ajax and Firebug ...................................................................................... jQuery's Ajax-Related Methods ...........................................................................
29 29 30 30 32 33 33 33 34 34 35 35 35 36 37 38 38 39 39 39 39 40 40 40 41 41 42 42 42 43 43 43 43 45 45 45 45 46 46 47 47 47 47 48 48 49 49 49 49 49 50 50 50 50
iv
jQuery Fundamentals
$.ajax ...................................................................................................... Convenience Methods ................................................................................ $.fn.load ............................................................................................ Ajax and Forms ................................................................................................ Working with JSONP ........................................................................................ Ajax Events ..................................................................................................... Exercises ......................................................................................................... Load External Content ............................................................................... Load Content Using JSON ......................................................................... 8. Plugins ................................................................................................................ What exactly is a plugin? ................................................................................... How to create a basic plugin .............................................................................. Finding & Evaluating Plugins ............................................................................. Writing Plugins ................................................................................................ Writing Stateful Plugins with the jQuery UI Widget Factory ..................................... Adding Methods to a Widget ...................................................................... Working with Widget Options ..................................................................... Adding Callbacks ...................................................................................... Cleaning Up ............................................................................................ Conclusion ............................................................................................... Exercises ......................................................................................................... Make a Table Sortable ............................................................................... Write a Table-Striping Plugin ..................................................................... III. Advanced Topics ......................................................................................................... This Section is a Work in Progress .............................................................................. 9. Performance Best Practices ..................................................................................... Cache length during loops .................................................................................. Append new content outside of a loop .................................................................. Keep things DRY ............................................................................................. Beware anonymous functions .............................................................................. Optimize Selectors ............................................................................................ ID-Based Selectors .................................................................................... Specificity ............................................................................................... Avoid the Universal Selector ...................................................................... Use Event Delegation ........................................................................................ Detach Elements to Work With Them .................................................................. Use Stylesheets for Changing CSS on Many Elements ............................................. Use $.data Instead of $.fn.data .................................................................. Don't Act on Absent Elements ............................................................................ Variable Definition ............................................................................................ Conditionals ..................................................................................................... Don't Treat jQuery as a Black Box ...................................................................... 10. Code Organization ............................................................................................... Overview ......................................................................................................... Key Concepts ........................................................................................... Encapsulation ................................................................................................... The Object Literal ..................................................................................... The Module Pattern ................................................................................... Managing Dependencies ..................................................................................... Getting RequireJS ..................................................................................... Using RequireJS with jQuery ...................................................................... Creating Reusable Modules with RequireJS ................................................... Optimizing Your Code: The RequireJS Build Tool .......................................... Exercises .........................................................................................................
51 52 54 54 54 55 55 55 56 57 57 57 59 59 62 63 65 66 67 68 68 68 69 70 71 72 72 72 72 73 74 74 74 74 75 75 75 75 76 76 77 77 78 78 78 78 78 81 84 84 84 85 87 88
jQuery Fundamentals
Create a Portlet Module ............................................................................. 11. Custom Events .................................................................................................... Introducing Custom Events ................................................................................. A Sample Application ...............................................................................
88 89 89 91
vi
List of Examples
1.1. An example of inline Javascript ...................................................................................... 1 1.2. An example of including external JavaScript ..................................................................... 1 1.3. Example of an example ................................................................................................. 3 2.1. A simple variable declaration ......................................................................................... 5 2.2. Whitespace has no meaning outside of quotation marks ....................................................... 5 2.3. Parentheses indicate precedence ...................................................................................... 5 2.4. Tabs enhance readability, but have no special meaning ........................................................ 5 2.5. Concatenation .............................................................................................................. 5 2.6. Multiplication and division ............................................................................................. 6 2.7. Incrementing and decrementing ....................................................................................... 6 2.8. Addition vs. concatenation ............................................................................................. 6 2.9. Forcing a string to act as a number .................................................................................. 6 2.10. Forcing a string to act as a number (using the unary-plus operator) ....................................... 6 2.11. Logical AND and OR operators .................................................................................... 6 2.12. Comparison operators .................................................................................................. 7 2.13. Flow control .............................................................................................................. 8 2.14. Values that evaluate to true ....................................................................................... 8 2.15. Values that evaluate to false ...................................................................................... 8 2.16. The ternary operator .................................................................................................... 9 2.17. A switch statement ...................................................................................................... 9 2.18. Loops ...................................................................................................................... 10 2.19. A typical for loop ................................................................................................... 10 2.20. A typical while loop ............................................................................................... 11 2.21. A while loop with a combined conditional and incrementer ............................................ 11 2.22. A do-while loop ................................................................................................... 11 2.23. Stopping a loop ........................................................................................................ 12 2.24. Skipping to the next iteration of a loop ......................................................................... 12 2.25. A simple array .......................................................................................................... 14 2.26. Accessing array items by index ................................................................................... 14 2.27. Testing the size of an array ......................................................................................... 14 2.28. Changing the value of an array item ............................................................................. 15 2.29. Adding elements to an array ....................................................................................... 15 2.30. Working with arrays .................................................................................................. 15 2.31. Creating an "object literal" .......................................................................................... 15 2.32. Function Declaration .................................................................................................. 16 2.33. Named Function Expression ........................................................................................ 16 2.34. A simple function ..................................................................................................... 16 2.35. A function that returns a value .................................................................................... 16 2.36. A function that returns another function ........................................................................ 16 2.37. A self-executing anonymous function ........................................................................... 17 2.38. Passing an anonymous function as an argument .............................................................. 17 2.39. Passing a named function as an argument ...................................................................... 17 2.40. Testing the type of various variables ............................................................................ 18 2.41. Functions have access to variables defined in the same scope ............................................ 19 2.42. Code outside the scope in which a variable was defined does not have access to the variable ....................................................................................................................................... 19 2.43. Variables with the same name can exist in different scopes with different values .................... 19 2.44. Functions can "see" changes in variable values after the function is defined .......................... 19 2.45. Scope insanity .......................................................................................................... 20 2.46. How to lock in the value of i? .................................................................................... 20 2.47. Locking in the value of i with a closure ....................................................................... 20
vii
jQuery Fundamentals
3.1. A $(document).ready() block ........................................................................................ 3.2. Shorthand for $(document).ready() ................................................................................. 3.3. Passing a named function instead of an anonymous function ............................................... 3.4. Selecting elements by ID ............................................................................................. 3.5. Selecting elements by class name .................................................................................. 3.6. Selecting elements by attribute ...................................................................................... 3.7. Selecting elements by compound CSS selector ................................................................. 3.8. Pseudo-selectors ......................................................................................................... 3.9. Testing whether a selection contains elements .................................................................. 3.10. Storing selections in a variable .................................................................................... 3.11. Refining selections .................................................................................................... 3.12. Using form-related pseduo-selectors ............................................................................. 3.13. Chaining .................................................................................................................. 3.14. Formatting chained code ............................................................................................ 3.15. Restoring your original selection using $.fn.end ......................................................... 3.16. The $.fn.html method used as a setter ..................................................................... 3.17. The html method used as a getter ................................................................................ 3.18. Getting CSS properties ............................................................................................... 3.19. Setting CSS properties ............................................................................................... 3.20. Working with classes ................................................................................................. 3.21. Basic dimensions methods .......................................................................................... 3.22. Setting attributes ....................................................................................................... 3.23. Getting attributes ...................................................................................................... 3.24. Moving around the DOM using traversal methods ........................................................... 3.25. Iterating over a selection ............................................................................................ 3.26. Changing the HTML of an element .............................................................................. 3.27. Moving elements using different approaches .................................................................. 3.28. Making a copy of an element ...................................................................................... 3.29. Creating new elements ............................................................................................... 3.30. Creating a new element with an attribute object .............................................................. 3.31. Getting a new element on to the page ........................................................................... 3.32. Creating and adding an element to the page at the same time ............................................. 3.33. Manipulating a single attribute .................................................................................... 3.34. Manipulating multiple attributes ................................................................................... 3.35. Using a function to determine an attribute's new value ..................................................... 4.1. Checking the type of an arbitrary value .......................................................................... 4.2. Storing and retrieving data related to an element .............................................................. 4.3. Storing a relationship between elements using $.fn.data ............................................... 4.4. Putting jQuery into no-conflict mode .............................................................................. 4.5. Using the $ inside a self-executing anonymous function ..................................................... 5.1. Event binding using a convenience method ..................................................................... 5.2. Event biding using the $.fn.bind method ................................................................... 5.3. Event binding using the $.fn.bind method with data .................................................... 5.4. Switching handlers using the $.fn.one method ............................................................. 5.5. Unbinding all click handlers on a selection ...................................................................... 5.6. Unbinding a particular click handler ............................................................................... 5.7. Namespacing events .................................................................................................... 5.8. Preventing a link from being followed ............................................................................ 5.9. Triggering an event handler the right way ....................................................................... 5.10. Event delegation using $.fn.delegate .................................................................... 5.11. Event delegation using $.fn.live ............................................................................ 5.12. Unbinding delegated events ........................................................................................ 5.13. The hover helper function ........................................................................................... 5.14. The toggle helper function ..........................................................................................
22 22 22 22 22 23 23 23 24 25 25 26 26 26 26 27 27 27 27 28 28 28 29 29 29 30 31 31 32 32 32 32 33 33 33 37 37 37 38 38 39 39 39 40 40 40 40 41 41 42 42 42 42 43
viii
jQuery Fundamentals
6.1. A basic use of a built-in effect ...................................................................................... 6.2. Setting the duration of an effect .................................................................................... 6.3. Augmenting jQuery.fx.speeds with custom speed definitions ...................................... 6.4. Running code when an animation is complete .................................................................. 6.5. Run a callback even if there were no elements to animate .................................................. 6.6. Custom effects with $.fn.animate ............................................................................ 6.7. Per-property easing ..................................................................................................... 7.1. Using the core $.ajax method ........................................................................................ 7.2. Using jQuery's Ajax convenience methods ...................................................................... 7.3. Using $.fn.load to populate an element ..................................................................... 7.4. Using $.fn.load to populate an element based on a selector ........................................... 7.5. Turning form data into a query string ............................................................................. 7.6. Creating an array of objects containing form data ............................................................. 7.7. Using YQL and JSONP ............................................................................................... 7.8. Setting up a loading indicator using Ajax Events .............................................................. 8.1. Creating a plugin to add and remove a class on hover ........................................................ 8.2. The Mike Alsup jQuery Plugin Development Pattern ......................................................... 8.3. A simple, stateful plugin using the jQuery UI widget factory .............................................. 8.4. Passing options to a widget .......................................................................................... 8.5. Setting default options for a widget ................................................................................ 8.6. Creating widget methods .............................................................................................. 8.7. Calling methods on a plugin instance ............................................................................. 8.8. Responding when an option is set .................................................................................. 8.9. Providing callbacks for user extension ............................................................................ 8.10. Binding to widget events ............................................................................................ 8.11. Adding a destroy method to a widget ........................................................................... 10.1. An object literal ........................................................................................................ 10.2. Using an object literal for a jQuery feature .................................................................... 10.3. The module pattern ................................................................................................... 10.4. Using the module pattern for a jQuery feature ................................................................ 10.5. Using RequireJS: A simple example ............................................................................. 10.6. A simple JavaScript file with dependencies .................................................................... 10.7. Defining a RequireJS module that has no dependencies .................................................... 10.8. Defining a RequireJS module with dependencies ............................................................ 10.9. Defining a RequireJS module that returns a function ........................................................ 10.10. A RequireJS build configuration file ...........................................................................
45 45 46 46 46 46 47 51 53 54 54 54 54 55 55 60 61 62 63 63 64 65 65 66 67 68 79 80 81 83 84 85 86 86 86 87
ix
Chapter 1. Welcome
jQuery is fast becoming a must-have skill for front-end developers. The purpose of this book is to provide an overview of the jQuery JavaScript library; when you're done with the book, you should be able to complete basic tasks using jQuery, and have a solid basis from which to continue your learning. This book was designed as material to be used in a classroom setting, but you may find it useful for individual study. This is a hands-on class. We will spend a bit of time covering a concept, and then youll have the chance to work on an exercise related to the concept. Some of the exercises may seem trivial; others may be downright daunting. In either case, there is no grade; the goal is simply to get you comfortable working your way through problems youll commonly be called upon to solve using jQuery. Example solutions to all of the exercises are included in the sample code.
Software
You'll want to have the following tools to make the most of the class: The Firefox browser The Firebug extension for Firefox A plain text editor For the Ajax portions: A local server (such as MAMP or WAMP), or an FTP or SSH client to access a remote server.
Welcome
JavaScript Debugging
A debugging tool is essential for JavaScript development. Firefox provides a debugger via the Firebug extension; Safari and Chrome provide built-in consoles. Each console offers: single- and multi-line editors for experimenting with JavaScript an inspector for looking at the generated source of your page a Network or Resources view, to examine network requests When you are writing JavaScript code, you can use the following methods to send messages to the console: console.log() for sending general log messages console.dir() for logging a browseable object console.warn() for logging warnings console.error() for logging error messages Other console methods are also available, though they may differ from one browser to another. The consoles also provide the ability to set break points and watch expressions in your code for debugging purposes.
Exercises
Most chapters in the book conclude with one or more exercises. For some exercises, youll be able to work directly in Firebug; for others, you will need to include other scripts after the jQuery script tag as directed in the individual exercises. In some cases, you will need to consult the jQuery documentation in order to complete an exercise, as we wont have covered all of the relevant information in the book. This is by design; the jQuery library is large, and learning to find answers in the documentation is an important part of the process. Here are a few suggestions for tackling these problems: First, make sure you thoroughly understand the problem you're being asked to solve. Next, figure out which elements you'll need to access in order to solve the problem, and determine how you'll get those elements. Use Firebug to verify that you're getting the elements you're after. Finally, figure out what you need to do with the elements to solve the problem. It can be helpful to write comments explaining what you're going to do before you try to write the code to do it. Do not be afraid to make mistakes! Do not try to make your code perfect on the first try! Making mistakes and experimenting with solutions is part of learning the library, and youll be a better developer for it. Examples of solutions for these exercises are located in the /solutions directory in the sample code.
Welcome
$.methodName. If this doesn't mean much to you, don't worry it should become clearer as you progress through the book.
Note
Notes about a topic will appear like this.
Reference Material
There are any number of articles and blog posts out there that address some aspect of jQuery. Some are phenomenal; some are downright wrong. When you read an article about jQuery, be sure it's talking about the same version as you're using, and resist the urge to just copy and paste take the time to understand the code in the article. Here are some excellent resources to use during your jQuery learning. The most important of all is the jQuery source itself: it contains, in code form, complete documentation of the library. It is not a black box your understanding of the library will grow exponentially if you spend some time visiting it now and again and I highly recommend bookmarking it in your browser and referring to it often. The jQuery source [http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js] jQuery documentation [http://api.jquery.com] jQuery forum [http://forum.jquery.com/] Delicious bookmarks [http://delicious.com/rdmey/jquery-class] #jquery IRC channel on Freenode [http://docs.jquery.com/Discussion#Chat_.2F_IRC_Channel]
Syntax Basics
Understanding statements, variable naming, whitespace, and other basic JavaScript syntax.
Operators
Basic Operators
Basic operators allow you to manipulate values.
JavaScript Basics
Example 2.10. Forcing a string to act as a number (using the unary-plus operator)
console.log(foo + +bar);
Logical Operators
Logical operators allow you to evaluate a series of operands using AND and OR operations.
JavaScript Basics
Though it may not be clear from the example, the || operator returns the value of the first truthy operand, or, in cases where neither operand is truthy, it'll return the last of both operands. The && operator returns the value of the first false operand, or the value of the last operand if both operands are truthy. Be sure to consult the section called Truthy and Falsy Things for more details on which values evaluate to true and which evaluate to false.
Note
You'll sometimes see developers use these logical operators for flow control instead of using if statements. For example: // do something with foo if foo is truthy foo && doSomething(foo); // set bar to baz if baz is truthy; // otherwise, set it to the return // value of createBar() var bar = baz || createBar(); This style is quite elegant and pleasantly terse; that said, it can be really hard to read, especially for beginners. I bring it up here so you'll recognize it in code you read, but I don't recommend using it until you're extremely comfortable with what it means and how you can expect it to behave.
Comparison Operators
Comparison operators allow you to test whether values are equivalent or whether values are identical.
foo === baz; foo !== baz; foo === parseInt(baz); foo > bim; bim > baz; foo <= baz;
Conditional Code
Sometimes you only want to run a block of code under certain conditions. Flow control via if and else blocks lets you run code only under certain conditions.
JavaScript Basics
Note
While curly braces aren't strictly required around single-line if statements, using them consistently, even when they aren't strictly required, makes for vastly more readable code. Be mindful not to define functions with the same name multiple times within separate if/else blocks, as doing so may not have the expected result.
JavaScript Basics
Switch Statements
Rather than using a series of if/else if/else blocks, sometimes it can be useful to use a switch statement instead. [Definition: Switch statements look at the value of a variable or expression, and run different blocks of code depending on the value.]
JavaScript Basics
alert('everything else is just ok'); } }; if (stuffToDo[foo]) { stuffToDo[foo](); } else { stuffToDo['default'](); } We'll look at objects in greater depth later in this chapter.
Loops
Loops let you run a block of code a certain number of times.
10
JavaScript Basics
11
JavaScript Basics
These types of loops are quite rare since only few situations require a loop that blindly executes at least once. Regardless, it's good to be aware of it.
Reserved Words
JavaScript has a number of reserved words, or words that have special meaning in the language. You should avoid using these words in your code except when using them with their intended meaning. break case catch continue default delete do else
12
JavaScript Basics
finally for function if in instanceof new return switch this throw try typeof var void while with abstract boolean byte char class const debugger double enum export extends final
13
JavaScript Basics
float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile
Arrays
Arrays are zero-indexed lists of values. They are a handy way to store a set of related items of the same type (such as strings), though in reality, an array can include multiple types of items, including other arrays.
14
JavaScript Basics
Objects
Objects contain one or more key-value pairs. The key portion can be any string. The value portion can be any type of value: a number, a string, an array, a function, or even another object. [Definition: When one of these values is a function, its called a method of the object.] Otherwise, they are called properties. As it turns out, nearly everything in JavaScript is an object arrays, functions, numbers, even strings and they all have properties and methods.
Note
When creating object literals, you should note that the key portion of each key-value pair can be written as any valid JavaScript identifier, a string (wrapped in quotes) or a number: var myObject = { validIdentifier: 123, 'some string': 456, 99999: 789 };
15
JavaScript Basics
Object literals can be extremely useful for code organization; for more information, read Using Objects to Organize Your Code [http://blog.rebeccamurphey.com/2009/10/15/using-objects-to-organize-your-code/] by Rebecca Murphey.
Functions
Functions contain blocks of code that need to be executed repeatedly. Functions can take zero or more arguments, and can optionally return a value. Functions can be created in a variety of ways:
Using Functions
Example 2.34. A simple function
var greet = function(person, greeting) { var text = greeting + ', ' + person; console.log(text); };
greet('Rebecca', 'Hello');
16
JavaScript Basics
console.log(foo);
// undefined!
Functions as Arguments
In JavaScript, functions are "first-class citizens" -- they can be assigned to variables or passed to other functions as arguments. Passing functions as arguments is an extremely common idiom in jQuery.
Testing Type
JavaScript offers a way to test the "type" of a variable. However, the result can be confusing -- for example, the type of an Array is "object". It's common practice to use the typeof operator when trying to determining the type of a specific value.
17
JavaScript Basics
typeof null;
if (myArray.push && myArray.slice && myArray.join) { // probably an array // (this is called "duck typing") } if (Object.prototype.toString.call(myArray) === '[object Array]') { // Definitely an array! // This is widely considered as the most rebust way // to determine if a specific value is an Array. } jQuery offers utility methods to help you determine the type of an arbitrary value. These will be covered later.
Scope
"Scope" refers to the variables that are available to a piece of code at a given time. A lack of understanding of scope can lead to frustrating debugging experiences. When a variable is declared inside of a function using the var keyword, it is only available to code inside of that function -- code outside of that function cannot access the variable. On the other hand, functions defined inside that function will have access to to the declared variable. Furthermore, variables that are declared inside a function without the var keyword are not local to the function -- JavaScript will traverse the scope chain all the way up to the window scope to find where the variable was previously defined. If the variable wasn't previously defined, it will be defined in the global scope, which can have extremely unexpected consequences;
18
JavaScript Basics
Example 2.41. Functions have access to variables defined in the same scope
var foo = 'hello'; var sayHello = function() { console.log(foo); }; sayHello(); console.log(foo); // logs 'hello' // also logs 'hello'
Example 2.42. Code outside the scope in which a variable was defined does not have access to the variable
var sayHello = function() { var foo = 'hello'; console.log(foo); }; sayHello(); console.log(foo); // logs 'hello' // doesn't log anything
Example 2.43. Variables with the same name can exist in different scopes with different values
var foo = 'world'; var sayHello = function() { var foo = 'hello'; console.log(foo); }; sayHello(); console.log(foo); // logs 'hello' // logs 'world'
Example 2.44. Functions can "see" changes in variable values after the function is defined
var myFunction = function() { var foo = 'hello'; var myFn = function() { console.log(foo); }; foo = 'world'; return myFn; }; var f = myFunction(); f(); // logs 'world' -- uh oh
19
JavaScript Basics
bar is defined outside of the anonymous function because it wasn't declared with var; furthermore, because it was defined in the same scope as baz, it has access to baz even though other code outside of the function does not
bim();
// bim is not defined outside of the anonymous function, // so this will result in an error
Closures
Closures are an extension of the concept of scope functions have access to variables that were available in the scope where the function was created. If thats confusing, dont worry: closures are generally best understood by example. In Example 2.44, Functions can "see" changes in variable values after the function is defined we saw how functions have access to changing variable values. The same sort of behavior exists with functions defined within loops -- the function "sees" the change in the variable's value even after the function is defined, resulting in all clicks alerting 5.
20
$(document).ready(readyFn);
Selecting Elements
The most basic concept of jQuery is to select some elements and do something with them. jQuery supports most CSS3 selectors, as well as some non-standard selectors. For a complete selector reference, visit http://api.jquery.com/category/selectors/. Following are a few examples of common selection techniques.
22
jQuery Basics
Note
When you use the :visible and :hidden pseudo-selectors, jQuery tests the actual visibility of the element, not its CSS visibility or display that is, it looks to see if the element's physical height and width on the page are both greater than zero. However, this test doesn't work with <tr> elements; in this case, jQuery does check the CSS display property, and considers an element hidden if its display property is set to none. Elements that have not been added to the DOM will always be considered hidden, even if the CSS that would affect them would render them visible. (See the Manipulation section later in this chapter to learn how to create and add elements to the DOM.) For reference, here is the code jQuery uses to determine whether an element is visible or hidden, with comments added for clarity: jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight, skip = elem.nodeName.toLowerCase() === "tr"; // does the element have 0 height, 0 width, // and it's not a <tr>? return width === 0 && height === 0 && !skip ? // then it must be hidden true : // but if it has width and height // and it's not a <tr> width > 0 && height > 0 && !skip ? // then it must be visible false : // if we get here, the element has width // and height, but it's also a <tr>, // so check its display property to // decide whether it's hidden jQuery.curCSS(elem, "display") === "none";
23
jQuery Basics
}; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; Choosing Selectors Choosing good selectors is one way to improve the performance of your JavaScript. A little specificity for example, including an element type such as div when selecting elements by class name can go a long way. Generally, any time you can give jQuery a hint about where it might expect to find what you're looking for, you should. On the other hand, too much specificity can be a bad thing. A selector such as #myTable thead tr th.special is overkill if a selector such as #myTable th.special will get you what you want. jQuery offers many attribute-based selectors, allowing you to make selections based on the content of arbitrary attributes using simplified regular expressions. // find all <a>s whose rel attribute // ends with "thinger" $("a[rel$='thinger']"); While these can be useful in a pinch, they can also be extremely slow I once wrote an attributebased selector that locked up my page for multiple seconds. Wherever possible, make your selections using IDs, class names, and tag names. Want to know more? Paul Irish has a great presentation about improving performance in JavaScript [http://paulirish.com/perf], with several slides focused specifically on selector performance.
Saving Selections
Every time you make a selection, a lot of code runs, and jQuery doesn't do caching of selections for you. If you've made a selection that you might need to make again, you should save the selection in a variable rather than making the selection repeatedly.
24
jQuery Basics
Note
In Example 3.10, Storing selections in a variable, the variable name begins with a dollar sign. Unlike in other languages, there's nothing special about the dollar sign in JavaScript -- it's just another character. We use it here to indicate that the variable contains a jQuery object. This practice -- a sort of Hungarian notation [http://en.wikipedia.org/wiki/Hungarian_notation] -- is merely convention, and is not mandatory. Once you've stored your selection, you can call jQuery methods on the variable you stored it in just like you would have called them on the original selection.
Note
A selection only fetches the elements that are on the page when you make the selection. If you add elements to the page later, you'll have to repeat the selection or otherwise add them to the selection stored in the variable. Stored selections don't magically update when the DOM changes.
25
jQuery Basics
Selects inputs with type="password" Selects inputs with type="radio" Selects inputs with type="reset" Selects options that are selected Selects inputs with type="submit" Selects inputs with type="text"
Chaining
If you call a method on a selection and that method returns a jQuery object, you can continue to call jQuery methods on the object without pausing for a semicolon.
26
jQuery Basics
Note
Chaining is extraordinarily powerful, and it's a feature that many libraries have adapted since it was made popular by jQuery. However, it must be used with care. Extensive chaining can make code extremely difficult to modify or debug. There is no hard-and-fast rule to how long a chain should be -- just know that it is easy to get carried away.
Note
CSS properties that normally include a hyphen need to be camel cased in JavaScript. For example, the CSS property font-size is expressed as fontSize in JavaScript.
$('h1').css('fontSize', '100px'); // setting an individual property $('h1').css({ 'fontSize' : '100px', 'color' : 'red' }); // setting multiple propert Note the style of the argument we use on the second line -- it is an object that contains multiple properties. This is a common way to pass multiple arguments to a function, and many jQuery setter methods accept objects to set mulitple values at once.
27
jQuery Basics
write CSS rules for classes that describe the various visual states, and then simply change the class on the element you want to affect.
Dimensions
jQuery offers a variety of methods for obtaining and modifying dimension and position information about an element. The code in Example 3.21, Basic dimensions methods is just a very brief overview of the dimensions functionality in jQuery; for complete details about jQuery dimension methods, visit http://api.jquery.com/ category/dimensions/.
Attributes
An element's attributes can contain useful information for your application, so it's important to be able to get and set them. The $.fn.attr method acts as both a getter and a setter. As with the $.fn.css method, $.fn.attr as a setter can accept either a key and a value, or an object containing one or more key/value pairs.
28
jQuery Basics
This time, we broke the object up into multiple lines. Remember, whitespace doesn't matter in JavaScript, so you should feel free to use it liberally to make your code more legible! You can use a minification tool later to strip out unnecessary whitespace for production.
Traversing
Once you have a jQuery selection, you can find other elements using your selection as a starting point. For complete documentation of jQuery traversal methods, visit http://api.jquery.com/category/traversing/.
Note
Be cautious with traversing long distances in your documents -- complex traversal makes it imperative that your document's structure remain the same, something that's difficult to guarantee even if you're the one creating the whole application from server to client. One- or two-step traversal is fine, but you generally want to avoid traversals that take you from one container to another.
Manipulating Elements
Once you've made a selection, the fun begins. You can change, move, remove, and clone elements. You can also create new elements via a simple syntax. For complete documentation of jQuery manipulation methods, visit http://api.jquery.com/category/ manipulation/.
29
jQuery Basics
Note
Changing things about elements is trivial, but remember that the change will affect all elements in the selection, so if you just want to change one element, be sure to specify that in your selection before calling a setter method.
Note
When methods act as getters, they generally only work on the first element in the selection, and they do not return a jQuery object, so you can't chain additional methods to them. One notable exception is $.fn.text; as mentioned below, it gets the text for all elements in the selection. $.fn.html $.fn.text $.fn.attr $.fn.width $.fn.height $.fn.position Get or set the html contents. Get or set the text contents; HTML will be stripped. Get or set the value of the provided attribute. Get or set the width in pixels of the first element in the selection as an integer. Get or set the height in pixels of the first element in the selection as an integer. Get an object with position information for the first element in the selection, relative to its first positioned ancestor. This is a getter only. Get or set the value of form elements.
$.fn.val
30
jQuery Basics
The method that makes the most sense for you will depend on what elements you already have selected, and whether you will need to store a reference to the elements you're adding to the page. If you need to store a reference, you will always want to take the first approach -- placing the selected elements relative to another element -- as it returns the element(s) you're placing. In this case, $.fn.insertAfter, $.fn.insertBefore, $.fn.appendTo, and $.fn.prependTo will be your tools of choice.
Cloning Elements
When you use methods such as $.fn.appendTo, you are moving the element; sometimes you want to make a copy of the element instead. In this case, you'll need to use $.fn.clone first.
Note
If you need to copy related data and events, be sure to pass true as an argument to $.fn.clone.
Removing Elements
There are two ways to remove elements from the page: $.fn.remove and $.fn.detach. You'll use $.fn.remove when you want to permanently remove the selection from the page; while the method does return the removed element(s), those elements will not have their associated data and events attached to them if you return them to the page. If you need the data and events to persist, you'll want to use $.fn.detach instead. Like $.fn.remove, it returns the selection, but it also maintains the data and events associated with the selection, so you can restore the selection to the page at a later time.
Note
The $.fn.detach method is extremely valuable if you are doing heavy manipulation to an element. In that case, it's beneficial to $.fn.detach the element from the page, work on it in your code, and then restore it to the page when you're done. This saves you from expensive "DOM touches" while maintaining the element's data and events. If you want to leave the element on the page but simply want to remove its contents, you can use $.fn.empty to dispose of the element's inner HTML.
31
jQuery Basics
Example 3.32. Creating and adding an element to the page at the same time
$('ul').append('<li>list item</li>');
Note
The syntax for adding new elements to the page is so easy, it's tempting to forget that there's a huge performance cost for adding to the DOM repeatedly. If you are adding many elements to the same container, you'll want to concatenate all the html into a single string, and then append that string to the container instead of appending the elements one at a time. You can use an array to gather all the pieces together, then join them into a single string for appending. var myItems = [], $myList = $('#myList');
32
jQuery Basics
Manipulating Attributes
jQuery's attribute manipulation capabilities are extensive. Basic changes are simple, but the $.fn.attr method also allows for more complex manipulations.
Exercises
Selecting
Open the file /exercises/index.html in your browser. Use the file /exercises/js/ sandbox.js or work in Firebug to accomplish the following: 1. Select all of the div elements that have a class of "module". 2. Come up with three selectors that you could use to get the third item in the #myList unordered list. Which is the best to use? Why? 3. Select the label for the search input using an attribute selector. 4. Figure out how many elements on the page are hidden (hint: .length). 5. Figure out how many image elements on the page have an alt attribute. 6. Select all of the odd table rows in the table body.
33
jQuery Basics
Traversing
Open the file /exercises/index.html in your browser. Use the file /exercises/js/ sandbox.js or work in Firebug to accomplish the following: 1. Select all of the image elements on the page; log each image's alt attribute. 2. Select the search input text box, then traverse up to the form and add a class to the form. 3. Select the list item inside #myList that has a class of "current" and remove that class from it; add a class of "current" to the next list item. 4. Select the select element inside #specials; traverse your way to the submit button. 5. Select the first list item in the #slideshow element; add the class "current" to it, and then add a class of "disabled" to its sibling elements.
Manipulating
Open the file /exercises/index.html in your browser. Use the file /exercises/js/ sandbox.js or work in Firebug to accomplish the following: 1. Add five new list items to the end of the unordered list #myList. Hint: for (var i = 0; i<5; i++) { ... } 2. Remove the odd list items 3. Add another h2 and another paragraph to the last div.module 4. Add another option to the select element; give the option the value "Wednesday" 5. Add a new div.module to the page after the last one; put a copy of one of the existing images inside of it.
34
Utility Methods
jQuery offers several utility methods in the $ namespace. These methods are helpful for accomplishing routine programming tasks. Below are examples of a few of the utility methods; for a complete reference on jQuery utility methods, visit http://api.jquery.com/category/utilities/. $.trim Removes leading and trailing whitespace. $.trim(' lots of extra whitespace // returns 'lots of extra whitespace' $.each Iterates over arrays and objects. $.each([ 'foo', 'bar', 'baz' ], function(idx, val) { console.log('element ' + idx + 'is ' + val); }); $.each({ foo : 'bar', baz : 'bim' }, function(k, v) { console.log(k + ' : ' + v); }); ');
Note
There is also a method $.fn.each, which is used for iterating over a selection of elements. 35
jQuery Core
$.inArray
Returns a value's index in an array, or -1 if the value is not in the array. var myArray = [ 1, 2, 3, 5 ]; if ($.inArray(4, myArray) !== -1) { console.log('found it!'); }
$.extend
Changes the properties of the first object using the properties of subsequent objects. var firstObject = { foo : 'bar', a : 'b' }; var secondObject = { foo : 'baz' }; var newObject = $.extend(firstObject, secondObject); console.log(firstObject.foo); // 'baz' console.log(newObject.foo); // 'baz' If you don't want to change any of the objects you pass to $.extend, pass an empty object as the first argument. var firstObject = { foo : 'bar', a : 'b' }; var secondObject = { foo : 'baz' }; var newObject = $.extend({}, firstObject, secondObject); console.log(firstObject.foo); // 'bar' console.log(newObject.foo); // 'baz'
$.proxy
Returns a function that will always run in the provided scope that is, sets the meaning of this inside the passed function to the second argument. var myFunction = function() { console.log(this); }; var myObject = { foo : 'bar' }; myFunction(); // logs window object var myProxyFunction = $.proxy(myFunction, myObject); myProxyFunction(); // logs myObject object If you have an object with methods, you can pass the object and the name of a method to return a function that will always run in the scope of the object. var myObject = { myFn : function() { console.log(this); } }; $('#foo').click(myObject.myFn); // logs DOM element #foo $('#foo').click($.proxy(myObject, 'myFn')); // logs myObject
Checking types
As mentioned in the "JavaScript basics" section, jQuery offers a few basic utility methods for determining the type of a specific value. 36
jQuery Core
Data Methods
As your work with jQuery progresses, you'll find that there's often data about an element that you want to store with the element. In plain JavaScript, you might do this by adding a property to the DOM element, but you'd have to deal with memory leaks in some browsers. jQuery offers a straightforward way to store data related to an element, and it manages the memory issues for you.
37
jQuery Core
38
Chapter 5. Events
Overview
jQuery provides simple methods for attaching event handlers to selections. When an event occurs, the provided function is executed. Inside the function, this refers to the element that was clicked. For details on jQuery events, visit http://api.jquery.com/category/events/. The event handling function can receive an event object. This object can be used to determine the nature of the event, and to prevent the events default behavior. For details on the event object, visit http://api.jquery.com/category/events/event-object/.
Example 5.3. Event binding using the $.fn.bind method with data
$('input').bind( 'click change', // bind to multiple events { foo : 'bar' }, // pass in data function(eventObject) { console.log(eventObject.type, eventObject.data); // logs event type, then { foo : 'bar' } } );
39
Events
Disconnecting Events
To disconnect an event handler, you use the $.fn.unbind method and pass in the event type to unbind. If you attached a named function to the event, then you can isolate the unbinding to that named function by passing it as the second argument.
Namespacing Events
For complex applications and for plugins you share with others, it can be useful to namespace your events so you don't unintentionally disconnect events that you didn't or couldn't know about.
40
Events
preventDefault() stopPropagation()
Prevent the default action of the event (e.g. following a link). Stop the event from bubbling up to other elements.
In addition to the event object, the event handling function also has access to the DOM element that the handler was bound to via the keyword this. To turn the DOM element into a jQuery object that we can use jQuery methods on, we simply do $(this), often following this idiom: var $this = $(this);
41
Events
event handlers to hundreds of individual elements is non-trivial; if you have a large set of elements, you should consider delegating related events to a container element.
Note
The $.fn.live method was introduced in jQuery 1.3, and at that time only certain event types were supported. As of jQuery 1.4.2, the $.fn.delegate method is available, and is the preferred method.
Event Helpers
jQuery offers two event-related helper functions that save you a few keystrokes.
$.fn.hover
The $.fn.hover method lets you pass one or two functions to be run when the mouseenter and mouseleave events occur on an element. If you pass one function, it will be run for both events; if you pass two functions, the first will run for mouseenter, and the second will run for mouseleave.
Note
Prior to jQuery 1.4, the $.fn.hover method required two functions.
42
Events
$.fn.toggle
Much like $.fn.hover, the $.fn.toggle method receives two or more functions; each time the event occurs, the next function in the list is called. Generally, $.fn.toggle is used with just two functions, but technically you can use as many as you'd like.
Exercises
Create an Input Hint
Open the file /exercises/index.html in your browser. Use the file /exercises/js/ inputHint.js or work in Firebug. Your task is to use the text of the label for the search input to create "hint" text for the search input. The steps are as follows: 1. Set the value of the search input to the text of the label element 2. Add a class of "hint" to the search input 3. Remove the label element 4. Bind a focus event to the search input that removes the hint text and the "hint" class 5. Bind a blur event to the search input that restores the hint text and "hint" class if no search text was entered What other considerations might there be if you were creating this functionality for a real site?
43
Events
Adds a class of "current" to the clicked list item Removes the class "current" from the other list item 5. Finally, show the first tab.
44
Chapter 6. Effects
Overview
jQuery makes it trivial to add simple effects to your page. Effects can use the built-in settings, or provide a customized duration. You can also create custom animations of arbitrary CSS properties. For complete details on jQuery effects, visit http://api.jquery.com/category/effects/.
Built-in Effects
Frequently used effects are built into jQuery as methods: $.fn.show $.fn.hide $.fn.fadeIn $.fn.fadeOut $.fn.slideDown $.fn.slideUp $.fn.slideToggle Show the selected element. Hide the selected elements. Animate the opacity of the selected elements to 100%. Animate the opacity of the selected elements to 0%. Display the selected elements with a vertical sliding motion. Hide the selected elements with a vertical sliding motion. Show or hide the selected elements with a vertical sliding motion, depending on whether the elements are currently visible.
jQuery.fx.speeds
jQuery has an object at jQuery.fx.speeds that contains the default speed, as well as settings for "slow" and "fast". speeds: { slow: 600, fast: 200, // Default speed _default: 400 }
45
Effects
It is possible to override or add to this object. For example, you may want to change the default duration of effects, or you may want to create your own effects speed.
46
Effects
Note
Color-related properties cannot be animated with $.fn.animate using jQuery out of the box. Color animations can easily be accomplished by including the color plugin [http:// plugins.jquery.com/files/jquery.color.js.txt]. We'll discuss using plugins later in the book.
Easing
[Definition: Easing describes the manner in which an effect occurs -- whether the rate of change is steady, or varies over the duration of the animation.] jQuery includes only two methods of easing: swing and linear. If you want more natural transitions in your animations, various easing plugins are available. As of jQuery 1.4, it is possible to do per-property easing when using the $.fn.animate method.
Managing Effects
jQuery provides several tools for managing animations. $.fn.stop $.fn.delay Stop currently running animations on the selected elements. Wait the specified number of milliseconds before running the next animation. $('h1').show(300).delay(1000).hide(300); jQuery.fx.off If this value is true, there will be no transition for animations; elements will immediately be set to the target final state instead. This can be especially useful when dealing with older browsers; you also may want to provide the option to your users.
Exercises
Reveal Hidden Text
Open the file /exercises/index.html in your browser. Use the file /exercises/js/ blog.js. Your task is to add some interactivity to the blog section of the page. The spec for the feature is as follows: Clicking on a headline in the #blog div should slide down the excerpt paragraph Clicking on another headline should slide down its excerpt paragraph, and slide up any other currently showing excerpt paragraphs.
47
Effects
Create a Slideshow
Open the file /exercises/index.html in your browser. Use the file /exercises/js/ slideshow.js. Your task is to take a plain semantic HTML page and enhance it with JavaScript by adding a slideshow. 1. Move the #slideshow element to the top of the body. 2. Write code to cycle through the list items inside the element; fade one in, display it for a few seconds, then fade it out and fade in the next one. 3. When you get to the end of the list, start again at the beginning. For an extra challenge, create a navigation area under the slideshow that shows how many images there are and which image you're currently viewing. (Hint: $.fn.prevAll will come in handy for this.)
48
Chapter 7. Ajax
Overview
The XMLHttpRequest method (XHR) allows browsers to communicate with the server without requiring a page reload. This method, also known as Ajax (Asynchronous JavaScript and XML), allows for web pages that provide rich, interactive experiences. Ajax requests are triggered by JavaScript code; your code sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the response. Because the request is asynchronous, the rest of your code continues to execute while the request is being processed, so its imperative that a callback be used to handle the response. jQuery provides Ajax support that abstracts away painful browser differences. It offers both a fullfeatured $.ajax() method, and simple convenience methods such as $.get(), $.getScript(), $.getJSON(), $.post(), and $().load(). Most jQuery applications dont in fact use XML, despite the name Ajax; instead, they transport data as plain HTML or JSON (JavaScript Object Notation). In general, Ajax does not work across domains. Exceptions are services that provide JSONP (JSON with Padding) support, which allow limited cross-domain functionality.
Key Concepts
Proper use of Ajax-related jQuery methods requires understanding some key concepts first.
Data Types
jQuery generally requires some instruction as to the type of data you expect to get back from an Ajax request; in some cases the data type is specified by the method name, and in other cases it is provided as part of a configuration object. There are several options: text html script For transporting simple strings For transporting blocks of HTML to be placed on the page For adding a new script to the page
49
Ajax
json
For transporting JSON-formatted data, which can include strings, arrays, and objects
Note
As of jQuery 1.4, if the JSON data sent by your server isn't properly formatted, the request may fail silently. See http://json.org for details on properly formatting JSON, but as a general rule, use built-in language methods for generating JSON on the server to avoid syntax issues. jsonp xml For transporting JSON data from another domain For transporting data in a custom XML schema
I am a strong proponent of using the JSON format in most cases, as it provides the most flexibility. It is especially useful for sending both HTML and data at the same time.
A is for Asynchronous
The asynchronicity of Ajax catches many new jQuery users off guard. Because Ajax calls are asynchronous by default, the response is not immediately available. Responses can only be handled using a callback. So, for example, the following code will not work: var response; $.get('foo.php', function(r) { response = r; }); console.log(response); // undefined! Instead, we need to pass a callback function to our request; this callback will run when the request succeeds, at which point we can access the data that it returned, if any. $.get('foo.php', function(response) { console.log(response); });
50
Ajax
I generally use the $.ajax method and do not use convenience methods. As you'll see, it offers features that the convenience methods do not, and its syntax is more easily understandable, in my opinion.
$.ajax
jQuerys core $.ajax method is a powerful and straightforward way of creating Ajax requests. It takes a configuration object that contains all the instructions jQuery requires to complete the request. The $.ajax method is particularly valuable because it offers the ability to specify both success and failure callbacks. Also, its ability to take a configuration object that can be defined separately makes it easier to write reusable code. For complete documentation of the configuration options, visit http://api.jquery.com/jQuery.ajax/.
// code to run regardless of success or failure complete : function(xhr, status) { alert('The request is complete!'); } });
Note
A note about the dataType setting: if the server sends back data that is in a different format than you specify, your code may fail, and the reason will not always be clear, because the HTTP response code will not show an error. When working with Ajax requests, make sure your server is sending back the data type you're asking for, and verify that the Content-type header is accurate for
51
Ajax
the data type. For example, for JSON data, the Content-type header should be application/ json.
$.ajax Options
There are many, many options for the $.ajax method, which is part of its power. For a complete list of options, visit http://api.jquery.com/jQuery.ajax/; here are several that you will use frequently: async Set to false if the request should be sent synchronously. Defaults to true. Note that if you set this option to false, your request will block execution of other code until the response is received. Whether to use a cached response if available. Defaults to true for all dataTypes except "script" and "jsonp". When set to false, the URL will simply have a cachebusting parameter appended to it. A callback function to run when the request is complete, regardless of success or failure. The function receives the raw request object and the text status of the request. The scope in which the callback function(s) should run (i.e. what this will mean inside the callback function(s)). By default, this inside the callback function(s) refers to the object originally passed to $.ajax. The data to be sent to the server. This can either be an object or a query string, such as foo=bar&baz=bim. The type of data you expect back from the server. By default, jQuery will look at the MIME type of the response if no dataType is specified. A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request. The callback name to send in a query string when making a JSONP request. Defaults to "callback". A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the dataType was JSON), as well as the text status of the request and the raw request object. The time in milliseconds to wait before considering the request a failure. Set to true to use the param serialization style in use prior to jQuery 1.4. For details, see http://api.jquery.com/jQuery.param/. The type of the request, "POST" or "GET". Defaults to "GET". Other request types, such as "PUT" and "DELETE" can be used, but they may not be supported by all browsers. The URL for the request.
cache
complete context
url
The url option is the only required property of the $.ajax configuration object; all other properties are optional.
Convenience Methods
If you don't need the extensive configurability of $.ajax, and you don't care about handling errors, the Ajax convenience functions provided by jQuery can be useful, terse ways to accomplish Ajax requests.
52
Ajax
These methods are just "wrappers" around the core $.ajax method, and simply pre-set some of the options on the $.ajax method. The convenience methods provided by jQuery are: $.get $.post $.getScript $.getJSON Perform a GET request to the provided URL. Perform a POST request to the provided URL. Add a script to the page. Perform a GET request, and expect JSON to be returned.
In each case, the methods take the following arguments, in order: url data The URL for the request. Required. The data to be sent to the server. Optional. This can either be an object or a query string, such as foo=bar&baz=bim.
Note
This option is not valid for $.getScript. success callback A callback function to run if the request succeeds. Optional. The function receives the response data (converted to a JavaScript object if the data type was JSON), as well as the text status of the request and the raw request object. The type of data you expect back from the server. Optional.
data type
Note
This option is only applicable for methods that don't already specify the data type in their name.
53
Ajax
$.fn.load
The $.fn.load method is unique among jQuerys Ajax methods in that it is called on a selection. The $.fn.load method fetches HTML from a URL, and uses the returned HTML to populate the selected element(s). In addition to providing a URL to the method, you can optionally provide a selector; jQuery will fetch only the matching content from the returned HTML.
54
Ajax
Ajax Events
Often, youll want to perform an operation whenever an Ajax requests starts or stops, such as showing or hiding a loading indicator. Rather than defining this behavior inside every Ajax request, you can bind Ajax events to elements just like you'd bind other events. For a complete list of Ajax events, visit http:// docs.jquery.com/Ajax_Events.
Exercises
Load External Content
Open the file /exercises/index.html in your browser. Use the file /exercises/js/ load.js. Your task is to load the content of a blog item when a user clicks on the title of the item. 1. Create a target div after the headline for each blog post and store a reference to it on the headline element using $.fn.data. 2. Bind a click event to the headline that will use the $.fn.load method to load the appropriate content from /exercises/data/blog.html into the target div. Don't forget to prevent the default action of the click event.
55
Ajax
Note that each blog headline in index.html includes a link to the post. You'll need to leverage the href of that link to get the proper content from blog.html. Once you have the href, here's one way to process it into an ID that you can use as a selector in $.fn.load: var href = 'blog.html#post1'; var tempArray = href.split('#'); var id = '#' + tempArray[1]; Remember to make liberal use of console.log to make sure you're on the right path!
56
Chapter 8. Plugins
What exactly is a plugin?
A jQuery plugin is simply a new method that we use to extend jQuery's prototype object. By extending the prototype object you enable all jQuery objects to inherit any methods that you add. As established, whenever you call jQuery() you're creating a new jQuery object, with all of jQuery's methods inherited. The idea of a plugin is to do something with a collection of elements. You could consider each method that comes with the jQuery core a plugin, like fadeOut or addClass. You can make your own plugins and use them privately in your code or you can release them into the wild. There are thousands of jQuery plugins available online. The barrier to creating a plugin of your own is so low that you'll want to do it straight away!
57
Plugins
$.fn.myNewPlugin = function() { alert(this === somejQueryObject); }; somejQueryObject.myNewPlugin(); // alerts 'true' Your typical jQuery object will contain references to any number of DOM elements, and that's why jQuery objects are often referred to as collections. So, to do something with a collection we need to loop through it, which is most easily achieved using jQuery's each() method: $.fn.myNewPlugin = function() { return this.each(function(){ }); }; jQuery's each() method, like most other jQuery methods, returns a jQuery object, thus enabling what we've all come to know and love as 'chaining' ($(...).css().attr()...). We wouldn't want to break this convention so we return the this object. Within this loop you can do whatever you want with each element. Here's an example of a small plugin using some of the techniques we've discussed: (function($){ $.fn.showLinkLocation = function() { return this.filter('a').each(function(){ $(this).append( ' (' + $(this).attr('href') + ')' ); }); }; }(jQuery)); // Usage example: $('a').showLinkLocation(); This handy plugin goes through all anchors in the collection and appends the href attribute in brackets. <!-- Before plugin is called: --> <a href="page.html">Foo</a> <!-- After plugin is called: --> <a href="page.html">Foo (page.html)</a> Our plugin can be optimised though: (function($){ $.fn.showLinkLocation = function() { return this.filter('a').append(function(){ return ' (' + this.href + ')'; }); }; }(jQuery)); We're using the append method's capability to accept a callback, and the return value of that callback will determine what is appended to each element in the collection. Notice also that we're not using the
58
Plugins
attr method to retrieve the href attribute, because the native DOM API gives us easy access with the aptly named href property. Here's another example of a plugin. This one doesn't require us to loop through every elememt with the each() method. Instead, we're simply going to delegate to other jQuery methods directly: (function($){ $.fn.fadeInAndAddClass = function(duration, className) { return this.fadeIn(duration, function(){ $(this).addClass(className); }); }; }(jQuery)); // Usage example: $('a').fadeInAndAddClass(400, 'finishedFading');
Writing Plugins
Sometimes you want to make a piece of functionality available throughout your code; for example, perhaps you want a single method you can call on a jQuery selection that performs a series of operations on the selection. In this case, you may want to write a plugin. Most plugins are simply methods created in the $.fn namespace. jQuery guarantees that a method called on a jQuery object will be able to access that jQuery object as this inside the method. In return, your plugin needs to guarantee that it returns the same object it received, unless explicitly documented otherwise. Here is an example of a simple plugin:
59
Plugins
60
Plugins
61
Plugins
Example 8.3. A simple, stateful plugin using the jQuery UI widget factory
$.widget("nmk.progressbar", { _create: function() { var progress = this.options.value + "%"; this.element .addClass("progressbar") .text(progress); } }); The name of the plugin must contain a namespace; in this case weve used the nmk namespace. There is a limitation that namespaces be exactly one level deep that is, we can't use a namespace like nmk.foo. We can also see that the widget factory has provided two properties for us. this.element is a jQuery object containing exactly one element. If our plugin is called on a jQuery object containing multiple elements, a separate plugin instance will be created for each element, and each instance will have its own this.element. The second property, this.options, is a hash containing key/value pairs for all of our plugins options. These options can be passed to our plugin as shown here.
Note
In our example we use the nmk namespace. The ui namespace is reserved for official jQuery UI plugins. When building your own plugins, you should create your own namespace. This makes it clear where the plugin came from and whether it is part of a larger collection.
62
Plugins
63
Plugins
64
Plugins
Note
Executing methods by passing the method name to the same jQuery function that was used to initialize the plugin may seem odd. This is done to prevent pollution of the jQuery namespace while maintaining the ability to chain method calls.
65
Plugins
Adding Callbacks
One of the easiest ways to make your plugin extensible is to add callbacks so users can react when the state of your plugin changes. We can see below how to add a callback to our progress bar to signify when the progress has reached 100%. The _trigger method takes three parameters: the name of the callback, a native event object that initiated the callback, and a hash of data relevant to the event. The callback name is the only required parameter, but the others can be very useful for users who want to implement custom functionality on top of your plugin. For example, if we were building a draggable plugin, we could pass the native mousemove event when triggering a drag callback; this would allow users to react to the drag based on the x/y coordinates provided by the event object.
66
Plugins
Cleaning Up
In some cases, it will make sense to allow users to apply and then later unapply your plugin. You can accomplish this via the destroy method. Within the destroy method, you should undo anything your
67
Plugins
plugin may have done during initialization or later use. The destroy method is automatically called if the element that your plugin instance is tied to is removed from the DOM, so this can be used for garbage collection as well. The default destroy method removes the link between the DOM element and the plugin instance, so its important to call the base function from your plugins destroy method.
Conclusion
The widget factory is only one way of creating stateful plugins. There are a few different models that can be used and each have their own advantages and disadvantages. The widget factory solves lots of common problems for you and can greatly improve productivity, it also greatly improves code reuse, making it a great fit for jQuery UI as well as many other stateful plugins.
Exercises
Make a Table Sortable
For this exercise, your task is to identify, download, and implement a table sorting plugin on the index.html page. When youre done, all columns in the table on the page should be sortable.
68
Plugins
69
71
72
} if ($eventhover.data('currently') != 'showing') { $eventhover.stop(); } if ($spans.data('currently') != 'showing') { $spans.stop(); } // GOOD!! var $elems = [$eventfade, $eventhover, $spans]; $.each($elems, function(i,elem) { if (elem.data('currently') != 'showing') { elem.stop(); } });
73
Optimize Selectors
Selector optimization is less important than it used to be, as more browser implement document.querySelectorAll() and the burden of selection shifts from jQuery to the browser. However, there are still some tips to keep in midn.
ID-Based Selectors
Beginning your selector with an ID is always best. // fast $('#container div.robotarm'); // super-fast $('#container').find('div.robotarm'); The $.fn.find approach is faster because the first selection is handled without going through the Sizzle selector engine ID-only selections are handled using document.getElementById(), which is extremely fast because it is native to the browser.
Specificity
Be specific on the right-hand side of your selector, and less specific on the left. // unoptimized $('div.data .gonzalez'); // optimized $('.data td.gonzalez'); Use tag.class if possible on your right-most selector, and just tag or just .class on the left. Avoid excessive specificity. $('.data table.attendees td.gonzalez'); // better: drop the middle if possible $('.data td.gonzalez'); A "flatter" DOM also helps improve selector performance, as the selector engine has fewer layers to traverse when looking for an element.
74
75
// regular $(elem).data(key,value);
$('li.cartitems').doOnce(function(){ // make it ajax! \o/ }); This guidance is especially applicable for jQuery UI widgets, which have a lot of overhead even when the selection doesn't contain elements.
Variable Definition
Variables can be defined in one statement instead of several. // old & busted var test = 1; var test2 = function() { ... }; var test3 = test2(test); // new hotness var test = 1, test2 = function() { ... }, test3 = test2(test);
76
In self-executing functions, variable definition can be skipped all together. (function(foo, bar) { ... })(1, 2);
Conditionals
// old way if (type == 'foo' || type == 'bar') { ... } // better if (/^(foo|bar)$/.test(type)) { ... } // object literal lookup if (({ foo : 1, bar : 1 })[type]) { ... }
77
Key Concepts
Before we jump into code organization patterns, it's important to understand some concepts that are common to all good code organization patterns. Your code should be divided into units of functionality modules, services, etc. Avoid the temptation to have all of your code in one huge $(document).ready() block. This concept, loosely, is known as encapsulation. Don't repeat yourself. Identify similarities among pieces of functionality, and use inheritance techniques to avoid repetitive code. Despite jQuery's DOM-centric nature, JavaScript applications are not all about the DOM. Remember that not all pieces of functionality need to or should have a DOM representation. Units of functionality should be loosely coupled [http://en.wikipedia.org/wiki/Loose_coupling] a unit of functionality should be able to exist on its own, and communication between units should be handled via a messaging system such as custom events or pub/sub. Stay away from direct communication between units of functionality whenever possible. The concept of loose coupling can be especially troublesome to developers making their first foray into complex applications, so be mindful of this as you're getting started.
Encapsulation
The first step to code organization is separating pieces of your application into distinct pieces; sometimes, even just this effort is sufficient to lend
78
Code Organization
79
var myFeature = { init : function(settings) { myFeature.config Code = { Organization $items : $('#myFeature li'), $container : $('<div class="container"></div>'), '/foo.php?item=' Example 10.2.urlBase Using an: object literal for a jQuery feature }; // allow overriding the default config $.extend(myFeature.config, settings); myFeature.setup(); }, setup : function() { myFeature.config.$items .each(myFeature.createContainer) .click(myFeature.showItem); }, createContainer : function() { var $i = $(this), $c = myFeature.config.$container.clone() .appendTo($i); $i.data('container', $c); }, buildUrl : function() { return myFeature.config.urlBase + myFeature.$currentItem.attr('id'); }, showItem : function() { var myFeature.$currentItem = $(this); myFeature.getContent(myFeature.showContent); }, getContent : function(callback) { var url = myFeature.buildUrl(); myFeature.$currentItem .data('container').load(url, callback); }, showContent : function() { myFeature.$currentItem .data('container').show(); myFeature.hideContent(); }, hideContent : function() { myFeature.$currentItem.siblings() .each(function() { $(this).data('container').hide(); }); } }; $(document).ready(myFeature.init);
80
Code Organization
The first thing you'll notice is that this approach is obviously far longer than the original again, if this were the extent of our application, using an object literal would likely be overkill. Assuming it's not the extent of our application, though, we've gained several things: We've broken our feature up into tiny methods. In the future, if we want to change how content is shown, it's clear where to change it. In the original code, this step is much harder to locate. We've eliminated the use of anonymous functions. We've moved configuration options out of the body of the code and put them in a central location. We've eliminated the constraints of the chain, making the code easier to refactor, remix, and rearrange. For non-trivial features, object literals are a clear improvement over a long stretch of code stuffed in a $(document).ready() block, as they get us thinking about the pieces of our functionality. However, they aren't a whole lot more advanced than simply having a bunch of function declarations inside of that $(document).ready() block.
81
Code Organization
In the example above, we self-execute an anonymous function that returns an object. Inside of the function, we define some variables. Because the variables are defined inside of the function, we don't have access to them outside of the function unless we put them in the return object. This means that no code outside of the function has access to the privateThing variable or to the changePrivateThing function. However, sayPrivateThing does have access to privateThing and changePrivateThing, because both were defined in the same scope as sayPrivateThing. This pattern is powerful because, as you can gather from the variable names, it can give you private variables and functions while exposing a limited API consisting of the returned object's properties and methods. Below is a revised version of the previous example, showing how we could create the same feature using the module pattern while only exposing one public method of the module, showItemByIndex().
82
Code Organization
$(document).ready(function() { Example 10.4. Using the module pattern for var feature = (function() {
a jQuery feature
var $items = $('#myFeature li'), $container = $('<div class="container"></div>'), $currentItem, urlBase = '/foo.php?item=', createContainer = function() { var $i = $(this), $c = $container.clone().appendTo($i); $i.data('container', $c); }, buildUrl = function() { return urlBase + $currentItem.attr('id'); }, showItem = function() { var $currentItem = $(this); getContent(showContent); }, showItemByIndex = function(idx) { $.proxy(showItem, $items.get(idx)); }, getContent = function(callback) { $currentItem.data('container').load(buildUrl(), callback); }, showContent = function() { $currentItem.data('container').show(); hideContent(); }, hideContent = function() { $currentItem.siblings() .each(function() { $(this).data('container').hide(); }); }; $items .each(createContainer) .click(showItem); return { showItemByIndex : showItemByIndex }; })(); feature.showItemByIndex(0); });
83
Code Organization
Managing Dependencies
Note
This section is based heavily on the excellent RequireJS documentation at http://requirejs.org/ docs/jquery.html, and is used with the permission of RequireJS author James Burke. When a project reaches a certain size, managing the script modules for a project starts to get tricky. You need to be sure to sequence the scripts in the right order, and you need to start seriously thinking about combining scripts together into a bundle for deployment, so that only one or a very small number of requests are made to load the scripts. You may also want to load code on the fly, after page load. RequireJS, a dependency management tool by James Burke, can help you manage the script modules, load them in the right order, and make it easy to combine the scripts later via the RequireJS optimization tool without needing to change your markup. It also gives you an easy way to load scripts after the page has loaded, allowing you to spread out the download size over time. RequireJS has a module system that lets you define well-scoped modules, but you do not have to follow that system to get the benefits of dependency management and build-time optimizations. Over time, if you start to create more modular code that needs to be reused in a few places, the module format for RequireJS makes it easy to write encapsulated code that can be loaded on the fly. It can grow with you, particularly if you want to incorporate internationalization (i18n) string bundles, to localize your project for different languages, or load some HTML strings and make sure those strings are available before executing code, or even use JSONP services as dependencies.
Getting RequireJS
The easiest way to use RequireJS with jQuery is to download a build of jQuery that has RequireJS built in [http://requirejs.org/docs/download.html]. This build excludes portions of RequireJS that duplicate jQuery functionality. You may also find it useful to download a sample jQuery project that uses RequireJS [http:// requirejs.org/docs/release/0.11.0/jquery-require-sample.zip].
84
Code Organization
The call to require(["app"]) tells RequireJS to load the scripts/app.js file. RequireJS will load any dependency that is passed to require() without a .js extension from the same directory as require-jquery.js, though this can be configured to behave differently. If you feel more comfortable specifying the whole path, you can also do the following: <script>require(["scripts/app.js"]);</script> What is in app.js? Another call to require.js to load all the scripts you need and any init work you want to do for the page. This example app.js script loads two plugins, jquery.alpha.js and jquery.beta.js (not the names of real plugins, just an example). The plugins should be in the same directory as require-jquery.js:
85
Code Organization
86
Code Organization
87
Code Organization
Exercises
Create a Portlet Module
Open the file /exercises/portlets.html in your browser. Use the file /exercises/js/ portlets.js. Your task is to create a portlet creation function that uses the module pattern, such that the following code will work: var myPortlet = Portlet({ title : 'Curry', source : 'data/html/curry.html', initialState : 'open' // or 'closed' }); myPortlet.$element.appendTo('body'); Each portlet should be a div with a title, a content area, a button to open/close the portlet, a button to remove the portlet, and a button to refresh the portlet. The portlet returned by the Portlet function should have the following public API: myPortlet.open(); // force open state myPortlet.close(); // force close state myPortlet.toggle(); // toggle open/close state myPortlet.refresh(); // refresh the content myPortlet.destroy(); // remove the portlet from the page myPortlet.setSource('data/html/onions.html'); // change the source
88
89
Custom Events
} }); $('.switch, .clapper').click(function() { $(this).parent().find('.lightbulb').trigger('changeState'); }); This last bit of code is not that exciting, but something important has happened: weve moved the behavior of the lightbulb to the lightbulb, and away from the switches and the clapper. Lets make our example a little more interesting. Well add another room to our house, along with a master switch, as shown here: <div class="room" id="kitchen"> <div class="lightbulb on"></div> <div class="switch"></div> <div class="switch"></div> <div class="clapper"></div> </div> <div class="room" id="bedroom"> <div class="lightbulb on"></div> <div class="switch"></div> <div class="switch"></div> <div class="clapper"></div> </div> <div id="master_switch"></div> If there are any lights on in the house, we want the master switch to turn all the lights off; otherwise, we want it to turn all lights on. To accomplish this, well add two more custom events to the lightbulbs: turnOn and turnOff. Well make use of them in the changeState custom event, and use some logic to decide which one the master switch should trigger: $('.lightbulb') .bind('changeState', function(e) { var $light = $(this); if ($light.hasClass('on')) { $light.trigger('turnOff'); } else { $light.trigger('turnOn'); } }) .bind('turnOn', function(e) { $(this).removeClass('off').addClass('on'); }) .bind('turnOff', function(e) { $(this).removeClass('off').addClass('on'); }); $('.switch, .clapper').click(function() { $(this).parent().find('.lightbulb').trigger('changeState'); }); $('#master_switch').click(function() { if ($('.lightbulb.on').length) { $('.lightbulb').trigger('turnOff');
90
Custom Events
} else { $('.lightbulb').trigger('turnOn'); } }); Note how the behavior of the master switch is attached to the master switch; the behavior of a lightbulb belongs to the lightbulbs.
Note
If youre accustomed to object-oriented programming, you may find it useful to think of custom events as methods of objects. Loosely speaking, the object to which the method belongs is created via the jQuery selector. Binding the changeState custom event to all $(.light) elements is akin to having a class called Light with a method of changeState, and then instantiating new Light objects for each element with a classname of light. Recap: $.fn.bind and $.fn.trigger In the world of custom events, there are two important jQuery methods: $.fn.bind and $.fn.trigger. In the Events chapter, we saw how to use these methods for working with user events; for this chapter, it's important to remember two things: The $.fn.bind method takes an event type and an event handling function as arguments. Optionally, it can also receive event-related data as its second argument, pushing the event handling function to the third argument. Any data that is passed will be available to the event handling function in the data property of the event object. The event handling function always receives the event object as its first argument. The $.fn.trigger method takes an event type as its argument. Optionally, it can also take an array of values. These values will be passed to the event handling function as arguments after the event object. Here is an example of the usage of $.fn.bind and $.fn.trigger that uses custom data in both cases: $(document).bind('myCustomEvent', { foo : 'bar' }, function(e, arg1, arg2) { console.log(e.data.foo); // 'bar' console.log(arg1); // 'bim' console.log(arg2); // 'baz' }); $(document).trigger('myCustomEvent', [ 'bim', 'baz' ]);
A Sample Application
To demonstrate the power of custom events, were going to create a simple tool for searching Twitter. The tool will offer several ways for a user to add search terms to the display: by entering a search term in a text box, by entering multiple search terms in the URL, and by querying Twitter for trending terms. The results for each term will be shown in a results container; these containers will be able to be expanded, collapsed, refreshed, and removed, either individually or all at once. When were done, it will look like this:
91
Custom Events
92
Custom Events
The Setup
Well start with some basic HTML: <h1>Twitter Search</h1> <input type="button" id="get_trends" value="Load Trending Terms" /> <form> <input type="text" class="input_text" id="search_term" /> <input type="submit" class="input_submit" value="Add Search Term" /> </form> <div id="twitter"> <div class="template results"> <h2>Search Results for <span class="search_term"></span></h2> </div> </div> This gives us a container (#twitter) for our widget, a template for our results containers (hidden via CSS), and a simple form where users can input a search term. (For the sake of simplicity, were going to assume that our application is JavaScript-only and that our users will always have CSS.) There are two types of objects well want to act on: the results containers, and the Twitter container. The results containers are the heart of the application. Well create a plugin that will prepare each results container once its added to the Twitter container. Among other things, it will bind the custom events for each container and add the action buttons at the top right of each container. Each results container will have the following custom events: refresh populate remove Mark the container as being in the refreshing state, and fire the request to fetch the data for the search term. Receive the returned JSON data and use it to populate the container. Remove the container from the page after the user verifies the request to do so. Verification can be bypassed by passing true as the second argument to the event handler. The remove event also removes the term associated with the results container from the global object containing the search terms. Add a class of collapsed to the container, which will hide the results via CSS. It will also turn the containers Collapse button into an Expand button. Remove the collapsed class from the container. It will also turn the containers Expand button into a Collapse button.
collapse expand
The plugin is also responsible for adding the action buttons to the container. It binds a click event to each actions list item, and uses the list items class to determine which custom event will be triggered on the corresponding results container. $.fn.twitterResult = function(settings) { return $(this).each(function() { var $results = $(this),
93
Custom Events
$actions = $.fn.twitterResult.actions = $.fn.twitterResult.actions || $.fn.twitterResult.createActions(), $a = $actions.clone().prependTo($results), term = settings.term; $results.find('span.search_term').text(term); $.each( ['refresh', 'populate', 'remove', 'collapse', 'expand'], function(i, ev) { $results.bind( ev, { term : term }, $.fn.twitterResult.events[ev] ); } ); // use the class of each action to figure out // which event it will trigger on the results panel $a.find('li').click(function() { // pass the li that was clicked to the function // so it can be manipulated if needed $results.trigger($(this).attr('class'), [ $(this) ]); }); }); }; $.fn.twitterResult.createActions = function() { return $('<ul class="actions" />').append( '<li class="refresh">Refresh</li>' + '<li class="remove">Remove</li>' + '<li class="collapse">Collapse</li>' ); }; $.fn.twitterResult.events = { refresh : function(e) { // indicate that the results are refreshing var $this = $(this).addClass('refreshing'); $this.find('p.tweet').remove(); $results.append('<p class="loading">Loading ...</p>'); // get the twitter data using jsonp $.getJSON( 'http://search.twitter.com/search.json?q=' + escape(e.data.term) + '&rpp=5&callback=?', function(json) { $this.trigger('populate', [ json ]); } ); },
94
Custom Events
populate : function(e, json) { var results = json.results; var $this = $(this); $this.find('p.loading').remove(); $.each(results, function(i,result) { var tweet = '<p class="tweet">' + '<a href="http://twitter.com/' + result.from_user + '">' + result.from_user + '</a>: ' + result.text + ' <span class="date">' + result.created_at + '</span>' + '</p>'; $this.append(tweet); }); // indicate that the results // are done refreshing $this.removeClass('refreshing'); }, remove : function(e, force) { if ( !force && !confirm('Remove panel for term ' + e.data.term + '?') ) { return; } $(this).remove(); // indicate that we no longer // have a panel for the term search_terms[e.data.term] = 0; }, collapse : function(e) { $(this).find('li.collapse').removeClass('collapse') .addClass('expand').text('Expand'); $(this).addClass('collapsed'); }, expand : function(e) { $(this).find('li.expand').removeClass('expand') .addClass('collapse').text('Collapse'); $(this).removeClass('collapsed'); }
95
Custom Events
}; The Twitter container itself will have just two custom events: getResults Receives a search term and checks to determine whether theres already a results container for the term; if not, adds a results container using the results template, set up the results container using the $.fn.twitterResult plugin discussed above, and then triggers the refresh event on the results container in order to actually load the results. Finally, it will store the search term so the application knows not to re-fetch the term. Queries Twitter for the top 10 trending terms, then iterates over them and triggers the getResults event for each of them, thereby adding a results container for each term.
getTrends
Here's how the Twitter container bindings look: $('#twitter') .bind('getResults', function(e, term) { // make sure we don't have a box for this term already if (!search_terms[term]) { var $this = $(this); var $template = $this.find('div.template'); // make a copy of the template div // and insert it as the first results box $results = $template.clone(). removeClass('template'). insertBefore($this.find('div:first')). twitterResult({ 'term' : term }); // load the content using the "refresh" // custom event that we bound to the results container $results.trigger('refresh'); search_terms[term] = 1;
} }) .bind('getTrends', function(e) { var $this = $(this); $.getJSON('http://search.twitter.com/trends.json?callback=?', function(json var trends = json.trends; $.each(trends, function(i, trend) { $this.trigger('getResults', [ trend.name ]); }); }); }); So far, weve written a lot of code that does approximately nothing, but thats OK. By specifying all the behaviors that we want our core objects to have, weve created a solid framework for rapidly building out the interface. Lets start by hooking up our text input and the Load Trending Terms button. For the text input, well capture the term that was entered in the input and pass it as we trigger the Twitter containers getResults event. Clicking the Load Trending Terms will trigger the Twitter containers getTrends event:
96
Custom Events
$('form').submit(function(e) { e.preventDefault(); var term = $('#search_term').val(); $('#twitter').trigger('getResults', [ term ]); }); $('#get_trends').click(function() { $('#twitter').trigger('getTrends'); }); By adding a few buttons with the appropriate IDs, we can make it possible to remove, collapse, expand, and refresh all results containers at once, as shown below. For the remove button, note how were passing a value of true to the event handler as its second argument, telling the event handler that we dont want to verify the removal of individual containers. $.each(['refresh', 'expand', 'collapse'], function(i, ev) { $('#' + ev).click(function(e) { $('#twitter div.results').trigger(ev); }); }); $('#remove').click(function(e) { if (confirm('Remove all results?')) { $('#twitter div.results').trigger('remove', [ true ]); } });
Conclusion
Custom events offer a new way of thinking about your code: they put the emphasis on the target of a behavior, not on the element that triggers it. If you take the time at the outset to spell out the pieces of your application, as well as the behaviors those pieces need to exhibit, custom events can provide a powerful way for you to talk to those pieces, either one at a time or en masse. Once the behaviors of a piece have been described, it becomes trivial to trigger those behaviors from anywhere, allowing for rapid creation of and experimentation with interface options. Finally, custom events can enhance code readability and maintainability, by making clear the relationship between an element and its behaviors. You can see the full application at demos/custom-events.html and demos/js/customevents.js in the sample code.
97