Think jQuery
Upcoming SlideShare
Loading in...5
×
 

Think jQuery

on

  • 3,888 views

 

Statistics

Views

Total Views
3,888
Views on SlideShare
3,888
Embed Views
0

Actions

Likes
3
Downloads
90
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

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

Think jQuery Think jQuery Presentation Transcript

  • 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("p:first")
      • 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. Are 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>