SlideShare uma empresa Scribd logo
1 de 44
Baixar para ler offline
The DOM Scripting Toolkit:
       jQuery
         Remy Sharp
          Left Logic
Why JS Libraries?

• DOM scripting made easy
• Cross browser work done for you
• Puts some fun back in to coding
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.
What’s in jQuery?

• Selectors & Chaining
• DOM manipulation
• Events
• Ajax
• Simple effects
$ function
$

• Selectors
• DOM elements or raw HTML
• “Ready” functions
$

• $(‘ul’)
• $(document.createElement(‘ul’))
• $(‘<ul />’)
• $(fn)
Selectors
$(‘#emails a.subject’);
Selectors

• “Find something, do something with it”
• CSS 1-3 selectors at the core of jQuery
• Custom selectors
CSS Selectors

$(‘div’)
$(‘div.foo’)
$(‘a[type=”application/pdf”]’)
$(‘tr td:first-child’)
Tricky Selector

<div id=“content.block” />
$(‘#content.block’) // won’t work :-(
$(‘#content.block’) // will work :-)
Custom Selectors

$(‘div:visible’)
$(‘:animated’)
$(‘:input’)
$(‘tr:odd’)
Custom selectors

• Roll your own
 $.expr[‘:’], {
   within: ‘jQuery(a).parents(m[3]).length > 0’
 });
 $(‘a.subject’).is(‘:within(“#email”)’);
Selector Performance
$(‘#email’) // same as getElementById
$(‘.email’) // like getElementsByTagName
// using context
$(‘div.email’)
$(‘#emails .subject’)
$(‘.subject’, this)
// Caching
var $subjects = $(‘#emails .subject’);
Chaining
$(‘#emails .subjects’)
   .click()
   .addClass(‘read’);
Chaining


• jQuery returns itself *
• We can use the selector once, and keep
    manipulating



* except when requesting string values, such as .css() or .val()
Chaining Example
// simple tabs
$(‘a.tab’).click(function () {
  // tabs = $(‘div.tab’)
  $tabs
    .hide()
    .filter(this.hash) // refers to page.html#hash
      .show();
});
More Chaining
var image = new Image();
$(image)
 .load(function () {
   // show new image
 })
 .error(function () {
   // handle error
 })
 .attr(‘src’, ‘/path/to/large-image.jpg’);
Working the DOM
 $(this).addClass(‘read’).next().show();
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
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);
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
Events
$(‘a.subject’).click();
DOM Ready
• Runs after DOM, but before images
  $(document).ready(function () {})
  // or as a shortcut:
  $(function () {})
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’);
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
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) {})
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
Ajax
$.ajax({ url : ‘/foo’, success : bar });
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
Simple Ajax

/* Loads the #links element with the content
from link.html matched in the selector */
$(‘#links’).load(‘link.html #links li’);
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
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
    }
  });
});
$.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
});
Effects
$(this).slideDown();
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)
Utilities
$.browser.version
Utilities

• Iterators: each, map, grep
• Browser versions, model and boxModel
  support
• isFunction
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
Plugins
$(‘#emails .subjects’).doMagic()
Plugins

• Simple to write
• Makes your code more reusable
• Don’t break the chain!
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()
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’ }
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

Mais conteúdo relacionado

Mais procurados

Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQueryRemy Sharp
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)jeresig
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonKris Wallsmith
 
History of jQuery
History of jQueryHistory of jQuery
History of jQueryjeresig
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutesSimon Willison
 
jQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and BlingjQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and BlingDoug Neiner
 
Processing and Processing.js
Processing and Processing.jsProcessing and Processing.js
Processing and Processing.jsjeresig
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Eventsdmethvin
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
HirshHorn theme: how I created it
HirshHorn theme: how I created itHirshHorn theme: how I created it
HirshHorn theme: how I created itPaul Bearne
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuerymanugoel2003
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery FundamentalsGil Fink
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009Remy Sharp
 

Mais procurados (20)

Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
 
PhoneGap: Local Storage
PhoneGap: Local StoragePhoneGap: Local Storage
PhoneGap: Local Storage
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
jQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and BlingjQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and Bling
 
Processing and Processing.js
Processing and Processing.jsProcessing and Processing.js
Processing and Processing.js
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
HirshHorn theme: how I created it
HirshHorn theme: how I created itHirshHorn theme: how I created it
HirshHorn theme: how I created it
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
J query training
J query trainingJ query training
J query training
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009
 

Semelhante a DOM Scripting Toolkit - jQuery

JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupalkatbailey
 
jQuery Internals + Cool Stuff
jQuery Internals + Cool StuffjQuery Internals + Cool Stuff
jQuery Internals + Cool Stuffjeresig
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
An in-depth look at jQuery
An in-depth look at jQueryAn in-depth look at jQuery
An in-depth look at jQueryPaul Bakaus
 
Cheap frontend tricks
Cheap frontend tricksCheap frontend tricks
Cheap frontend tricksambiescent
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tipsanubavam-techkt
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformanceJonas De Smet
 
Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9Jack Franklin
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the newRemy Sharp
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
jQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersjQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersYehuda Katz
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQueryBastian Feder
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jeresig
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Knowgirish82
 

Semelhante a DOM Scripting Toolkit - jQuery (20)

JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupal
 
jQuery Internals + Cool Stuff
jQuery Internals + Cool StuffjQuery Internals + Cool Stuff
jQuery Internals + Cool Stuff
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
An in-depth look at jQuery
An in-depth look at jQueryAn in-depth look at jQuery
An in-depth look at jQuery
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Cheap frontend tricks
Cheap frontend tricksCheap frontend tricks
Cheap frontend tricks
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tips
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
 
Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
jQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersjQuery Presentation to Rails Developers
jQuery Presentation to Rails Developers
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQuery
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Know
 
jQuery
jQueryjQuery
jQuery
 

Mais de Remy Sharp

HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreRemy Sharp
 
Yearning jQuery
Yearning jQueryYearning jQuery
Yearning jQueryRemy Sharp
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Remy Sharp
 
Forget the Web
Forget the WebForget the Web
Forget the WebRemy Sharp
 
Interaction Implementation
Interaction ImplementationInteraction Implementation
Interaction ImplementationRemy Sharp
 
HTML5: huh, what is it good for?
HTML5: huh, what is it good for?HTML5: huh, what is it good for?
HTML5: huh, what is it good for?Remy Sharp
 
HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsRemy Sharp
 
Developing for Mobile
Developing for MobileDeveloping for Mobile
Developing for MobileRemy Sharp
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with WingsRemy Sharp
 
Webapps without the web
Webapps without the webWebapps without the web
Webapps without the webRemy Sharp
 
HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?Remy Sharp
 
codebits 2009 HTML5 JS APIs
codebits 2009 HTML5 JS APIscodebits 2009 HTML5 JS APIs
codebits 2009 HTML5 JS APIsRemy Sharp
 
HTML5 JavaScript APIs
HTML5 JavaScript APIsHTML5 JavaScript APIs
HTML5 JavaScript APIsRemy Sharp
 
iPhone Appleless Apps
iPhone Appleless AppsiPhone Appleless Apps
iPhone Appleless AppsRemy Sharp
 
HTML5 & Friends
HTML5 & FriendsHTML5 & Friends
HTML5 & FriendsRemy Sharp
 
jQuery Loves Developers - SWDC2009
jQuery Loves Developers - SWDC2009jQuery Loves Developers - SWDC2009
jQuery Loves Developers - SWDC2009Remy Sharp
 

Mais de Remy Sharp (18)

HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymore
 
Yearning jQuery
Yearning jQueryYearning jQuery
Yearning jQuery
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)
 
Forget the Web
Forget the WebForget the Web
Forget the Web
 
Interaction Implementation
Interaction ImplementationInteraction Implementation
Interaction Implementation
 
HTML5: huh, what is it good for?
HTML5: huh, what is it good for?HTML5: huh, what is it good for?
HTML5: huh, what is it good for?
 
HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & sockets
 
Developing for Mobile
Developing for MobileDeveloping for Mobile
Developing for Mobile
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with Wings
 
Webapps without the web
Webapps without the webWebapps without the web
Webapps without the web
 
TwitterLib.js
TwitterLib.jsTwitterLib.js
TwitterLib.js
 
HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?
 
codebits 2009 HTML5 JS APIs
codebits 2009 HTML5 JS APIscodebits 2009 HTML5 JS APIs
codebits 2009 HTML5 JS APIs
 
HTML5 JavaScript APIs
HTML5 JavaScript APIsHTML5 JavaScript APIs
HTML5 JavaScript APIs
 
iPhone Appleless Apps
iPhone Appleless AppsiPhone Appleless Apps
iPhone Appleless Apps
 
HTML5 & Friends
HTML5 & FriendsHTML5 & Friends
HTML5 & Friends
 
HTML5 JS APIs
HTML5 JS APIsHTML5 JS APIs
HTML5 JS APIs
 
jQuery Loves Developers - SWDC2009
jQuery Loves Developers - SWDC2009jQuery Loves Developers - SWDC2009
jQuery Loves Developers - SWDC2009
 

Último

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Último (20)

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

DOM Scripting Toolkit - jQuery

  • 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
  • 6. $ • Selectors • DOM elements or raw HTML • “Ready” functions
  • 9. Selectors • “Find something, do something with it” • CSS 1-3 selectors at the core of jQuery • Custom selectors
  • 11. Tricky Selector <div id=“content.block” /> $(‘#content.block’) // won’t work :-( $(‘#content.block’) // will work :-)
  • 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
  • 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 });
  • 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
  • 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