Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

The Dom Scripting Toolkit J Query

884 views

Published on

Published in: Technology
  • Be the first to comment

The Dom Scripting Toolkit J Query

  1. 1. The DOM Scripting Toolkit: jQuery Remy Sharp Left Logic
  2. 2. Why JS Libraries? • DOM scripting made easy
  3. 3. Why JS Libraries? • DOM scripting made easy • Cross browser work done for you
  4. 4. Why JS Libraries? • DOM scripting made easy • Cross browser work done for you • Puts some fun back in to coding
  5. 5. Why jQuery? • Lean API, makes your code smaller
  6. 6. Why jQuery? • Lean API, makes your code smaller • Small (15k gzip’d), encapsulated, friendly library - plays well!
  7. 7. Why jQuery? • Lean API, makes your code smaller • Small (15k gzip’d), encapsulated, friendly library - plays well! • Plugin API is really simple
  8. 8. Why jQuery? • Lean API, makes your code smaller • Small (15k gzip’d), encapsulated, friendly library - plays well! • Plugin API is really simple • Large, active community
  9. 9. Why jQuery? • Lean API, makes your code smaller • Small (15k gzip’d), encapsulated, friendly library - plays well! • Plugin API is really simple • Large, active community • Big boys use it too: Google, BBC, Digg, Wordpress, Amazon, IBM.
  10. 10. What’s in jQuery? • Selectors & Chaining • DOM manipulation • Events • Ajax • Simple effects
  11. 11. Selectors $(‘#emails a.subject’);
  12. 12. Selectors • “Find something, do something with it”
  13. 13. Selectors • “Find something, do something with it” • The dollar function
  14. 14. Selectors • “Find something, do something with it” • The dollar function • CSS 1-3 selectors at the core of jQuery
  15. 15. Selectors • “Find something, do something with it” • The dollar function • CSS 1-3 selectors at the core of jQuery • Custom selectors
  16. 16. CSS Selectors $(‘div’)
  17. 17. CSS Selectors $(‘div’) $(‘div.foo’)
  18. 18. CSS Selectors $(‘div’) $(‘div.foo’) $(‘a[type=”application/pdf”]’)
  19. 19. CSS Selectors $(‘div’) $(‘div.foo’) $(‘a[type=”application/pdf”]’) $(‘tr td:first-child’)
  20. 20. Custom Selectors $(‘div:visible’)
  21. 21. Custom Selectors $(‘div:visible’) $(‘:animated’)
  22. 22. Custom Selectors $(‘div:visible’) $(‘:animated’) $(‘:input’)
  23. 23. Custom Selectors $(‘div:visible’) $(‘:animated’) $(‘:input’) $(‘tr:odd’)
  24. 24. Selector Performance $(‘#email’) // same as getElementById
  25. 25. Selector Performance $(‘#email’) // same as getElementById $(‘.email’) // slower on a big DOM
  26. 26. Selector Performance $(‘#email’) // same as getElementById $(‘.email’) // slower on a big DOM // using context $(‘#emails .subject’) $(‘.subject’, this)
  27. 27. Selector Performance $(‘#email’) // same as getElementById $(‘.email’) // slower on a big DOM // using context $(‘#emails .subject’) $(‘.subject’, this) // Caching var subjects = $(‘#emails .subject’);
  28. 28. Chaining $(‘#emails .subjects’) .click() .addClass(‘read’);
  29. 29. Chaining • jQuery returns itself * * except when requesting string values, such as .css() or .val()
  30. 30. Chaining • jQuery returns itself * • We can use the selector once, and keep manipulating * except when requesting string values, such as .css() or .val()
  31. 31. Chaining • jQuery returns itself * • We can use the selector once, and keep manipulating • Can reduce size of our code * except when requesting string values, such as .css() or .val()
  32. 32. Chaining in Action var image = new Image(); $(image) .load(function () { // show new image }) .error(function () { // handle error }) .attr(‘src’, ‘/path/to/large-image.jpg’);
  33. 33. More Chaining // simple tabs $(‘a.tab’).click(function () { $(tabs) .hide() .filter(this.hash) .show(); });
  34. 34. Collections $(‘#emails .subjects’).each(fn)
  35. 35. Collections • .each(fn) Iterates through a collection applying the method
  36. 36. Collections • .each(fn) Iterates through a collection applying the method • .map(fn) Iterates through collection, returning array from fn
  37. 37. Working the DOM $(this).addClass(‘read’).next().show();
  38. 38. DOM Walking • Navigation: children, parent, parents, siblings, next, prev
  39. 39. DOM Walking • Navigation: children, parent, parents, siblings, next, prev • Filters: filter, find, not, eq
  40. 40. DOM Walking • Navigation: children, parent, parents, siblings, next, prev • Filters: filter, find, not, eq • Collections: add, end
  41. 41. DOM Walking • Navigation: children, parent, parents, siblings, next, prev • Filters: filter, find, not, eq • Collections: add, end • Tests: is
  42. 42. DOM Walking • Navigation: children, $(‘div’) parent, parents, siblings, .find(‘a.subject’) .click(fn) next, prev .end() // strip filter • Filters: filter, find, not, eq .eq(0) // like :first .addClass(‘highlight’); • Collections: add, end • Tests: is
  43. 43. Manipulation • Inserting: after, append, before, prepend, html, text, wrap, clone
  44. 44. Manipulation • Inserting: after, append, before, prepend, html, text, wrap, clone • Clearing: empty, remove, removeAttr
  45. 45. Manipulation • Inserting: after, append, before, prepend, html, text, wrap, clone • Clearing: empty, remove, removeAttr • Style: attr, addClass, removeClass, toggleClass, css, hide, show, toggle
  46. 46. Manipulation • Inserting: after, append, before, prepend, html, text, wrap, clone • Clearing: empty, remove, removeAttr • Style: attr, addClass, removeClass, toggleClass, css, hide, show, toggle var a = $(document.createElement(‘a’)); // or $(‘<a>’) a.css(‘opacity’, 0.6).text(‘My Link’).attr(‘href’, ‘/home/’); $(‘div’).empty().append(a);
  47. 47. Data • Storing data directly against elements can cause leaks
  48. 48. Data • Storing data directly against elements can cause leaks • .data() clean way of linking data to element
  49. 49. Data • Storing data directly against elements can cause leaks • .data() clean way of linking data to element • All handled by jQuery’s garbage collection
  50. 50. Data • $(this).data(‘type’, ‘forward’); Storing data directly against elements can var types = cause leaks $(‘a.subject’).data(‘type’); • .data() clean way of $(‘a.subject’).removeData(); linking data to element • All handled by jQuery’s garbage collection
  51. 51. Events $(‘a.subject’).click();
  52. 52. DOM Ready • Most common event: DOM ready
  53. 53. DOM Ready • Most common event: DOM ready $(document).ready(function () {}) // or as a shortcut: $(function () {})
  54. 54. Binding • Manages events and garbage collection
  55. 55. Binding • Manages events and garbage collection • Event functions are bound to the elements matched selector
  56. 56. Binding • Manages events and garbage collection • Event functions are bound to the elements matched selector • Also supports .one()
  57. 57. Binding • Manages events and garbage collection • Event functions are bound to the elements matched selector • Also supports .one() $(‘a.reveal’).bind(‘click’, function(event) { // ‘this’ refers to the current element // this.hash is #moreInfo - mapping to real element $(this.hash).slideDown(); }).filter(‘:first’).trigger(‘click’);
  58. 58. Helpers • Mouse: click, dlbclick, mouseover, toggle, hover, etc.
  59. 59. Helpers • Mouse: click, dlbclick, mouseover, toggle, hover, etc. • Keyboard: keydown, keyup, keypress
  60. 60. Helpers • Mouse: click, dlbclick, mouseover, toggle, hover, etc. • Keyboard: keydown, keyup, keypress • Forms: change, select, submit, focus, blur
  61. 61. Helpers • Mouse: click, dlbclick, mouseover, toggle, hover, etc. • Keyboard: keydown, keyup, keypress • Forms: change, select, submit, focus, blur • Windows: scroll
  62. 62. Helpers • Mouse: click, dlbclick, mouseover, toggle, hover, etc. • Keyboard: keydown, keyup, keypress • Forms: change, select, submit, focus, blur • Windows: scroll • Windows, images, scripts: load, error
  63. 63. Custom Events • Roll your own
  64. 64. Custom Events • Roll your own • Bind to element (or elements)
  65. 65. Custom Events • Roll your own • Bind to element (or elements) • Trigger them later and pass data
  66. 66. Custom Events • Roll your own • Bind to element (or elements) • Trigger them later and pass data $(‘div.myWidget’).trigger(‘foo’, [123/*id*/]); // id access via // .bind(‘foo’, function (event, id, etc) {})
  67. 67. Event Namespaces • Support for event subsets via namespaces
  68. 68. Event Namespaces • Support for event subsets via namespaces • If you don’t want to unbind all type X events - use namespaces
  69. 69. Event Namespaces • $(‘a’).bind(‘click.foo’, fn); Support for event subsets via namespaces $(‘a’).unbind(‘.foo’); • If you don’t want to unbind all type X events - use namespaces
  70. 70. Ajax $.ajax({ url : ‘/foo’, success : bar });
  71. 71. Ajax Made Easy • Cross browser, no hassle.
  72. 72. Ajax Made Easy • Cross browser, no hassle. • $.ajax does it all
  73. 73. Ajax Made Easy • Cross browser, no hassle. • $.ajax does it all • Helpers $.get, $.getJSON, $.getScript, $.post, $.load
  74. 74. Ajax Made Easy • Cross browser, no hassle. • $.ajax does it all • Helpers $.get, $.getJSON, $.getScript, $.post, $.load • All Ajax requests sends: X-Requested-With = XMLHttpRequest
  75. 75. $.ajax $(‘form.register’).submit(function () { var el = this; // cache for use in success function $.ajax({ url : $(this).attr(‘action’), data : { ‘username’ : $(‘input.username’).val() }, // ‘this’ is the link beforeSend : showValidatingMsg, // function dataType : ‘json’, type : ‘post’, success : function (data) { // do something with data - show validation message }, error : function (xhr, status, e) { // handle the error - inform the user of problem console.log(xhr, status, e); } }); return false; // cancel default browser action });
  76. 76. Effects $(this).slideDown();
  77. 77. Base Effects $(‘div:hidden’).show(200, fn); $(‘div:visible’).hide(200); $(‘div’).fadeIn(200); $(‘div’).slideDown(100);
  78. 78. Base Effects $(‘div:hidden’).show(200, fn); $(‘div:visible’).hide(200); $(‘div’).fadeIn(200); $(‘div’).slideDown(100); $(‘div’).animate({ ‘opacity’ : 0.5, ‘left’ : ‘-=10px’ }, ‘slow’, fn)
  79. 79. Utilities $.browser.version
  80. 80. Utilities • Iterators: each, map, grep
  81. 81. Utilities • Iterators: each, map, grep • Browser versions, model and boxModel support
  82. 82. Utilities • Iterators: each, map, grep • Browser versions, model and boxModel support • isFunction
  83. 83. Core Utilities • jQuery can plays with others!
  84. 84. Core Utilities • jQuery can plays with others! $j = $.noConflict(); $j === $ // false
  85. 85. Core Utilities • Extend jQuery, merge objects and create settings from defaults
  86. 86. Core Utilities • Extend jQuery, merge objects and create settings from defaults var defaults = { ‘limit’ : 10, ‘dataType’ : ‘json’ }; var options = { ‘limit’ : 5, ‘username’ : ‘remy’ }; var settings = $.extend({}, defaults, options); // settings = { ‘limit’ : 5, ‘dataType’ : ‘json’, ‘username’ : ‘remy’ }
  87. 87. Plugins $(‘#emails .subjects’).doMagic()
  88. 88. Plugins • Simple to write
  89. 89. Plugins • Simple to write • Makes your code more reusable
  90. 90. Plugins • Simple to write • Makes your code more reusable • Don’t break the chain!
  91. 91. Simple Plugin // wrap in anonymous function to use $ (function ($) { $.fn.log = function () { console.log(this); // returning continues the chain return this; // this is the jQuery collection }; })(jQuery);
  92. 92. More Info Resources: Remy Sharp: jquery.com remy@leftlogic.com docs.jquery.com leftlogic.com groups.google.com/group/ jquery-en remysharp.com ui.jquery.com learningjquery.com jqueryfordesigners.com

×