SlideShare una empresa de Scribd logo
1 de 14
Descargar para leer sin conexión
jQuery in 15 minutes
    Torchbox, 7th August 2007
What makes jQuery
      interesting?
• Built around CSS selectors
• Well behaved
 • Doesn’t hijack your global namespace
 • Plays well with other libraries
• API designed with conciseness and
  convenience as the driving factors
The jQuery() function

jQuery('div#intro h2')
jQuery('div.section > p')
jQuery('input:radio')


$('div#intro h2')
jQuery collections
• $('div.section') returns a jQuery collection
• You can call methods on it:
    $('div.section').size() = no. of matched elements
    $('div.section').each(function(div) {
        // Manipulate the div
    }
Manipulating collections
• Most jQuery methods operate on all of the
  matched elements in the collection


  $('div.section').addClass('highlighted')
  $('img.photo').attr('src', '/default.png');
  $('a.foo').html('<em>Click me now!</em>');
  $('p:odd').css('background-color', '#ccc');
Grabbing values
• Some methods return results from the first
  matched element


  var height = $('div#intro').height();
  var src = $('img.photo').attr('src');
  var lastP = $('p:last').html()
Traversing the DOM
• jQuery provides enhanced methods for
  traversing the DOM
  $('div.section').next()
  $('div.section').prev()
  $('div.section').prev('a')
  $('div.section').parent()
  $('div.section').parents()
Handling events
• jQuery provides methods for assigning event
  handlers to elements in a cross-browser way
  $('a').click(function(ev) {
   $(this).css({backgroundColor: 'orange'});
   ev.preventDefault();
  });
Going unobtrusive

$(document).ready(function() {
 alert('The DOM is ready!');
});


$(function() { alert('This is a shortcut') });
Chaining

• Most jQuery methods return another
  jQuery object - often one representing the
  same collection. This means you can chain
  methods together:
  $('div.section').hide().addClass('gone');
Crazy chaining
$('form#login')
   // hide all the labels inside the form with the 'optional' class
   .find('label.optional').hide().end()

  // add a red border to any password fields in the form
  .find('input:password').css('border', '1px solid red').end()

  // add a submit handler to the form
  .submit(function(){
      return confirm('Are you sure you want to submit?');
  });

     From http://www.ibm.com/developerworks/library/x-ajaxjquery.html
Ajax
•   jQuery has excellent support for Ajax
      $('div#intro').load('/some/file.html');

•   More advanced methods include:
      $.get(url, params, callback)
      $.post(url, params, callback)
      $.getJSON(url, params, callback)
      $.getScript(url, callback)
Plugins
• jQuery is extensible through plugins, which
  can add new methods to the jQuery object
  • Form: better form manipulation
  • Dimensions: lots of browser measurements
  • Interface: fancy effects, accordions
  • UI: drag and drop, and more
Further reading


•   http://jquery.com/ - official site
•   http://visualjquery.com/ - useful API reference

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do More
 
Jquery
JqueryJquery
Jquery
 
A Short Introduction To jQuery
A Short Introduction To jQueryA Short Introduction To jQuery
A Short Introduction To jQuery
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
jQuery
jQueryjQuery
jQuery
 
jQuery
jQueryjQuery
jQuery
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
 
jQuery
jQueryjQuery
jQuery
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
jQuery
jQueryjQuery
jQuery
 
jQuery
jQueryjQuery
jQuery
 
D3.js and SVG
D3.js and SVGD3.js and SVG
D3.js and SVG
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
Sprout core and performance
Sprout core and performanceSprout core and performance
Sprout core and performance
 

Similar a jQuery in 15 minutes

Jquery in-15-minutes1421
Jquery in-15-minutes1421Jquery in-15-minutes1421
Jquery in-15-minutes1421palsingh26
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012ghnash
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentationMevin Mohan
 
Learning jquery-in-30-minutes-1195942580702664-3
Learning jquery-in-30-minutes-1195942580702664-3Learning jquery-in-30-minutes-1195942580702664-3
Learning jquery-in-30-minutes-1195942580702664-3luckysb16
 
jQuery (BostonPHP)
jQuery (BostonPHP)jQuery (BostonPHP)
jQuery (BostonPHP)jeresig
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupalkatbailey
 
jQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersjQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersYehuda Katz
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascriptAlmog Baku
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)jeresig
 
Game jump: frontend introduction #1
Game jump: frontend introduction #1Game jump: frontend introduction #1
Game jump: frontend introduction #1Sebastian Pożoga
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Thinqloud
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zLEDC 2016
 

Similar a jQuery in 15 minutes (20)

Jquery in-15-minutes1421
Jquery in-15-minutes1421Jquery in-15-minutes1421
Jquery in-15-minutes1421
 
webstudy jquery
webstudy jquerywebstudy jquery
webstudy jquery
 
jQuery
jQueryjQuery
jQuery
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 
Learning jquery-in-30-minutes-1195942580702664-3
Learning jquery-in-30-minutes-1195942580702664-3Learning jquery-in-30-minutes-1195942580702664-3
Learning jquery-in-30-minutes-1195942580702664-3
 
jQuery (BostonPHP)
jQuery (BostonPHP)jQuery (BostonPHP)
jQuery (BostonPHP)
 
jQuery Presentasion
jQuery PresentasionjQuery Presentasion
jQuery Presentasion
 
Jquery News Packages
Jquery News PackagesJquery News Packages
Jquery News Packages
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
J query training
J query trainingJ query training
J query training
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupal
 
jQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersjQuery Presentation to Rails Developers
jQuery Presentation to Rails Developers
 
jQuery
jQueryjQuery
jQuery
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascript
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)
 
Game jump: frontend introduction #1
Game jump: frontend introduction #1Game jump: frontend introduction #1
Game jump: frontend introduction #1
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to z
 

Más de Simon Willison

Cheap tricks for startups
Cheap tricks for startupsCheap tricks for startups
Cheap tricks for startupsSimon Willison
 
The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)Simon Willison
 
How we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graphHow we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graphSimon Willison
 
Web Services for Fun and Profit
Web Services for Fun and ProfitWeb Services for Fun and Profit
Web Services for Fun and ProfitSimon Willison
 
Tricks & challenges developing a large Django application
Tricks & challenges developing a large Django applicationTricks & challenges developing a large Django application
Tricks & challenges developing a large Django applicationSimon Willison
 
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & FabricAdvanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & FabricSimon Willison
 
How Lanyrd uses Twitter
How Lanyrd uses TwitterHow Lanyrd uses Twitter
How Lanyrd uses TwitterSimon Willison
 
Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approvalSimon Willison
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesSimon Willison
 
Building crowdsourcing applications
Building crowdsourcing applicationsBuilding crowdsourcing applications
Building crowdsourcing applicationsSimon Willison
 
Evented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunniesEvented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunniesSimon Willison
 
Cowboy development with Django
Cowboy development with DjangoCowboy development with Django
Cowboy development with DjangoSimon Willison
 
Crowdsourcing with Django
Crowdsourcing with DjangoCrowdsourcing with Django
Crowdsourcing with DjangoSimon Willison
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 
Web App Security Horror Stories
Web App Security Horror StoriesWeb App Security Horror Stories
Web App Security Horror StoriesSimon Willison
 
Web Security Horror Stories
Web Security Horror StoriesWeb Security Horror Stories
Web Security Horror StoriesSimon Willison
 

Más de Simon Willison (20)

How Lanyrd does Geo
How Lanyrd does GeoHow Lanyrd does Geo
How Lanyrd does Geo
 
Cheap tricks for startups
Cheap tricks for startupsCheap tricks for startups
Cheap tricks for startups
 
The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)
 
Building Lanyrd
Building LanyrdBuilding Lanyrd
Building Lanyrd
 
How we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graphHow we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graph
 
Web Services for Fun and Profit
Web Services for Fun and ProfitWeb Services for Fun and Profit
Web Services for Fun and Profit
 
Tricks & challenges developing a large Django application
Tricks & challenges developing a large Django applicationTricks & challenges developing a large Django application
Tricks & challenges developing a large Django application
 
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & FabricAdvanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
 
How Lanyrd uses Twitter
How Lanyrd uses TwitterHow Lanyrd uses Twitter
How Lanyrd uses Twitter
 
ScaleFail
ScaleFailScaleFail
ScaleFail
 
Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approval
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
 
Building crowdsourcing applications
Building crowdsourcing applicationsBuilding crowdsourcing applications
Building crowdsourcing applications
 
Evented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunniesEvented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunnies
 
Cowboy development with Django
Cowboy development with DjangoCowboy development with Django
Cowboy development with Django
 
Crowdsourcing with Django
Crowdsourcing with DjangoCrowdsourcing with Django
Crowdsourcing with Django
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
Web App Security Horror Stories
Web App Security Horror StoriesWeb App Security Horror Stories
Web App Security Horror Stories
 
Web Security Horror Stories
Web Security Horror StoriesWeb Security Horror Stories
Web Security Horror Stories
 

Último

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Último (20)

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

jQuery in 15 minutes

  • 1. jQuery in 15 minutes Torchbox, 7th August 2007
  • 2. What makes jQuery interesting? • Built around CSS selectors • Well behaved • Doesn’t hijack your global namespace • Plays well with other libraries • API designed with conciseness and convenience as the driving factors
  • 3. The jQuery() function jQuery('div#intro h2') jQuery('div.section > p') jQuery('input:radio') $('div#intro h2')
  • 4. jQuery collections • $('div.section') returns a jQuery collection • You can call methods on it: $('div.section').size() = no. of matched elements $('div.section').each(function(div) { // Manipulate the div }
  • 5. Manipulating collections • Most jQuery methods operate on all of the matched elements in the collection $('div.section').addClass('highlighted') $('img.photo').attr('src', '/default.png'); $('a.foo').html('<em>Click me now!</em>'); $('p:odd').css('background-color', '#ccc');
  • 6. Grabbing values • Some methods return results from the first matched element var height = $('div#intro').height(); var src = $('img.photo').attr('src'); var lastP = $('p:last').html()
  • 7. Traversing the DOM • jQuery provides enhanced methods for traversing the DOM $('div.section').next() $('div.section').prev() $('div.section').prev('a') $('div.section').parent() $('div.section').parents()
  • 8. Handling events • jQuery provides methods for assigning event handlers to elements in a cross-browser way $('a').click(function(ev) { $(this).css({backgroundColor: 'orange'}); ev.preventDefault(); });
  • 9. Going unobtrusive $(document).ready(function() { alert('The DOM is ready!'); }); $(function() { alert('This is a shortcut') });
  • 10. Chaining • Most jQuery methods return another jQuery object - often one representing the same collection. This means you can chain methods together: $('div.section').hide().addClass('gone');
  • 11. Crazy chaining $('form#login') // hide all the labels inside the form with the 'optional' class .find('label.optional').hide().end() // add a red border to any password fields in the form .find('input:password').css('border', '1px solid red').end() // add a submit handler to the form .submit(function(){ return confirm('Are you sure you want to submit?'); }); From http://www.ibm.com/developerworks/library/x-ajaxjquery.html
  • 12. Ajax • jQuery has excellent support for Ajax $('div#intro').load('/some/file.html'); • More advanced methods include: $.get(url, params, callback) $.post(url, params, callback) $.getJSON(url, params, callback) $.getScript(url, callback)
  • 13. Plugins • jQuery is extensible through plugins, which can add new methods to the jQuery object • Form: better form manipulation • Dimensions: lots of browser measurements • Interface: fancy effects, accordions • UI: drag and drop, and more
  • 14. Further reading • http://jquery.com/ - official site • http://visualjquery.com/ - useful API reference