DOM Scripting Toolkit - jQuery
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

DOM Scripting Toolkit - jQuery

on

  • 22,864 views

Detailed presentation on the jQuery API with a few details about jQuery you may not have used yet.

Detailed presentation on the jQuery API with a few details about jQuery you may not have used yet.

Statistics

Views

Total Views
22,864
Views on SlideShare
20,680
Embed Views
2,184

Actions

Likes
11
Downloads
381
Comments
0

34 Embeds 2,184

http://remysharp.com 2003
http://www.slideshare.net 37
http://www.webgox.com 32
http://www.sliversofmysoul.netsons.org 23
http://kookaa.blogspot.com 18
http://jquery-arulmurugant.blogspot.ru 14
http://mpathirage.com 14
http://webcache.googleusercontent.com 4
http://lanyrd.com 4
http://feeds.feedburner.com 4
http://flashnext.blogspot.com 3
http://egox.tumblr.com 2
http://kookaa.blogspot.tw 2
http://www.hanrss.com 2
http://localhost 2
http://jquery-arulmurugant.blogspot.com 2
http://kookaa.blogspot.in 1
http://kookaa.blogspot.co.il 1
http://kookaa.blogspot.de 1
http://74.125.93.104 1
http://kookaa.blogspot.ru 1
http://remysharp.dev 1
http://115.112.206.131 1
http://kookaa.blogspot.nl 1
http://jquery-arulmurugant.blogspot.in 1
http://static.slideshare.net 1
http://209.85.141.104 1
http://www.jacogrinwis.nl 1
http://ig.gmodules.com 1
http://www.zhuaxia.com 1
http://xianguo.com 1
http://kookaa.blogspot.com.es 1
http://www.kookaa.blogspot.com.au 1
http://pmomale-ld1 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

DOM Scripting Toolkit - jQuery Presentation Transcript

  • 1. The DOM Scripting Toolkit: jQuery Remy Sharp Left Logic
  • 2. Why JS Libraries? • DOM scripting made easy • Cross browser work done for you • Puts some fun back in to coding
  • 3. Why jQuery? • Lean API, makes your code smaller • Small (16k 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.
  • 4. What’s in jQuery? • Selectors & Chaining • DOM manipulation • Events • Ajax • Simple effects
  • 5. $ function
  • 6. $ • Selectors • DOM elements or raw HTML • “Ready” functions
  • 7. $ • $(‘ul’) • $(document.createElement(‘ul’)) • $(‘<ul />’) • $(fn)
  • 8. Selectors $(‘#emails a.subject’);
  • 9. Selectors • “Find something, do something with it” • CSS 1-3 selectors at the core of jQuery • Custom selectors
  • 10. CSS Selectors $(‘div’) $(‘div.foo’) $(‘a[type=”application/pdf”]’) $(‘tr td:first-child’)
  • 11. Tricky Selector <div id=“content.block” /> $(‘#content.block’) // won’t work :-( $(‘#content.block’) // will work :-)
  • 12. Custom Selectors $(‘div:visible’) $(‘:animated’) $(‘:input’) $(‘tr:odd’)
  • 13. Custom selectors • Roll your own $.expr[‘:’], { within: ‘jQuery(a).parents(m[3]).length > 0’ }); $(‘a.subject’).is(‘:within(“#email”)’);
  • 14. Selector Performance $(‘#email’) // same as getElementById $(‘.email’) // like getElementsByTagName // using context $(‘div.email’) $(‘#emails .subject’) $(‘.subject’, this) // Caching var $subjects = $(‘#emails .subject’);
  • 15. Chaining $(‘#emails .subjects’) .click() .addClass(‘read’);
  • 16. Chaining • jQuery returns itself * • We can use the selector once, and keep manipulating * except when requesting string values, such as .css() or .val()
  • 17. Chaining Example // simple tabs $(‘a.tab’).click(function () { // tabs = $(‘div.tab’) $tabs .hide() .filter(this.hash) // refers to page.html#hash .show(); });
  • 18. More Chaining var image = new Image(); $(image) .load(function () { // show new image }) .error(function () { // handle error }) .attr(‘src’, ‘/path/to/large-image.jpg’);
  • 19. Working the DOM $(this).addClass(‘read’).next().show();
  • 20. 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
  • 21. 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(‘Click!’).attr(‘href’, ‘/home/’); $(‘div’).empty().append(a);
  • 22. Data • $(el).data(‘type’, ‘forward’); .data() clean way of linking data to element var types = • Storing data directly $(‘a.subject’).data(‘type’); against elements can $(‘a.subject’).removeData(); cause leaks • All handled by jQuery’s garbage collection
  • 23. Events $(‘a.subject’).click();
  • 24. DOM Ready • Runs after DOM, but before images $(document).ready(function () {}) // or as a shortcut: $(function () {})
  • 25. 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’);
  • 26. 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
  • 27. 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) {})
  • 28. 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
  • 29. Ajax $.ajax({ url : ‘/foo’, success : bar });
  • 30. 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
  • 31. Simple Ajax /* Loads the #links element with the content from link.html matched in the selector */ $(‘#links’).load(‘link.html #links li’);
  • 32. JSON for Data • Uses eval for conversion • Use JSONP for cross server data (flickr, twitter, delicious, etc) • JSON simple to use, and less space than XML
  • 33. Twitter Example // Run when the DOM has completed. // i.e. don’t hang on a script request $(funtion () { var url = ‘http://www.twitter.com/statuses/user_timeline/rem.json? callback=?’; $.ajax({ dataType: ‘jsonp’, url: url, success: function (data) { $(‘#status’).html(data[0].text); // update with my latest tweet } }); });
  • 34. $.ajax $(‘form.register’).submit(function () { var el = this; // cache for use in success function $.ajax({ url : $(this).attr(‘action’), type : ‘post’, data : { ‘username’ : $(‘input.username’, this).val() }, beforeSend : showValidatingMsg, // function dataType : ‘json’, 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 });
  • 35. Effects $(this).slideDown();
  • 36. 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)
  • 37. Utilities $.browser.version
  • 38. Utilities • Iterators: each, map, grep • Browser versions, model and boxModel support • isFunction
  • 39. Core Utilities • jQuery can plays with others! • Good guys come last $ === jQuery; // true $ === $j; // false $j = $.noConflict(); // store jQuery in $j $j === $; // false $j === jQuery; // true
  • 40. Plugins $(‘#emails .subjects’).doMagic()
  • 41. Plugins • Simple to write • Makes your code more reusable • Don’t break the chain!
  • 42. Simple Plugin jQuery.fn.log = function () { // returning continues the chain return this.each(function() { if (this.nodeName == ‘A’) { console.log(this.href); } }); }; $(‘a’).log().filter(‘[hash=#first]’).log()
  • 43. 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’ }
  • 44. More Info Remy Sharp: Resources: jquery.com remy@leftlogic.com docs.jquery.com leftlogic.com groups.google.com/group/ jquery-en remysharp.com ui.jquery.com jqueryfordesigners.com learningjquery.com