jQueryThe killer Javascript framework                                      By Romain MATON                                ...
jQuery   Summary     Presentation     Concept     2 minutes tutorial     Best practices     Conclusion     Hands On !     ...
Presentation   Javascript Framework : DOM, events, effects and Ajax   January 2006, 1.3.2   Make Javascript easy   Enhance...
Developement (function(){ var       // Will speed up references to window, and allows munging its name.       window = thi...
Production (function(){var R=/((?:((?:([^()]+)|[^()]+)+)|[(?:[[^[]]*]|["][^"]*["]|[^[]"]+)+]|.|[^       >+~,([]+)+|[>+~])(...
Concept  Markup Separation (HTML contains data)    Presentation from markup (CSS)    Behavior from markup (JS event)    Se...
2 minutes tutorial (maybe 10)   Your best friend : the $ selector       $(“a”).css(‘color’, ‘red’);       $(“#elementId”)....
The jQuery object   Accessors     each(callback)     size()     eq(position)     get(), get(position)   Data     data(name...
The $ selector   By id, element or class      $(“#elementId”), $(“a”), $(“.className”)   Hierarchy      parent > child, pr...
Examples       $(‘a.selectedClass’)              Tag a with class selectedClass      $(‘#elementID:visible’)        Elemen...
Attributes   Attr     attr(name), attr(name, value), attr(name, fn), removeAttr(name)   Class     addClass(name), hasClass...
Traversing   eq(index)   filter(expr)   is(expr)   not(expr)   find(expr)   children(expr)   next(expr), nextAll(expr)   p...
Manipulation   append(content), appendTo(selector)   prepend(content), prependTo(selector)   after(content), insertAfter(s...
Events   ready(fn)   bind(type, fn)   one(type, fn)   trigger(event)   live(type, fn), die(type, fn)   hover, toggle   blu...
Effects, Ajax & utilities   show(), hide(), toggle()   slideToggle(speed)   fadeIn(speed), fadeOut(speed)   load(url, [dat...
Best practice : graceful degradation   Not perfect :       <script language="javascript">          var now = new Date();  ...
Best practice : performance         Use id !!!                              17
FYI      18
FYI      19
Best practice : cache objects   $(‘#myID’).css(‘border’, ‘3px dashed yellow’);   $(‘#myID’).css(‘background-color’, orange...
Best practice : sub queries   var myIDObject = $(‘#myID’);   var myIDObject = $(‘#myID input:enabled’);   var myIDObject =...
Best practice : use chaining   var $myIDObject = $(‘#myID’);   $myIDObject.css(‘border’, ‘3px dashed yellow’);   $myIDObje...
Best practice : limit DOM manipulation   var list = [...];   var $mylist = $(#myUL);   for (var i=0; i<list.length; i++) {...
Conclusion   Very good library   Just like Spring for Java : cannot do without !   Easy to use, makes code more readable  ...
Hands On !   Mvn jetty:run and code !   Home : http://jquery.com/   Documentation : http://docs.jquery.com/Main_Page   htt...
Plugins   Form plugins http://www.queness.com/post/204/25-jquery-plugins-   that-enhance-and-beautify-html-form-elements  ...
Upcoming SlideShare
Loading in...5
×

XKE - jQuery

1,043

Published on

Introduction to Javascript and jQuery.
Given at Xebia during XKE (May 6th, 2009).

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,043
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

XKE - jQuery

  1. 1. jQueryThe killer Javascript framework By Romain MATON November 5th, 2009 www.xebia.fr / blog.xebia.fr
  2. 2. jQuery Summary Presentation Concept 2 minutes tutorial Best practices Conclusion Hands On ! 2
  3. 3. Presentation Javascript Framework : DOM, events, effects and Ajax January 2006, 1.3.2 Make Javascript easy Enhanced Browser Support Unobtrusive Lightweight Production 19ko (minified and gzipped) Developpement 120ko (uncompressed code) 3
  4. 4. Developement (function(){ var // Will speed up references to window, and allows munging its name. window = this, // Will speed up references to undefined, and allows munging its name. undefined, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, jQuery = window.jQuery = window.$ = function( selector, context ) { // The jQuery object is actually just the init constructor enhanced return new jQuery.fn.init( selector, context ); }, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^[^<]*(<(.|s)+>)[^>]*$|^#([w-]+)$/, // Is it a simple selector isSimple = /^.[^:#[.,]*$/; jQuery.fn = jQuery.prototype = { init: function( selector, context ) { // Make sure that a selection was provided … 4
  5. 5. Production (function(){var R=/((?:((?:([^()]+)|[^()]+)+)|[(?:[[^[]]*]|["][^"]*["]|[^[]"]+)+]|.|[^ >+~,([]+)+|[>+~])(s*,s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length >1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift( );if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.leng th>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;a b.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length- 1)!==""){X[1]=(X[1]||"").replace(//g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByT agName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continu e}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.m atch[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[wu00c0-uFFFF_-]|.)+)/,CLASS:/.((?:[wu00c0-uFFFF_- ]|.)+)/,NAME:/[name=["]*((?:[wu00c0-uFFFF_-]|.)+)["]*]/,ATTR:/[s*((?:[wu00c0-uFFFF_- ]|.)+)s*(?:(S?=)s*(["]*)(.*?)3|)s*]/,TAG:/^((?:[wu00c0-uFFFF*_-]|.)+)/,CHILD:/:(only|nth|last|first)-child(?:((even|odd|[dn+- ]*)))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:((d*)))?(?=[^-]|$)/,PSEUDO:/:((?:[wu00c0-uFFFF_- ]|.)+)(?:((["]*)((?:([^)]+)|[^2()]*)+)2))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var … 5
  6. 6. Concept Markup Separation (HTML contains data) Presentation from markup (CSS) Behavior from markup (JS event) Semantic and Accessible Markup : h1..n, span, div, ul, li, dl, di, dd, blockquote, cite, em, strong, abbr, code, acronym… No more style=“background-color: red;” No more onclick=”doSomething();alert(‘foobar’);” Degradation (but gracefully) Cleaner and easier to manage code 6
  7. 7. 2 minutes tutorial (maybe 10) Your best friend : the $ selector $(“a”).css(‘color’, ‘red’); $(“#elementId”).hide(); $(“.className”).fadeOut(); Chainable $(“a”).bind(‘click’, function() {alert(‘Are you sur ?’);}) .css(‘border’, ‘3px dashed yellow’) .css(‘background-color’, ‘orange’) .fadeIn(‘slow’); Web 2.0 Effects show(), hide(), slideToggle(), fadeIn(), fadeOut(), animate()… Easily Extensible : create your own plugin ! 7
  8. 8. The jQuery object Accessors each(callback) size() eq(position) get(), get(position) Data data(name), data(name, value), removeData(name) queue(name), queue(name, callback), dequeue(name) Plugins jQuery.fn.extend(object), jQuery.extend(object) 8
  9. 9. The $ selector By id, element or class $(“#elementId”), $(“a”), $(“.className”) Hierarchy parent > child, prev + next, prev ~ sibblings Filters :first, :last :odd, :even :not, :eq, :lt, :gt :hidden, :visible :input, :text, :submit, :button, :file, :radio, :checkbox :enabled, :disabled, :checked, :selected 9
  10. 10. Examples $(‘a.selectedClass’) Tag a with class selectedClass $(‘#elementID:visible’) Element with id elementID that is visible $(‘p[title="Hello"]’) Tag p with title attribute equals Hello $(‘p[title^="H"]’) Tag p with title attribute begins with H $(‘#selectID option:selected’) Selected option in element with id selectID $(‘input[type=password], Password or text input input[type=text]’) $(‘table.orders tr:odd’) Odd tr in table with class orders 10
  11. 11. Attributes Attr attr(name), attr(name, value), attr(name, fn), removeAttr(name) Class addClass(name), hasClass(name), removeClass(name) toggleClass(name) HTML html(), html(val) Text text(), text(val) Value val(), val(val) 11
  12. 12. Traversing eq(index) filter(expr) is(expr) not(expr) find(expr) children(expr) next(expr), nextAll(expr) prev(expr), prevAll(expr) closest(expr) sibblings(expr) 12
  13. 13. Manipulation append(content), appendTo(selector) prepend(content), prependTo(selector) after(content), insertAfter(selector) before(content), insertBefore(selector) wrap(html), wrap(elem), wrapAll(html), wrapAll(elem) replaceWith(html) empty() clone() 13
  14. 14. Events ready(fn) bind(type, fn) one(type, fn) trigger(event) live(type, fn), die(type, fn) hover, toggle blur, change, click, keypress… 14
  15. 15. Effects, Ajax & utilities show(), hide(), toggle() slideToggle(speed) fadeIn(speed), fadeOut(speed) load(url, [data], [callback]) isArray(obj), trim(str) jQuery.each(obj, callback) 15
  16. 16. Best practice : graceful degradation Not perfect : <script language="javascript"> var now = new Date(); if(now.getHours() < 12) document.write(Good Morning !); else document.write(Good Afternoon !); </script> Prefer : <p title="Good Day Message">Good Morning !</p> var now = new Date(); if(now.getHours() >= 12) { var goodDay = $(p[title="Good Day Message"]); goodDay.text(Good Afternoon !); } 16
  17. 17. Best practice : performance Use id !!! 17
  18. 18. FYI 18
  19. 19. FYI 19
  20. 20. Best practice : cache objects $(‘#myID’).css(‘border’, ‘3px dashed yellow’); $(‘#myID’).css(‘background-color’, orange’); $(‘#myID’).fadeIn(‘slow’); var $myIDObject = $(‘#myID’); $myIDObject.css(‘border’, ‘3px dashed yellow’); $myIDObject.css(‘background-color’, ‘orange’); $myIDObject.fadeIn(‘slow’); window.$my = { head : $(‘head’), orders: $(‘#order_table’) }; 20
  21. 21. Best practice : sub queries var myIDObject = $(‘#myID’); var myIDObject = $(‘#myID input:enabled’); var myIDObject = $(‘#myID input:disabled’); var myIDObject = $(‘#myID’); var myIDObject = $myIDObject.find(‘input:enabled’); var myIDObject = $myIDObject.find(‘input:disabled’); 21
  22. 22. Best practice : use chaining var $myIDObject = $(‘#myID’); $myIDObject.css(‘border’, ‘3px dashed yellow’); $myIDObject.css(‘background-color’, ‘orange’); $myIDObject.fadeIn(‘slow’); var $myIDObject = $(‘#myID’); $myIDObject.css(‘border’, ‘3px dashed yellow’).css(‘background- color’, ‘orange’).fadeIn(‘slow’); var $myIDObject = $(‘#myID’); $myIDObject.css(‘border’, ‘3px dashed yellow’) .css(‘background-color’, ‘orange’) .fadeIn(‘slow’); 22
  23. 23. Best practice : limit DOM manipulation var list = [...]; var $mylist = $(#myUL); for (var i=0; i<list.length; i++) { $mylist.append(‘<li>’ + list[i] + ‘</li>’); } var list = [...]; var $mylist = $(‘#myUL’); var ul = ‘<ul id="#myUL">’; for (var i=0; i<list.length; i++) { ul += ‘<li>’ + list[i] + ‘</li>’; } ul += ‘</ul>’; $mylist.replaceWith(lis); 23
  24. 24. Conclusion Very good library Just like Spring for Java : cannot do without ! Easy to use, makes code more readable Efficient and cross browser 24
  25. 25. Hands On ! Mvn jetty:run and code ! Home : http://jquery.com/ Documentation : http://docs.jquery.com/Main_Page http://www.artzstudio.com/files/jquery- rules/jquery_1.3_cheatsheet_v1.pdf API : http://api.jquery.com/ Plugins : http://plugins.jquery.com/ 25
  26. 26. Plugins Form plugins http://www.queness.com/post/204/25-jquery-plugins- that-enhance-and-beautify-html-form-elements Form validations http://bassistance.de/jquery-plugins/jquery-plugin- validation/ Simplemodal http://www.ericmmartin.com/projects/simplemodal/ Pirobox http://designshack.co.uk/news/pirobox-jquery-lightbox Thickbox http://jquery.com/demo/thickbox/ JQueryUI http://jqueryui.com/demos/dialog/ BlockUI http://malsup.com/jquery/block/ Lightbox http://leandrovieira.com/projects/jquery/lightbox/ FaceBox http://famspam.com/facebox jDialog http://www.gimiti.com/kltan/wordpress/?p=20 FancyZoom http://www.dfc- e.com/metiers/multimedia/opensource/jquery-fancyzoom/ Alert Dialogs http://abeautifulsite.net/notebook/87 26

×