Yearning jQuery
Hi, I’m Remy / @remScreencast @jqueryfordesigners.comQuestions: interrupt me& ask!
1. Build without jQuery.2. Design the start and end of your  effects without jQuery.3. Add jQuery a little at a time.
(a lot of it is...)        "all about CSS"                      Me, to many a colleague
@rem     Remy SharpDear designer/dev: if youre usingJavaScript to do a job that CSS could havedone perfectly well, youve l...
@rem     Remy SharpThe day someone loses business becausean animated transition wasnt used toreveal a screenshot: Ill sell...
What were covering• Getting friendly with the $• DOM navigation & manipulation• Events• Ajax• Tips
APIs         Blogs, tutorials, screencasts, docs.jquery.com                    plugins, development sprints  api.jquery.co...
jsbin.com
Bling Function
It means no more of thisvar tables = document.getElementsByTagName(table);for (var t = 0; t < tables.length; t++) {!   var...
jQuery simplifies$(table tr:nth-child(odd)).addClass(odd);
jQuery simplifiesjQuery function$(table tr:nth-child(odd)).addClass(odd);
jQuery simplifiesjQuery function$(table tr:nth-child(odd)).addClass(odd);             CSS expression
jQuery simplifiesjQuery function            jQuery method$(table tr:nth-child(odd)).addClass(odd);             CSS express...
jQuery simplifies$(table tr:nth-child(odd)).addClass(odd);
$(just css)
Tools of the Trade
• Firefox: Firebug (& FireQuery*)• Safari & Chrome: Web Inspector• Opera: DragonFly• IE: Web Developer Toolbar
Tip      $.fn.jquery        (little q)
Lets play.http://twitter.com
jQuery on every site?        No Problem.
http://bit.ly/9JAcCj
Lets play.
Installing jQuery
dev or min?
Hosting options  • Host it yourself (good for offline    dev)  • Hotlink it:   • Media Temple   • Microsoft   • Google (my...
CDN FTW
Tip: keep a copy on  your machine
Where does it all go?
• jQuery first• Then jQuery plugins• Then your code
• Other JavaScript libraries• jQuery last library• Then jQuery plugin scripts• Then your code
<html><head>  <styles>  <!-- make me beautiful -->  </styles></head><body>  <content>  <!-- make me learned -->  </content...
<html>                 <head>                   <styles> Styles first      <!-- make me beautiful -->lets the page     </s...
<html>                 <head>                   <styles>                   <!-- make me beautiful --> Then your         </...
<html>               <head>                 <styles>                 <!-- make me beautiful -->                 </styles> ...
$(document).ready(function () {      // < YOU >});
$(document).ready(function () {      // < YOU >});
$(function () {      // < YOU >});
TipjQuery(function ($) {      // < YOU >});       Useful when giving code to a client
<!DOCTYPE html><html lang="en"><head><meta charset=utf-8 /><title>My first jQuery page</title></head><body><h1>Remy woz er...
Is it jQuery or $?
Its both.
$(table tr:nth-child(odd))
jQuery(table tr:nth-child(odd))
$(table tr:nth-child(odd))
∞∞∞ Chaining ∞∞∞
$(div).show().hide().slideUp().slideDown();
$(div).show().hide().slideUp().slideDown();            Get the divs,
$(div).show().hide().slideUp().slideDown();          and show them,
$(div).show().hide().slideUp().slideDown();          now hide them,
$(div).show().hide().slideUp().slideDown();    and then slide them up,
$(div).show().hide().slideUp().slideDown();then finally slide them down.
Cant chain text getters.val() .html() .text() .css(prop) .attr(prop), etc
Gotc ha  & Tip  if ( $(foo) ) {    doAmazing();  }
1) $(foo)2) $()3) []4) [].join(,) // works
if ( $(foo) ) {  doAmazing();}
if ( $(foo).length ) {  doAmazing();}
$(el).doStuff        vs  $.doStuff
$(el).doStuff runs against  everything   matched.
$.doStuffis a utility.
Deprecated$.browser.version$.browser.msie$.browser.safari$.browser.webkit
Doing stuff
$(a).click(function () {  alert(I got clicked);  return false;});
$(a).click(function () {  alert(I got clicked);  return false;});      Find the anchors
$(a).click(function () {  alert(I got clicked);  return false;});    when theyre clicked
$(a).click(function () {  alert(I got clicked);  return false;});run this function - dont worry   about the crazy syntax.
$(a).click(function () {  alert(I got clicked);  return false;}); Cancel the browsers default action, which is to redirect.
$(a).click(function(event){   event.preventDefault();   alert(I got clicked); });Same thing as cancelling (almost),  this ...
• click, dblclick• mousedown, mouseup, mousemove  mouseover, mouseout, mouseenter  mouseleave• keydown, keypress, keyup• s...
Tabs freakin everywhere!
You get the idea.
A tabbing system is...• A group of "panels"• Tabs (or links) pointing to a panel• Clicking tab, hides all panels, then  sh...
...the content can also be be Ajaxy
A few words on this
this is the elementthat the event ishappening to.
$(a).click(function () {  console.log(this);});this is the anchor element, not the jQuerywrapped element.
Common mistake$(a).click(function () {  setTimeout(function () {    $(this).text("Im alive!");  }, 1000);});
Common mistake$(a).click(function () {  setTimeout(function () {    $(this).text("Im alive!");  }, 1000);});this is the wi...
Common mistake$(a).click(function () {  var el = this;  setTimeout(function () {    $(el).text("Im alive!");  }, 1000);});
Live codin time!     tabs.html
Events
$(input).keydown(function (event) {  // whats the event arg?});
•.keyup(fn), .click(fn), etc•.bind(type, fn)•.trigger(type), unbind(type)•.one(type, fn)
Tip      Clickables
$.event.special.click = {   setup: function() {      $(this).css(cursor,pointer);      return false;   },   teardown: func...
Problem
<h1>Super Ted</h1>               <img src="superted.jpg"> When the               <img src="spotty.jpg"> page has      <img...
<h1>Super Ted</h1>  Clicking     <img src="superted.jpg">               <img src="spotty.jpg">these images               <...
<h1>Super Ted</h1>                <img src="superted.jpg"> Now Ajax       <img src="spotty.jpg">(or something   <img src="...
<h1>Super Ted</h1>                <img src="superted.jpg"> Now Ajax       <img src="spotty.jpg">                <img src="...
<h1>Super Ted</h1>                <img src="superted.jpg">                <img src="spotty.jpg">Clicking this   <img src="...
Solution: delegation
<h1>Super Ted</h1><img src="superted.jpg"><img src="spotty.jpg"><img src="txspete.jpg"><script src="jquery.js"><script>$(#...
These imagesare loaded after the DOM hasloaded via Ajax
Were going to "delegate" thetask of listening for particular     events to this <div>
Weve "delegate" clicks,looking for the "img" selector
$(div).delegate(img,click,function(){  /* do funky stuff */});
Now, any new images inserted in this<div> can be clicked and will fire the       "funky stuff" function
Ajax   Warning: wear your tech-hat
No brainer Ajax
.load
Example
$(#detail).load(page.html);
$(#detail).load(page.html #id);
1. Ajax load the page2. Search for the selector passed  (#dizzy)3. Squirt contents found into original  selector
$(#tabs a).click(function (event) {  // this.pathname = ajax-load-detail.html  $(#detail).load(this.pathname);  return fal...
this.hash$(#tabs a).click(function (event) {  $(#detail).load(this.pathname +   +this.hash);  return false;});
JSON
JavaScript Object{    screen_name : "@rem",    height : "short",    fingers : 5,    brit : true}
JSON{    "screen_name": "@rem",    "height": "short",    "fingers": 5,    "brit": true}
JSONP WTF
JSON+...{    "screen_name": "@rem",    "height": "short",    "fingers": 5,    "brit": true}
JSON+Paddingcallback({ "screen_name": "@rem", "height": "short", "fingers": 5, "brit": true});
Getting otherpeoples data
$.getJSON
Remember =?
Twitterajax/twitter.html
$(document).ready(function () {  $.getJSON(http://twitter.com/statuses/user_timeline/rem.json?callback=?,  function (data)...
Loading...Giving users feedback
Ajax order1. ajaxStart2. ajaxSuccess (or ajaxError)3. ajaxComplete    http://api.jquery.com/?s=ajax
$(#status).ajaxStart(function () {  $(this).fadeIn();}).ajaxComplete(function () {  $(this).fadeOut();});
Deferreds
$.get(foo.html, function (html) {var jqXHR = $.get(foo.html);  $(#latest).append(html);});jqXHR.done(function (html) {  $(...
$.ajax({  url: foo.json,  dataType: json,  success: function () {     // this === xhr  },  error: function () {  }});
$.ajax({  url: foo.json,  dataType: json,  context: document.body,  success: function () {     // this === body element  }...
var jqXHR = $.ajax({  url: foo.json,  dataType: json,  context: document.body});jqXHR.then(success, fail);
var jqXHR = $.ajax({  url: foo.json,  dataType: json,  context: document.body});jqXHR.then(success, fail);// much later in...
jqXHR is apromise
var jqXHR = $.ajax({  url: foo.json,  dataType: json,  context: document.body});// much later in the codejqXHR.done(succes...
.done(ok)   // success.fail(fail) // error.always(fn) // complete.then(ok, fail)
Plugins
What’s a plugin?A plugin is nothing more than acustom jQuery method created toextend the functionality of the jQueryobject...
Plugin design in 6 steps
Step 1:create a privatescope for $ alias
<!DOCTYPE html><html><body><script src=”jquery.js”></script><script>(function ($) {})(jQuery);</script></body></html>
Step 2: attach plugin to fnalias (aka prototype)
<!DOCTYPE html><html><body><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = function () {  $(this).t...
<!DOCTYPE html><html><body><p>I hate jQuery!</p><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = fun...
Step 3:add implicit iteration
<!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>...
Step 4:enable chaining
<!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>...
<!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>...
<!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>...
Step 5:add default options
<!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>...
Step 6:add custom options
<!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>...
<!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>...
<!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>...
<!DOCTYPE html><html><body>     http://jsbin.com/ifuga/edit<p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script s...
<!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>...
<!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>...
Poorlydesigned plugins
$.fn.myplugin = function () {  var me = $(this).each(function() {    return $(this).bind(someEvent, function () {      // ...
$.fn.myplugin = function () {  var me = $(this).each(fn);  return me;};
$.fn.myplugin = function () {  return $(this).each(fn);};
$.fn.myplugin = function () {  return $(this).each(function() {    return $(this).bind(someEvent, function () {      // do...
$.fn.myplugin = function () {  return $(this).each(function() {    return $(this).bind(someEvent, function () {      // do...
$.fn.myplugin = function () {  return this.each(function() {    return $(this).bind(someEvent, function () {      // does ...
$.fn.myplugin = function () {  return this.each(function() {    return $(this).bind(someEvent, function () {      // does ...
$.fn.myplugin = function () {  return this.each(function() {    $(this).bind(someEvent, function () {      // does somethi...
$.fn.myplugin = function () {  return this.each(function() {    $(this).bind(someEvent, function () {      // does somethi...
$.fn.myplugin = function () {   return this.bind(someEvent, function () {     // does something  });};
(function ($) {  $.fn.myplugin = function () {    return this.bind(someEvent, function () {       // does something     })...
Questions?      To contact me after my presentation      – text NHT to INTRO (46876)      Or --      remy@leftlogic.com   ...
Yearning jQuery
Yearning jQuery
Yearning jQuery
Yearning jQuery
Yearning jQuery
Yearning jQuery
Yearning jQuery
Yearning jQuery
Yearning jQuery
Yearning jQuery
Yearning jQuery
Yearning jQuery
Yearning jQuery
Yearning jQuery
Upcoming SlideShare
Loading in...5
×

Yearning jQuery

3,328

Published on

Published in: Technology, Design
0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,328
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
68
Comments
0
Likes
6
Embeds 0
No embeds

No notes for slide

Yearning jQuery

  1. 1. Yearning jQuery
  2. 2. Hi, I’m Remy / @remScreencast @jqueryfordesigners.comQuestions: interrupt me& ask!
  3. 3. 1. Build without jQuery.2. Design the start and end of your effects without jQuery.3. Add jQuery a little at a time.
  4. 4. (a lot of it is...) "all about CSS" Me, to many a colleague
  5. 5. @rem Remy SharpDear designer/dev: if youre usingJavaScript to do a job that CSS could havedone perfectly well, youve lost somepoints in my book. Sorry
  6. 6. @rem Remy SharpThe day someone loses business becausean animated transition wasnt used toreveal a screenshot: Ill sell my left nut oneBay. #cssinstead
  7. 7. What were covering• Getting friendly with the $• DOM navigation & manipulation• Events• Ajax• Tips
  8. 8. APIs Blogs, tutorials, screencasts, docs.jquery.com plugins, development sprints api.jquery.com visualjquery.com Twitter forum.jquery.com @jquery Help!@jquerysites @jqueryui IRC channel irc.freenode.net/#jquery
  9. 9. jsbin.com
  10. 10. Bling Function
  11. 11. It means no more of thisvar tables = document.getElementsByTagName(table);for (var t = 0; t < tables.length; t++) {! var rows = tables[t].getElementsByTagName(tr);! for (var i = 1; i < rows.length; i += 2) { if (!/(^|s)odd(s|$)/.test(rows[i].className)) { rows[i].className += odd; } }}
  12. 12. jQuery simplifies$(table tr:nth-child(odd)).addClass(odd);
  13. 13. jQuery simplifiesjQuery function$(table tr:nth-child(odd)).addClass(odd);
  14. 14. jQuery simplifiesjQuery function$(table tr:nth-child(odd)).addClass(odd); CSS expression
  15. 15. jQuery simplifiesjQuery function jQuery method$(table tr:nth-child(odd)).addClass(odd); CSS expression
  16. 16. jQuery simplifies$(table tr:nth-child(odd)).addClass(odd);
  17. 17. $(just css)
  18. 18. Tools of the Trade
  19. 19. • Firefox: Firebug (& FireQuery*)• Safari & Chrome: Web Inspector• Opera: DragonFly• IE: Web Developer Toolbar
  20. 20. Tip $.fn.jquery (little q)
  21. 21. Lets play.http://twitter.com
  22. 22. jQuery on every site? No Problem.
  23. 23. http://bit.ly/9JAcCj
  24. 24. Lets play.
  25. 25. Installing jQuery
  26. 26. dev or min?
  27. 27. Hosting options • Host it yourself (good for offline dev) • Hotlink it: • Media Temple • Microsoft • Google (my pick)http://docs.jquery.com/Downloading_jQuery
  28. 28. CDN FTW
  29. 29. Tip: keep a copy on your machine
  30. 30. Where does it all go?
  31. 31. • jQuery first• Then jQuery plugins• Then your code
  32. 32. • Other JavaScript libraries• jQuery last library• Then jQuery plugin scripts• Then your code
  33. 33. <html><head> <styles> <!-- make me beautiful --> </styles></head><body> <content> <!-- make me learned --> </content> <behaviour> <!-- ooo, matron --> </behaviour></body></html>
  34. 34. <html> <head> <styles> Styles first <!-- make me beautiful -->lets the page </styles> </head> render <body> without <content> scripts <!-- make me learned --> </content> blocking <behaviour> <!-- ooo, matron --> </behaviour> </body> </html>
  35. 35. <html> <head> <styles> <!-- make me beautiful --> Then your </styles> content, </head>again so that <body> <content>its delivered <!-- make me learned --> to your </content> visitor as <behaviour> <!-- ooo, matron --> early as </behaviour> possible </body> </html>
  36. 36. <html> <head> <styles> <!-- make me beautiful --> </styles> </head> <body>Finally, add <content> your <!-- make me learned -->behaviour, </content>the jQuery <behaviour> <!-- ooo, matron --> and sexy </behaviour>magic jazz. </body> </html>
  37. 37. $(document).ready(function () { // < YOU >});
  38. 38. $(document).ready(function () { // < YOU >});
  39. 39. $(function () { // < YOU >});
  40. 40. TipjQuery(function ($) { // < YOU >}); Useful when giving code to a client
  41. 41. <!DOCTYPE html><html lang="en"><head><meta charset=utf-8 /><title>My first jQuery page</title></head><body><h1>Remy woz ere</h1><p>Lorem ipsum dolor sit amet.</p><script src="jquery.min.js"></script><script>$(function () { // < YOU >});</script></body></html>
  42. 42. Is it jQuery or $?
  43. 43. Its both.
  44. 44. $(table tr:nth-child(odd))
  45. 45. jQuery(table tr:nth-child(odd))
  46. 46. $(table tr:nth-child(odd))
  47. 47. ∞∞∞ Chaining ∞∞∞
  48. 48. $(div).show().hide().slideUp().slideDown();
  49. 49. $(div).show().hide().slideUp().slideDown(); Get the divs,
  50. 50. $(div).show().hide().slideUp().slideDown(); and show them,
  51. 51. $(div).show().hide().slideUp().slideDown(); now hide them,
  52. 52. $(div).show().hide().slideUp().slideDown(); and then slide them up,
  53. 53. $(div).show().hide().slideUp().slideDown();then finally slide them down.
  54. 54. Cant chain text getters.val() .html() .text() .css(prop) .attr(prop), etc
  55. 55. Gotc ha & Tip if ( $(foo) ) { doAmazing(); }
  56. 56. 1) $(foo)2) $()3) []4) [].join(,) // works
  57. 57. if ( $(foo) ) { doAmazing();}
  58. 58. if ( $(foo).length ) { doAmazing();}
  59. 59. $(el).doStuff vs $.doStuff
  60. 60. $(el).doStuff runs against everything matched.
  61. 61. $.doStuffis a utility.
  62. 62. Deprecated$.browser.version$.browser.msie$.browser.safari$.browser.webkit
  63. 63. Doing stuff
  64. 64. $(a).click(function () { alert(I got clicked); return false;});
  65. 65. $(a).click(function () { alert(I got clicked); return false;}); Find the anchors
  66. 66. $(a).click(function () { alert(I got clicked); return false;}); when theyre clicked
  67. 67. $(a).click(function () { alert(I got clicked); return false;});run this function - dont worry about the crazy syntax.
  68. 68. $(a).click(function () { alert(I got clicked); return false;}); Cancel the browsers default action, which is to redirect.
  69. 69. $(a).click(function(event){ event.preventDefault(); alert(I got clicked); });Same thing as cancelling (almost), this is useful for debugging.
  70. 70. • click, dblclick• mousedown, mouseup, mousemove mouseover, mouseout, mouseenter mouseleave• keydown, keypress, keyup• submit, change, blur, focus, select• scroll, resize, load, error
  71. 71. Tabs freakin everywhere!
  72. 72. You get the idea.
  73. 73. A tabbing system is...• A group of "panels"• Tabs (or links) pointing to a panel• Clicking tab, hides all panels, then shows just one
  74. 74. ...the content can also be be Ajaxy
  75. 75. A few words on this
  76. 76. this is the elementthat the event ishappening to.
  77. 77. $(a).click(function () { console.log(this);});this is the anchor element, not the jQuerywrapped element.
  78. 78. Common mistake$(a).click(function () { setTimeout(function () { $(this).text("Im alive!"); }, 1000);});
  79. 79. Common mistake$(a).click(function () { setTimeout(function () { $(this).text("Im alive!"); }, 1000);});this is the window object, not the link
  80. 80. Common mistake$(a).click(function () { var el = this; setTimeout(function () { $(el).text("Im alive!"); }, 1000);});
  81. 81. Live codin time! tabs.html
  82. 82. Events
  83. 83. $(input).keydown(function (event) { // whats the event arg?});
  84. 84. •.keyup(fn), .click(fn), etc•.bind(type, fn)•.trigger(type), unbind(type)•.one(type, fn)
  85. 85. Tip Clickables
  86. 86. $.event.special.click = { setup: function() { $(this).css(cursor,pointer); return false; }, teardown: function() { $(this).css(cursor,); return false; }}; All credit to David Walsh
  87. 87. Problem
  88. 88. <h1>Super Ted</h1> <img src="superted.jpg"> When the <img src="spotty.jpg"> page has <img src="txspete.jpg"> finished <script src="jquery.js"> <script>loading, the $(img).click(function(){jQuery runs showDetails(this); }); </script>
  89. 89. <h1>Super Ted</h1> Clicking <img src="superted.jpg"> <img src="spotty.jpg">these images <img src="txspete.jpg"> "shows <script src="jquery.js"> details" <script> $(img).click(function(){ showDetails(this); }); </script>
  90. 90. <h1>Super Ted</h1> <img src="superted.jpg"> Now Ajax <img src="spotty.jpg">(or something <img src="txspete.jpg">else) add new <script src="jquery.js"> <script>images to the $(img).click(function(){ page showDetails(this); }); </script>
  91. 91. <h1>Super Ted</h1> <img src="superted.jpg"> Now Ajax <img src="spotty.jpg"> <img src="txspete.jpg">(or something <img src="mothernature.jpg">else) add new <script src="jquery.js">images to the <script> $(img).click(function(){ page showDetails(this); }); </script>
  92. 92. <h1>Super Ted</h1> <img src="superted.jpg"> <img src="spotty.jpg">Clicking this <img src="txspete.jpg">image doesnt <img src="mothernature.jpg">do anything. <script src="jquery.js"> <script> $(img).click(function(){ showDetails(this); }); </script>
  93. 93. Solution: delegation
  94. 94. <h1>Super Ted</h1><img src="superted.jpg"><img src="spotty.jpg"><img src="txspete.jpg"><script src="jquery.js"><script>$(#superTed).delegate(img,click,function(){ showDetails(this);});</script>
  95. 95. These imagesare loaded after the DOM hasloaded via Ajax
  96. 96. Were going to "delegate" thetask of listening for particular events to this <div>
  97. 97. Weve "delegate" clicks,looking for the "img" selector
  98. 98. $(div).delegate(img,click,function(){ /* do funky stuff */});
  99. 99. Now, any new images inserted in this<div> can be clicked and will fire the "funky stuff" function
  100. 100. Ajax Warning: wear your tech-hat
  101. 101. No brainer Ajax
  102. 102. .load
  103. 103. Example
  104. 104. $(#detail).load(page.html);
  105. 105. $(#detail).load(page.html #id);
  106. 106. 1. Ajax load the page2. Search for the selector passed (#dizzy)3. Squirt contents found into original selector
  107. 107. $(#tabs a).click(function (event) { // this.pathname = ajax-load-detail.html $(#detail).load(this.pathname); return false;});
  108. 108. this.hash$(#tabs a).click(function (event) { $(#detail).load(this.pathname + +this.hash); return false;});
  109. 109. JSON
  110. 110. JavaScript Object{ screen_name : "@rem", height : "short", fingers : 5, brit : true}
  111. 111. JSON{ "screen_name": "@rem", "height": "short", "fingers": 5, "brit": true}
  112. 112. JSONP WTF
  113. 113. JSON+...{ "screen_name": "@rem", "height": "short", "fingers": 5, "brit": true}
  114. 114. JSON+Paddingcallback({ "screen_name": "@rem", "height": "short", "fingers": 5, "brit": true});
  115. 115. Getting otherpeoples data
  116. 116. $.getJSON
  117. 117. Remember =?
  118. 118. Twitterajax/twitter.html
  119. 119. $(document).ready(function () { $.getJSON(http://twitter.com/statuses/user_timeline/rem.json?callback=?, function (data) { $(#tweets).empty(); $.each(data, function (i, item) { $(#tweets).append(<li class="tweet"> + item.text + </li>); }); });});
  120. 120. Loading...Giving users feedback
  121. 121. Ajax order1. ajaxStart2. ajaxSuccess (or ajaxError)3. ajaxComplete http://api.jquery.com/?s=ajax
  122. 122. $(#status).ajaxStart(function () { $(this).fadeIn();}).ajaxComplete(function () { $(this).fadeOut();});
  123. 123. Deferreds
  124. 124. $.get(foo.html, function (html) {var jqXHR = $.get(foo.html); $(#latest).append(html);});jqXHR.done(function (html) { $(#latest).append(html);});
  125. 125. $.ajax({ url: foo.json, dataType: json, success: function () { // this === xhr }, error: function () { }});
  126. 126. $.ajax({ url: foo.json, dataType: json, context: document.body, success: function () { // this === body element }, error: function () { }});
  127. 127. var jqXHR = $.ajax({ url: foo.json, dataType: json, context: document.body});jqXHR.then(success, fail);
  128. 128. var jqXHR = $.ajax({ url: foo.json, dataType: json, context: document.body});jqXHR.then(success, fail);// much later in the codejqXHR.done(success2);
  129. 129. jqXHR is apromise
  130. 130. var jqXHR = $.ajax({ url: foo.json, dataType: json, context: document.body});// much later in the codejqXHR.done(success);
  131. 131. .done(ok) // success.fail(fail) // error.always(fn) // complete.then(ok, fail)
  132. 132. Plugins
  133. 133. What’s a plugin?A plugin is nothing more than acustom jQuery method created toextend the functionality of the jQueryobject$(‘ul’).myPlugin()
  134. 134. Plugin design in 6 steps
  135. 135. Step 1:create a privatescope for $ alias
  136. 136. <!DOCTYPE html><html><body><script src=”jquery.js”></script><script>(function ($) {})(jQuery);</script></body></html>
  137. 137. Step 2: attach plugin to fnalias (aka prototype)
  138. 138. <!DOCTYPE html><html><body><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = function () { $(this).text( $(this).text().replace(/hate/g, ‘love’) );}; // end of plugin})(jQuery);</script></body></html>
  139. 139. <!DOCTYPE html><html><body><p>I hate jQuery!</p><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = function () { $(this).text( $(this).text().replace(/hate/g, ‘love’) );}; // end of plugin})(jQuery);$(‘p’).notHate();</script></body></html>
  140. 140. Step 3:add implicit iteration
  141. 141. <!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = function () { this.each(function () { $(this).text( $(this).text().replace(/hate/g, ‘love’) ); });}; // end of plugin})(jQuery);$(‘p’).notHate();</script></body></html>
  142. 142. Step 4:enable chaining
  143. 143. <!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = function () { return this.each(function () { $(this).text( $(this).text().replace(/hate/g, ‘love’) ); });}; // end of plugin})(jQuery);$(‘p’).notHate().hide();</script></body></html>
  144. 144. <!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script> this == jQuery(function ($) {$.fn.notHate = function () { return this.each(function () { $(this).text( $(this).text().replace(/hate/g, ‘love’) ); });}; // end of plugin})(jQuery);$(‘p’).notHate().hide();</script></body></html>
  145. 145. <!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script> this == jQuery(function ($) {$.fn.notHate = function () { return this.each(function () { $(this).text( $(this).text().replace(/hate/g, ‘love’) ); });}; // end of == DOM element this plugin})(jQuery);$(‘p’).notHate().hide();</script></body></html>
  146. 146. Step 5:add default options
  147. 147. <!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = function () { return this.each(function () { $(this).text( $(this).text().replace(/hate/g, ➥ $.fn.notHate.defaults.text) ); });}; // end of plugin$.fn.notHate.defaults = {text:‘love’};})(jQuery);$(‘p’).notHate();</script></body></html>
  148. 148. Step 6:add custom options
  149. 149. <!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = function () { return this.each(function () { $(this).text( $(this).text().replace(/hate/g, ➥ $.fn.notHate.defaults.text) ); });}; // end of plugin$.fn.notHate.defaults = {text:‘love’};})(jQuery);$(‘p’).notHate({text: ‘love-love-love’});</script></body></html>
  150. 150. <!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = function (options) { return this.each(function () { $(this).text( $(this).text().replace(/hate/g, ➥ $.fn.notHate.defaults.text) ); });}; // end of plugin$.fn.notHate.defaults = {text:‘love’};})(jQuery);$(‘p’).notHate({text: ‘love-love-love’});</script></body></html>
  151. 151. <!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = function (options) { var settings = $.extend({}, ➥ $.fn.notHate.defaults, options); return this.each(function () { $(this).text( $(this).text().replace(/hate/g, ➥ $.fn.notHate.defaults.text) ); });}; // end of plugin$.fn.notHate.defaults = {text:‘love’};})(jQuery);$(‘p’).notHate({text: ‘love-love-love’});</script></body></html>
  152. 152. <!DOCTYPE html><html><body> http://jsbin.com/ifuga/edit<p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = function (options) { var settings = $.extend({}, ➥ $.fn.notHate.defaults, options); return this.each(function () { $(this).text( $(this).text().replace(/hate/g, ➥ settings.text) ); });}; // end of plugin$.fn.notHate.defaults = {text:‘love’};})(jQuery);$(‘p’).notHate({text: ‘love-love-love’});</script></body></html>
  153. 153. <!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = function (options) { var settings = $.extend({}, ➥ $.fn.notHate.defaults, options); return this.each(function () { $(this).text( $(this).text().replace(/hate/g, ➥ settings.text) ); });}; // end of plugin$.fn.notHate.defaults = {text:‘love’};})(jQuery);$(‘p’).notHate({text: ‘love-love-love’});</script></body></html>
  154. 154. <!DOCTYPE html><html><body><p>I hate jQuery!</p><p>I mean really hate jQuery!</p><script src=”jquery.js”></script><script>(function ($) {$.fn.notHate = function (options) { var settings = $.extend({}, ➥ $.fn.notHate.defaults, options); return this.text(function (i, text) { return text.replace(/hate/g, ➥ settings.text); });}; // end of plugin$.fn.notHate.defaults = {text:‘love’};})(jQuery);$(‘p’).notHate({text: ‘love-love-love’});</script></body></html>
  155. 155. Poorlydesigned plugins
  156. 156. $.fn.myplugin = function () {  var me = $(this).each(function() {    return $(this).bind(someEvent, function () {      // does something    });  });  return me;};
  157. 157. $.fn.myplugin = function () {  var me = $(this).each(fn);  return me;};
  158. 158. $.fn.myplugin = function () {  return $(this).each(fn);};
  159. 159. $.fn.myplugin = function () {  return $(this).each(function() {    return $(this).bind(someEvent, function () {      // does something    });  });};
  160. 160. $.fn.myplugin = function () {  return $(this).each(function() {    return $(this).bind(someEvent, function () {      // does something    });  });};
  161. 161. $.fn.myplugin = function () {  return this.each(function() {    return $(this).bind(someEvent, function () {      // does something    });  });};
  162. 162. $.fn.myplugin = function () {  return this.each(function() {    return $(this).bind(someEvent, function () {      // does something    });  });};
  163. 163. $.fn.myplugin = function () {  return this.each(function() {    $(this).bind(someEvent, function () {      // does something    });  });};
  164. 164. $.fn.myplugin = function () {  return this.each(function() {    $(this).bind(someEvent, function () {      // does something    });  });};
  165. 165. $.fn.myplugin = function () { return this.bind(someEvent, function () {  // does something  });};
  166. 166. (function ($) { $.fn.myplugin = function () {   return this.bind(someEvent, function () {    // does something  }); };})(jQuery);
  167. 167. Questions? To contact me after my presentation – text NHT to INTRO (46876) Or -- remy@leftlogic.com @rem
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×