# JQuery: Novice to Ninja- P28

Chia sẻ: Cong Thanh | Ngày: | Loại File: PDF | Số trang:15

0
53
lượt xem
4

## JQuery: Novice to Ninja- P28

Mô tả tài liệu

JQuery: Novice to Ninja- P28:No matter what kind of ninja you are—a cooking ninja, a corporate lawyer ninja, or an actual ninja ninja—virtuosity lies in first mastering the basic tools of the trade. Once conquered, it’s then up to the full-fledged ninja to apply that knowledge in creative and inventive ways.

Chủ đề:

Bình luận(0)

Lưu

## Nội dung Text: JQuery: Novice to Ninja- P28

1. 382 jQuery: Novice to Ninja When we “add” a string and a number using the + operator, JavaScript assumes we’re trying to concatenate the two, so it creates a new string. It would appear to change the number’s variable type to string. When we use the multiplication oper­ ator (*) though, JavaScript assumes that we want to treat the two variables as num­ bers. The variable itself remains the same throughout, it’s just treated differently. We can always explicitly tell JavaScript how we intend to treat a variable, but if we don’t, we need to understand just what JavaScript is doing for us. Here’s another example: alert(a + c);// alerts 22 alert(a + parseInt(c));// alerts 4 Licensed to JamesCarlson@aol.com Equality Operators The equal sign (=) and its related operators can also provide a trap for young players. And where it was once just a little odd, it became even more so in JavaScript 1.3. The first trick is that the equal sign has a different meaning than what you remember from your school mathematics classes: var a = 2; var b = "2"; A single equal sign is an assignment operator, and is used to assign values to vari­ ables. We all knew what it did, but now we know what it’s called: var c = (a == b); Two = signs together, ==, is known as the equality operator, and establishes a Boolean value. In our example, the variable c will have a value of true, as JavaScript compares the values before and after the equality operator, and considers them to be equal. Using the equality operator, JavaScript pays no heed to the variable’s type, and attempts to coerce the values to assess them. Switch out the first equal sign for an exclamation mark, and you have yourself an inequality operator (!=). This operator will return false if the variables are equal, or true if they aren’t:
2. Appendix B: JavaScript Tidbits 383 var d = (a != b); The variable d will now have a value of false, since a and b are equal. It may be a little complex, but at least it’s consistent. In JavaScript 1.3, the situation became less simple still, with the introduction of one further operator: the strict equality operator, shown as ===. var e = (a === b); The strict equality operator differs from the equality operator, in that it pays strict attention to type as well as value when it assigns its Boolean. In the above case, d Licensed to JamesCarlson@aol.com is set to false: while a and b both have a value of 2, they have different types. And as you might have guessed, where the inequality operator was paired with the equality operator, the strict equality operator has a corresponding strict inequality operator: var f = (a !== b); In this case the variable f will return true, as we know the two compared variables are of different types, though similar values. Suffice it to say that some equal signs are more equal then others! Truthiness and Falsiness JavaScript’s Boolean type has two possible values—true and false: var jQueryIsFun = true; var javaScriptIsJava = false; But we know that JavaScript likes to be trickier than this. In reality, there are a multitude of ways that variables can evaluate to true or false. These values are referred to as being truthy or falsy. So when we write if(variable) { … }, variable need not be a Boolean value: the code between the brackets will run if variable contains the number 5, or the string "Hello World!", or even an empty array. Any
3. 384 jQuery: Novice to Ninja value that acts as though it were the Boolean value true in this type of context is called truthy, and any value that acts like false is called falsy. JavaScript treats all these values as truthy: ■ true ■ 1 (because it’s a non-zero number) ■ "0" (because it’s a non-empty string) ■ "false" (because it’s a non-empty string) ■ function() {} (any function) ■ {} (any object) ■ [] (any array) Licensed to JamesCarlson@aol.com And these values are falsy: ■ false ■ 0 (the number zero) ■ "" (an empty string) ■ null ■ undefined ■ NaN (a special number value meaning Not a Number) These values can be combined with the logical NOT operator to great effect. A single exclamation mark is used: var a = 0; var b = 1; if (!b) { // do something } else if (!a) { // do something else } The logical NOT operator returns true if the value of the variable is false and, conversely, it will return false if the value is true. In the example above, b is truthy and so !b returns false, and a is falsy so !a returns true—so the code in the else if block would execute.
4. Appendix B: JavaScript Tidbits 385 It’s important to remember that while a value may be == true, it may only be truthy, and not strictly true: var a = true; var b = 1; alert(a == b);// alerts true alert(a === b);// alerts false alert(a != b); // alerts false alert(a !== b); // alerts true If you have the option, always elect to use the Boolean values of true and false. If there’s one thing that’s undoubtedly true, it’s that hunting down a truthy or falsy Licensed to JamesCarlson@aol.com logic error is truly painstaking!
6. Appendix C: Plugin Helpers There are a few jQuery properties and actions that, although applying to any jQuery selection, are particularly useful for plugin development. The reason they’re hidden away in this appendix is that they’re uncommonly used. Despite this, they’re quite powerful, and you should familiarize yourself with them if you intend to spend time developing plugins. Selector and Context The first ones we’ll look at are the selector and context properties. These work Licensed to JamesCarlson@aol.com together to show you what jQuery thinks it’s working on. The selector property returns a string value of the current jQuery selector string: so the command $('p:first').selector will return the string "p:first". This is useful in your plugins if you need to know what the user originally selected. You might think that the optional second parameter to the jQuery selector, which is called context, is what you’d obtain with the context property—but it’s a bit trickier than that. In fact, if you supply context as a string, it’s converted internally to a regular jQuery statement, which will actually affect the selector property: var selector =$('p:first', '#content').selector var context = $('p:first', '#content').context In the above example, the selector resolves to "#content p:first" and the context resolves to Document (the context that all your selectors will default to). The context property is only modified if you supply an actual DOM node to it: var domContext =$('#content')[0]; // Get the DOM element var selector = $('p:first', domContext).selector; var context =$('p:first', domContext).context; In this case, the selector will be reported as "p:first", and the context will be the DOM element itself (for this example, it’s the element).
8. Appendix C: Plugin Helpers 389 $('#categories li:first') .surrounds() .css('color', 'red') .end() .css('color', 'blue'); This will select the two elements that surround the first list item, then color them red. Because we’ve used pushStack, the jQuery chain remains intact; we can then use the end command to move back to the original selection (the first list item), and color it blue. You can use pushStack anytime you want to manipulate the chain like this. Licensed to JamesCarlson@aol.com The last trick we’ll look at in regard to the jQuery internal chain is the ability to access other steps in the chain. As you might remember, the end action takes you back up one level to the last command that modified the jQuery selection. If you look into the jQuery core, you’ll see that end is implemented using the prevObject property. Inside your plugin you can gain access to the previous jQuery object by using this.prevObject. If the previous object has a previous object, you can access this too! Minification You know there are two versions of jQuery, jQuery UI, and many jQuery plugins: an uncompressed version and a minified version. Why is this so? Regardless of which one you choose, when you add them to your page you gain access to all the features of jQuery (or the plugin in question). The difference is, of course, that the file size of the “.min” version is markedly smaller. With jQuery 1.3.2 coming in at around 118KB and the minified version at 55.9KB, you save over half the file size in bandwidth. And if the file is half as big, it’s delivered twice as fast. Faster downloads mean faster pageloads, so you may be wondering how to enjoy the benefit of minified files with your own script files, and—more importantly—your plugins. There are a number of utilities you can use to compress your files, so we’ll go over a few of the more commonly used ones. 9. 390 jQuery: Novice to Ninja Douglas Crockford’s JSMin1 was first released in December of 2003, and currently comes in both the original executable version (along with the C source code), as well as a host of other language options: C#, Java, JavaScript, Perl, PHP, Python, OCaml, and Ruby. Of a similar pedigree, but slightly more accessible to use, is Dean Edwards’ Packer.2 It’s primarily accessed via a web page interface, but it also has .NET, Perl, and PHP applications available for download. Both solutions work by eliminating whitespace—line breaks and extraneous spaces—and by shortening variable and function names. The code becomes obfus­ cated by human standards, but the browser’s JavaScript engine has no trouble inter­ Licensed to JamesCarlson@aol.com preting the code output. So, for example, this human-readable code:$growl.animate({ border: "none", height: 0, marginBottom: 0, marginTop: "-6px", opacity : 0, paddingBottom: 0, paddingTop: 0, queue: false } … would be shortened to this: $growl.animate({border:"none",height:0,marginBottom:0,marginTop: ➥"-6px",opacity :0,paddingBottom:0,paddingTop:0,queue:false} The second statement has the whitespace removed, and you can already see that it’s taking up less space to achieve the same results. You can also see how it’s become more difficult to read. Multiply this effect by the 4,377 lines in the jQuery source, and you can imagine how difficult it would be to make any sense of it. And that’s without altering any names. 1 http://www.crockford.com/javascript/jsmin.html 2 http://dean.edwards.name/packer/ 10. Appendix C: Plugin Helpers 391 Of these two methods, Packer is arguably the more extensive, not only removing whitespace but also converting names to base 62. Its compressed footprint can therefore be smaller, yet this mightn’t necessarily result in the fastest solution, as it means the minified code must be “unpacked” when delivered to the browser. Edwards’ most recent modifications have seen some astounding increases in unpack­ ing speeds, but this overhead should be considered when adopting a final solution. Two other popular options for minifying your JavaScript are Yahoo’s YUI Com­ pressor3 and Google’s Closure Compiler.4 The teams behind all four methods—well, three, as Crockford is fairly much sorted with JSMin—are continually refining their solutions, and are responsive to industry Licensed to JamesCarlson@aol.com and community feedback. 3 http://developer.yahoo.com/yui/compressor/ 4 http://code.google.com/closure/compiler/ 11. Licensed to JamesCarlson@aol.com 12. Index ' (quotes), 28, 282 Symbols + arithmetic operator, 158 !== (strict inequality) operator, 383 ++ increment operator, 115, 222 # (hash symbol) id name, 21 . (dot) notation, 130$ (dollar sign) . (period), namespaces, 356 JavaScript variable name, 12 1-up notifications, 287–290 uniqueness of, 362 :checked filter, 233 $(document).ready() function, 18, 27 :eq filter, 125$. prefixed functions, 345 :eq selector attribute, 106 Licensed to JamesCarlson@aol.com $.active property (Ajax), 215 :even filter, 24$.ajax method :hover pseudo selector, 144 about, 202 :not selector, 151 callbacks and functions, 376 :selected filter, 233 flags, 373 = (assignment) operator, 382 options, 373–376 == (equality) operator, 382 settings, 374 === (strict quality) operator, 383 $.ajaxSetup action, 203$.browser function, 191 A $.browser.version function, 191 “above the fold”, defined, 348$.datepicker.setDefaults method, 260 accessibility, semi-transparent controls, $.each function, 202, 210 167$.extend function, 338 action $.fn.extend() method, 343 attr, 95$.get request, 205 actions $.getJSON function, 200, 226$.ajaxSetup action, 203 $.getScript function, 204 about, 12, 33$.inArray, 296 attr action, 304 $.map, 296 bind, 247$.post method, 228 chaining actions, 62 $.post request, 205 closest action, 287$.support method, 376 data action, 125, 126, 366 $.trim method, 347 default event actions, 140 % (percent symbol) modulus, 114 delay, 63 && and operator, 177 disableSelection action, 273 13. 394 enableSelection action, 273 ajaxComplete global events, 207 filter action, 304 ajaxError global events, 206 hide action, 32 ajaxSend global events, 207 html action, 41 ajaxStart global events, 207 is action, 35 ajaxStart method, 215 live action, 280 ajaxStop global events, 207 one action, 336 ajaxStop method, 215 parent actions, 121 ajaxSuccess global events, 207 pushStack action, 388 aliases remove action, 40 event parameters, 133 text action, 41, 305 using, 11 add method, 151 and (&&) operator, 177 Licensed to JamesCarlson@aol.com addClass function, 30 animated navigation, 64–69 adding animating, 51–72 callbacks to plugins, 339–342 animated navigation, 64–69 classes, 30 animation queue, 61 elements, 37–40 chaining actions, 62 options to plugins, 337 color, 53 Ajax (Asynchronous JavaScript and content panes, 58 XML), 193–207 CSS properties, 52$.ajax method, 202 easing, 54–58 about, 193 effects, 42 client-side Twitter searcher, 201 jQuery UI library, 69 events, 206 “puff” effect example, 268 fetching data with $.getJSON, 200 queuing and dequeuing, 363 GET and POST requests, 205 animation queue, 61 Hijax, 194 anonymous functions, 44 image gallery, 207–223 API (Application Programming Inter­ image tagging, 223–229 face), fetching data, 200 live function and die events, 198 appending lists, 315 loading, 198 arithmetic (+) operator, 158 loading content, 159 assignment (=) operator, 382 loading external scripts, 204 async Ajax option, 373 loading remote HTML, 194 Asynchronous JavaScript and XML (see picking HTML with selectors, 196 Ajax) requests, 215 attr action, 95, 304 settings, 203 attribute selectors, 75 14. 395 attributes Cascading Style Sheets (see CSS) :eq selector attribute, 106 CDN (Content Delivery Network), 9 title attribute (links), 169 chaining autocomplete, forms, 248 actions, 62 axis option (draggable interaction help­ empty or remove commands, 246 er), 267 changeBubbles property ($.support method), 377 B checkboxes beforeClose events, 283 forms, 242 beforeSend local events, 207, 212 selecting columns of, 329 bgiframe plugin, 283 selecting rows with, 329–331 shift-selecting checkboxes, 330 Licensed to JamesCarlson@aol.com bind action, 247 bind method, 360 child elements, defined, 13 binding multiple events, 247 child selectors, styling top-level links, binding, iPhones, 357 138 Boolean type, JavaScript, 383 classes boxModel property ($.support method), decorating, 29 377 toggleClass method, 309 browser sniffing, 191 clearInterval command, 109 browsers clearTimeout command, 109 compatibility, 2 click event handler, 33, 310 drag and drop, 265 click method, 355 bubbles, events, 139 client-side form validation versus server- side form validation, 232 C client-side templating, 188–191 cache Ajax option, 373 client-side Twitter searcher, 201 calculated style, 26 clone method, 190 call method (JavaScript), 341 closest action, 287 callback functions coding practices, 182–187$.ajax method, 376 comments, 182 adding to plugins, 339–342 error handling, 223 effects, 44 JavaScript, 182–192 number of, 46 map objects, 183 passing, 290 namespaces, 184 running, 340 scope, 186 success callback, 209 color animation, 53 ColorBox plugin, 98
15. 396 columns, selecting columns of check- date picker, 257–260 boxes, 329 drag and drop, 264–271 commands navigation, 136 (see also actions; callback functions; navigation controls in plugins, 321 functions; methods; statements; progress bar, 274 utilities) sliders, 260–264 clearInterval command, 109 sortable behavior, 271 construction of, 12 tabs, 161 empty command, 246 create method, 254 filter command, 151 creating (see adding) remove command, 246 cropping images with Jcrop, 101–104 comments, in code, 182 cross-fading JavaScript timers, 111–115 Licensed to JamesCarlson@aol.com compatibility, browsers, 2 cross-fading multiple images, 109 complete callback handler, 340 cross-fading slideshows, 104–119 complete local events, 207 JavaScript timers, 106–115 components, making themeable, 369 rollover fader, 105 compressed versus uncompressed jQuery with plugins, 115–119 downloads, 11 CSS (Cascading Style Sheets) conditional assignment, modulus, 254 animating CSS properties, 52 conflicts, avoiding, 362 child selectors, 138 console.log, troubleshooting lightboxes, CSS3 selectors, 3 96 IE6, 179 content layout switcher, 80 loading via Ajax, 159 properties, 25–28 modifying, 41 tabs, 157 updating, 188 z-index property, 112 Content Delivery Network (CDN), 9 cssFloat property ($.support method), content panes, animating, 58 377 contents() function, 248 Cycle plugin, 117 contentType Ajax setting, 374 context Ajax setting, 218–219, 374 D context, plugins and selectors, 387 data controls accessing with selectables, 297 (see also dialogs; forms; notifications) fetching with$.getJSON, 200 accessibility and semi-transparent sending form data, 227–229 controls, 167 data action, 125, 126, 366 checkboxes, 242 data Ajax setting, 374