SlideShare a Scribd company logo
Think jQuery 06/02/09 By Ying Zhang
What is jQuery A javascript library that doesn’t intermingle with HTML (unobtrusive) Uses concise syntax to speed up DOM programming Relatively new: released on BarCamp NYC on Jan 2006 Picking up momentum recently Allows you to write less, do more
Why use jQuery Selector syntax is based on CSS (created by people who understand CSS) jQuery(‘h#header span’) $(“div.neato > input.radio”) Lightweight 15kb compressed 29kb packed Good documentation Great community Mailing list gets 10-20 conversations per day Tons of plugins and growing Works well with other Javascript libraries Good browser compatibility IE 6.0+, FF 2+, Safari 2.0+, Opera 9.0+  Integrated with Firebug console.log($(“div.jQuery”)) Write less, do more
jQuery crash course $(“div.section”) returns a jQuery collection obj Assign it to a variable var mySection = $(“div.section”); But remember, it’s a jQuery obj not a DOM obj, therefore use $(mySection) to interact with it Select Info $(mySection).children(&quot;p:first&quot;) Traverse $(mySection).each(function(i,div) { // blah }); Manipulate $(mySection).html(“<span>some text</span>”); $(mySection).append(“<span>some text</span>”); $(&quot;<span/>&quot;).html(&quot;some text&quot;).appendTo(mySelection); Bind Events $(mySection).click(function() {  $(“div#someOtherDiv).toggle();  }); jQuery  documentation  is categorized this way
Chaining Since most jQuery methods return an object, you may chain methods together $(“<form/>”) .addClass(“form”) .attr(“id”, “unique”) .find(“input.firstName”).removeClass(“formInput”) .submit(function() { return confirm(“Are you sure?” }) .appendTo(“div#parentWrapper”);
Going unobtrusive $(document).ready(function() { alert(‘DOM is ready’); }); Replaces non-lib js code: window.onload=function() { alert(‘DOM is ready’); } Or <body onload=“alert(‘DOM is ready’)”> But it’s so much superior!!!
Going unobtrusive cont. If you have two scripts that required page onload calls Traditional javascript: loadClock.js window.onload=loadClock; loadOther.js window.onload=loadOther; But it will not work because loadOther will override loadClock. So you must either create another js that contains window.onload=function() {loadClock(); loadOther()} or do <body onload=“loadClock();loadOther()”> in your HTML It requires you to have knowledge that both loadClock and loadOther need to be called on page load jQuery loadClock.js $(function() { // code for your clock loading }); loadOther.js $(function() { // code for your other loading }); Include both scripts in your HTML and you are done Nothing needs to be aware of both loadClock and loadOther
Syntax notes Different versions of the same thing $(document).ready(function() {}); jQuery(function($){}); $(function() {}); jQuery = $ $(“div.section”) is the same as jQuery(“div.section”)
jQuery one liners Issue: I cannot correct table border=“1” with CSS $(“table[border!=‘0’]”).attr(“border”, “0”); Issue: I want to know if the user doesn’t check any checkboxes in a group $(“.groupWrapper :checked”).length == 0 Issue: Put focus on the first input field when page loads $(“#wrapper :input:eq(0)”).focus(); Issue: ‘Clear page’ button needs to clear values off all of the input fields on the screen $(“input#clearPage”).click(function() { $(“:input”).val(“”); });
Let’s write something Problem Have a list of checkboxes for a particular field The choices are persisted to the backend The page may be loaded with previous selection or no selection If all left unchecked, prevent user from moving on If check fields are pre-populated & the user makes changes to the selections, warn user the selection has been updated
Let’s write something cont. Basic Tactic On page load save checked checkboxes into a global variable  checked On form submit save checked checkboxes into a local variable  onSubmitChecked compare it to  checked  and do more logic to determine if the submission should be allowed
The HTML <form action=&quot;#&quot;> <h2>Distributions</h2> <ul id=&quot;distributions&quot;> <li><input type=&quot;checkbox&quot; id=&quot;checkbox1&quot;><label for=&quot;checkbox1&quot;> Distribution 1</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox2&quot;><label for=&quot;checkbox2&quot;> Distribution 2</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox3&quot;><label for=&quot;checkbox3&quot;> Distribution 3</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox4&quot;><label for=&quot;checkbox4&quot;> Distribution 4</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox5&quot;><label for=&quot;checkbox5&quot;> Distribution 5</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox6&quot;><label for=&quot;checkbox6&quot;> Distribution 6</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox7&quot;><label for=&quot;checkbox7&quot;> Distribution 7</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox8&quot;><label for=&quot;checkbox8&quot;> Distribution 8</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox9&quot;><label for=&quot;checkbox9&quot;> Distribution 9</label></li> </ul> <input type=&quot;submit&quot; id=&quot;submit&quot; value=&quot;Submit&quot; /> </form>
The jQuery script <script type=&quot;text/javascript&quot;> var checked; jQuery(function($){ checked = $(&quot;ul#distributions :checked&quot;); $(&quot;#submit&quot;).click(function() { return validForm(); }); }); function validForm() { var valid = true; var onSubmitChecked = $(&quot;ul#distributions :checked&quot;); // if nothing is checked, alert and return false if(onSubmitChecked.length == 0) { alert(&quot;Please select at least one distribution!&quot;); valid = false; } else { var warn = false; // if the length doesn't match, then the checked has been updated
The jQuery script cont. if(checked.length != onSubmitChecked.length) { warn = true; } else { // if all the checked ones match the checked ones in onSubmitChecked $(checked).each(function(i,checkbox) { var onSubmitCheckbox = $(onSubmitChecked).get(i); //if($(this).attr(&quot;id&quot;) != $(onSubmitCheckbox).attr(&quot;id&quot;)) { if($(this).next().text() != $(onSubmitCheckbox).next().text()) { warn = true; return false; // breaks out of the for each loop } }); } if(warn) { valid = confirm(&quot;Selected distributions have been updated.\n\nAre you sure you wish to continue?&quot;); } } return valid; } </script>
Cool plugins Hotkeys  – bind anything to key shortcuts Textarea  Resizer   – drag and resize text input area http:// jquery.com/demo/thickbox /  – modal window jQuery  Ajax Form jQuery  Validation (Coz I contributed)  DodosPicklist So many more  http://plugins.jquery.com/ Or just search Google for jQuery plugins
Extending jQuery Writing a jQuery plugin jQuery.fn.functionName = function(param) { } jQuery object vs. DOM object $(this) vs this $(this)[0] gets the DOM object Optional parameters jQuery.fn.multiSelect = function(to, options) { } options = $.extend({  sortOptions: true,  autoSubmit: true }, options); $(“#example”).multiSelect(“#blah”, {  sortOptions: false });
jQuery vs. other libraries Sites/projects that use jQuery Wordpress – I’d argue it is the best open source blog script on the web Firefox  – Take a peek at the source code RichFaces –  jQuery  is included with the framework Oracle –  Fan  blog  entry? Vs. Prototype Now Ruby on Rails come prepackaged with it script.aculo.us I do not see an ever growing plugins list The  demos  hardly changed since I visited two years ago If interested,  watch this slide Maybe prototype has more OOP support?  But  jQuery  has basic support too
jQuery Resources (Duh) http://jquery.com http://remysharp.com/jquery-api / (General) http://groups.google.com/group/jquery -en (Plugin) http://groups.google.com/group/jquery-plugins http://www.learningjquery.com/ (Search jQuery) http://www.slideshare.net / Use jQuery without download: <!-- jQuery packed --> <script type=&quot;text/javascript&quot; src=&quot;http://code.jquery.com/jquery-latest.js&quot;> </script>

More Related Content

PPT
JavaScript: Ajax & DOM Manipulation
PPT
Eugene Andruszczenko: jQuery
PPTX
FYBSC IT Web Programming Unit III Javascript
PPT
Javascript: Ajax & DOM Manipulation v1.2
PPT
Grails Introduction - IJTC 2007
PPT
KMUTNB - Internet Programming 4/7
PPTX
FYBSC IT Web Programming Unit III Core Javascript
PPT
JavaScript & Dom Manipulation
JavaScript: Ajax & DOM Manipulation
Eugene Andruszczenko: jQuery
FYBSC IT Web Programming Unit III Javascript
Javascript: Ajax & DOM Manipulation v1.2
Grails Introduction - IJTC 2007
KMUTNB - Internet Programming 4/7
FYBSC IT Web Programming Unit III Core Javascript
JavaScript & Dom Manipulation

What's hot (20)

PPTX
FYBSC IT Web Programming Unit III Document Object
PPT
Scripting The Dom
PPT
Web Performance Tips
DOC
Basics java scripts
PPTX
FYBSC IT Web Programming Unit IV PHP and MySQL
RTF
Java scripts
PPT
Javascript 2009
PPT
Java script Learn Easy
PDF
Javascript
PPT
Java script -23jan2015
ZIP
Fundamental JavaScript [In Control 2009]
PPTX
Javascript
PPTX
Java Script
PPTX
Introduction to AJAX and DWR
PPT
JavaScript Workshop
PPT
Pragmatics of Declarative Ajax
PPT
Java script
PDF
Domain Driven Design and Hexagonal Architecture with Rails
PPT
JavaScript
PPTX
1. java script language fundamentals
FYBSC IT Web Programming Unit III Document Object
Scripting The Dom
Web Performance Tips
Basics java scripts
FYBSC IT Web Programming Unit IV PHP and MySQL
Java scripts
Javascript 2009
Java script Learn Easy
Javascript
Java script -23jan2015
Fundamental JavaScript [In Control 2009]
Javascript
Java Script
Introduction to AJAX and DWR
JavaScript Workshop
Pragmatics of Declarative Ajax
Java script
Domain Driven Design and Hexagonal Architecture with Rails
JavaScript
1. java script language fundamentals
Ad

Similar to Think jQuery (20)

PPT
jQuery Presentation - Refresh Events
PPT
jQuery Tips Tricks Trivia
PPTX
jQuery
PPT
GWT Extreme!
PPT
jQuery Fundamentals
PPTX
J Query Presentation
PPTX
Html, CSS, Javascript, Jquery, Meteor應用
PPT
eXo SEA - JavaScript Introduction Training
PPT
PPT
jQuery and_drupal
ODP
ActiveWeb: Chicago Java User Group Presentation
PPT
CTS Conference Web 2.0 Tutorial Part 2
PPT
An Introduction to Ajax Programming
PPTX
jQuery PPT
PPT
Javascript
ODP
JavaScript Web Development
PDF
Introduction to Javascript programming
PPTX
Javascript
PPT
J Query Public
PPT
Building Smart Workflows - Dan Diebolt
jQuery Presentation - Refresh Events
jQuery Tips Tricks Trivia
jQuery
GWT Extreme!
jQuery Fundamentals
J Query Presentation
Html, CSS, Javascript, Jquery, Meteor應用
eXo SEA - JavaScript Introduction Training
jQuery and_drupal
ActiveWeb: Chicago Java User Group Presentation
CTS Conference Web 2.0 Tutorial Part 2
An Introduction to Ajax Programming
jQuery PPT
Javascript
JavaScript Web Development
Introduction to Javascript programming
Javascript
J Query Public
Building Smart Workflows - Dan Diebolt
Ad

Recently uploaded (20)

PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
KodekX | Application Modernization Development
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Approach and Philosophy of On baking technology
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPT
Teaching material agriculture food technology
PPTX
Cloud computing and distributed systems.
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Spectroscopy.pptx food analysis technology
Review of recent advances in non-invasive hemoglobin estimation
Unlocking AI with Model Context Protocol (MCP)
The Rise and Fall of 3GPP – Time for a Sabbatical?
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
KodekX | Application Modernization Development
The AUB Centre for AI in Media Proposal.docx
Understanding_Digital_Forensics_Presentation.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Approach and Philosophy of On baking technology
MYSQL Presentation for SQL database connectivity
Building Integrated photovoltaic BIPV_UPV.pdf
Programs and apps: productivity, graphics, security and other tools
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Teaching material agriculture food technology
Cloud computing and distributed systems.
sap open course for s4hana steps from ECC to s4
Dropbox Q2 2025 Financial Results & Investor Presentation
Machine learning based COVID-19 study performance prediction
Spectroscopy.pptx food analysis technology

Think jQuery

  • 1. Think jQuery 06/02/09 By Ying Zhang
  • 2. What is jQuery A javascript library that doesn’t intermingle with HTML (unobtrusive) Uses concise syntax to speed up DOM programming Relatively new: released on BarCamp NYC on Jan 2006 Picking up momentum recently Allows you to write less, do more
  • 3. Why use jQuery Selector syntax is based on CSS (created by people who understand CSS) jQuery(‘h#header span’) $(“div.neato > input.radio”) Lightweight 15kb compressed 29kb packed Good documentation Great community Mailing list gets 10-20 conversations per day Tons of plugins and growing Works well with other Javascript libraries Good browser compatibility IE 6.0+, FF 2+, Safari 2.0+, Opera 9.0+ Integrated with Firebug console.log($(“div.jQuery”)) Write less, do more
  • 4. jQuery crash course $(“div.section”) returns a jQuery collection obj Assign it to a variable var mySection = $(“div.section”); But remember, it’s a jQuery obj not a DOM obj, therefore use $(mySection) to interact with it Select Info $(mySection).children(&quot;p:first&quot;) Traverse $(mySection).each(function(i,div) { // blah }); Manipulate $(mySection).html(“<span>some text</span>”); $(mySection).append(“<span>some text</span>”); $(&quot;<span/>&quot;).html(&quot;some text&quot;).appendTo(mySelection); Bind Events $(mySection).click(function() { $(“div#someOtherDiv).toggle(); }); jQuery documentation is categorized this way
  • 5. Chaining Since most jQuery methods return an object, you may chain methods together $(“<form/>”) .addClass(“form”) .attr(“id”, “unique”) .find(“input.firstName”).removeClass(“formInput”) .submit(function() { return confirm(“Are you sure?” }) .appendTo(“div#parentWrapper”);
  • 6. Going unobtrusive $(document).ready(function() { alert(‘DOM is ready’); }); Replaces non-lib js code: window.onload=function() { alert(‘DOM is ready’); } Or <body onload=“alert(‘DOM is ready’)”> But it’s so much superior!!!
  • 7. Going unobtrusive cont. If you have two scripts that required page onload calls Traditional javascript: loadClock.js window.onload=loadClock; loadOther.js window.onload=loadOther; But it will not work because loadOther will override loadClock. So you must either create another js that contains window.onload=function() {loadClock(); loadOther()} or do <body onload=“loadClock();loadOther()”> in your HTML It requires you to have knowledge that both loadClock and loadOther need to be called on page load jQuery loadClock.js $(function() { // code for your clock loading }); loadOther.js $(function() { // code for your other loading }); Include both scripts in your HTML and you are done Nothing needs to be aware of both loadClock and loadOther
  • 8. Syntax notes Different versions of the same thing $(document).ready(function() {}); jQuery(function($){}); $(function() {}); jQuery = $ $(“div.section”) is the same as jQuery(“div.section”)
  • 9. jQuery one liners Issue: I cannot correct table border=“1” with CSS $(“table[border!=‘0’]”).attr(“border”, “0”); Issue: I want to know if the user doesn’t check any checkboxes in a group $(“.groupWrapper :checked”).length == 0 Issue: Put focus on the first input field when page loads $(“#wrapper :input:eq(0)”).focus(); Issue: ‘Clear page’ button needs to clear values off all of the input fields on the screen $(“input#clearPage”).click(function() { $(“:input”).val(“”); });
  • 10. Let’s write something Problem Have a list of checkboxes for a particular field The choices are persisted to the backend The page may be loaded with previous selection or no selection If all left unchecked, prevent user from moving on If check fields are pre-populated & the user makes changes to the selections, warn user the selection has been updated
  • 11. Let’s write something cont. Basic Tactic On page load save checked checkboxes into a global variable checked On form submit save checked checkboxes into a local variable onSubmitChecked compare it to checked and do more logic to determine if the submission should be allowed
  • 12. The HTML <form action=&quot;#&quot;> <h2>Distributions</h2> <ul id=&quot;distributions&quot;> <li><input type=&quot;checkbox&quot; id=&quot;checkbox1&quot;><label for=&quot;checkbox1&quot;> Distribution 1</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox2&quot;><label for=&quot;checkbox2&quot;> Distribution 2</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox3&quot;><label for=&quot;checkbox3&quot;> Distribution 3</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox4&quot;><label for=&quot;checkbox4&quot;> Distribution 4</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox5&quot;><label for=&quot;checkbox5&quot;> Distribution 5</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox6&quot;><label for=&quot;checkbox6&quot;> Distribution 6</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox7&quot;><label for=&quot;checkbox7&quot;> Distribution 7</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox8&quot;><label for=&quot;checkbox8&quot;> Distribution 8</label></li> <li><input type=&quot;checkbox&quot; id=&quot;checkbox9&quot;><label for=&quot;checkbox9&quot;> Distribution 9</label></li> </ul> <input type=&quot;submit&quot; id=&quot;submit&quot; value=&quot;Submit&quot; /> </form>
  • 13. The jQuery script <script type=&quot;text/javascript&quot;> var checked; jQuery(function($){ checked = $(&quot;ul#distributions :checked&quot;); $(&quot;#submit&quot;).click(function() { return validForm(); }); }); function validForm() { var valid = true; var onSubmitChecked = $(&quot;ul#distributions :checked&quot;); // if nothing is checked, alert and return false if(onSubmitChecked.length == 0) { alert(&quot;Please select at least one distribution!&quot;); valid = false; } else { var warn = false; // if the length doesn't match, then the checked has been updated
  • 14. The jQuery script cont. if(checked.length != onSubmitChecked.length) { warn = true; } else { // if all the checked ones match the checked ones in onSubmitChecked $(checked).each(function(i,checkbox) { var onSubmitCheckbox = $(onSubmitChecked).get(i); //if($(this).attr(&quot;id&quot;) != $(onSubmitCheckbox).attr(&quot;id&quot;)) { if($(this).next().text() != $(onSubmitCheckbox).next().text()) { warn = true; return false; // breaks out of the for each loop } }); } if(warn) { valid = confirm(&quot;Selected distributions have been updated.\n\nAre you sure you wish to continue?&quot;); } } return valid; } </script>
  • 15. Cool plugins Hotkeys – bind anything to key shortcuts Textarea Resizer – drag and resize text input area http:// jquery.com/demo/thickbox / – modal window jQuery Ajax Form jQuery Validation (Coz I contributed) DodosPicklist So many more http://plugins.jquery.com/ Or just search Google for jQuery plugins
  • 16. Extending jQuery Writing a jQuery plugin jQuery.fn.functionName = function(param) { } jQuery object vs. DOM object $(this) vs this $(this)[0] gets the DOM object Optional parameters jQuery.fn.multiSelect = function(to, options) { } options = $.extend({ sortOptions: true, autoSubmit: true }, options); $(“#example”).multiSelect(“#blah”, { sortOptions: false });
  • 17. jQuery vs. other libraries Sites/projects that use jQuery Wordpress – I’d argue it is the best open source blog script on the web Firefox – Take a peek at the source code RichFaces – jQuery is included with the framework Oracle – Fan blog entry? Vs. Prototype Now Ruby on Rails come prepackaged with it script.aculo.us I do not see an ever growing plugins list The demos hardly changed since I visited two years ago If interested, watch this slide Maybe prototype has more OOP support? But jQuery has basic support too
  • 18. jQuery Resources (Duh) http://jquery.com http://remysharp.com/jquery-api / (General) http://groups.google.com/group/jquery -en (Plugin) http://groups.google.com/group/jquery-plugins http://www.learningjquery.com/ (Search jQuery) http://www.slideshare.net / Use jQuery without download: <!-- jQuery packed --> <script type=&quot;text/javascript&quot; src=&quot;http://code.jquery.com/jquery-latest.js&quot;> </script>