Introduction to jQuery by alekdavis

VIEWS: 869 PAGES: 18

More Info
									Introduction to jQuery


                    Alek Davis
         http://alekdavis.blogspot.com




                       June 2010
jQuery

•   Quick facts
    –     JavaScript library (file) created by John Resig
    –     Open source (MIT and GPL licenses; good for commercial use)
    –     Current version: 1.4.2
    –     Size: ~155 KB (~24 KB minimized)
    –     Browser support: IE 6+, Firefox 2+, Opera 9+, Safari 2+, Chrome
    –     Actively developed
    –     Large and active community
    –     Used by many companies (Google, IBM, Amazon, Dell, Netflix, Intel, …)
    –     Shipped with ASP.NET MVC Framework
    –     Included with Visual Studio 2010 (and later)
    –     24/7 support by Microsoft through Product Support Services (PSS)
•   See also
    –     Learning jQuery @ MIT (presented by John Resig at MIT)
          • More facts, performance benchmarks, key features



2 of 18                                 Introduction to jQuery             6/16/2010
Learning jQuery

•   Web sites
    –     http://jquery.com/ (downloads, docs, tutorials, bug tracker, forums)
    –     http://www.learningjquery.com/ (tips, techniques, tutorials, RSS)
•   Tutorials/articles
    –     jQuery for Absolute Beginners (15 short videos, about 5 minutes each)
    –     An introduction to jQuery (Part 1: The Client Side)
    –     Using jQuery with ASP.NET (Part 2: Making Ajax Callbacks to the Server)
    –     Six Things Every jQuery Developer Should Know by Elijah Manor
•   Books
    –     Learning jQuery: … by Karl Swedberg & Jonathan Chaffer
    –     jQuery Reference Guide by Karl Swedberg & Jonathan Chaffer
    –     jQuery in Action by Bear Bibeault & Yehuda Katz




3 of 18                                   Introduction to jQuery                    6/16/2010
jQuery basics

•   Syntax
    – $('select element').doSomething('info').doSomethingElse('more info');
•   Selectors
    –     $('#txtSearchBox'): element with ID txtSearchBox
    –     $('.SelectedCell'): element(s) with class attribute SelectedCell
    –     $('#userGrid tr:even'): even rows of the element with ID userGrid
    –     $('input:checkbox[id$=\'chkDelete\']'): input element(s) of the type
          checkbox with ID that ends with chkDelete
    –     $('img.ImgLink[id$=\'imgOK\'],img.ImgLink[id$=\'imgCancel\']'): IMG
          element(s) with class attribute ImgLink and ID ending with imgOK or
          imgCancel
•   Animations
    –     $(…).hide()                   $(…).show()
    –     $(…).fadeIn("fast")           $(…).fadeOut("slow")
    –     $(…).slideUp(1000)            $(…).slideDown(5000)
    –     …



4 of 18                                 Introduction to jQuery                   6/16/2010
More jQuery

•   Common operations
    –     $(…).preventDefaults(): prevents default behavior
    –     $(…).attr(): sets/gets attribute value
    –     $(…).css(): sets/gets CSS attribute value
    –     $(…).val(): sets/gets value of a text input element (text box, text area)
    –     $(…).text(): sets/gets text value of an element (span, etc)
    – …
•   Events
    –     $(…).click(function(e){ … }): on click event handler
    –     $(…).keydown(function(e){ … }): on key down event handler
    –     $(…).hover(function(){ … }, function()): on hover (in and out) event handler
    –     $(…).bind("eventX eventY …", …): binds one or more event to event hander
    – …




5 of 18                                 Introduction to jQuery                 6/16/2010
jQuery extras

•   jQuery UI
    – jQuery widgets
      • Handle drag-and-drop, sorting, resizing, selecting
      • Accordion, date picker, dialog, progress bar, slider, tabs controls
      • Effects (color animation, class transitions, theming)
•   Plugins
    – Third party widgets
      • User interface
      • Data manipulation
      • AJAX
      • …
    – See also: Plugins/Authoring
•   See also
    –     http://docs.jquery.com/ (documentation)




6 of 18                                  Introduction to jQuery               6/16/2010
jQuery demo

•   Features
    – Custom search box
      • Auto-show, auto-hide
      • Submit, cancel
      • Buttons and keyboard
      • Input validation




7 of 18                        Introduction to jQuery   6/16/2010
Browsers and tools

•   Firefox
    – Use IE Tab add-on to switch between Firefox and IE views
    – Use Web Developer add-on/toolbar for… lots of things
    – Use Firebug add-on for debugging
      • console.log is your friend
    – Use YSlow add-on to see performance score
•   Chrome
    – Use the built-in Developer Tools menu
•   Internet Explorer
    – Use Fiddler to debug HTTP traffic
    – Use Internet Explorer Developer Toolbar for debugging
    – Use IE7Pro add-on for "everything" else
•   Web tools
    –     jQuery API Browser
    –     Visual jQuery


8 of 18                                Introduction to jQuery    6/16/2010
Using jQuery in a project

•   Options
    – Option 1: Reference distribution source (Google)
      • Pros: Download speed, caching, proximity
      • Cons: External reference
    – Option 2: Make your own copy
      • Pros: Internal reference
      • Cons: Download speed (possibly)




9 of 18                          Introduction to jQuery   6/16/2010
jQuery and IntelliSense

•   The documentation (-vsdoc.js) file
    – Use for documentation only (it’s not functional)
    – If official version is not available (e.g. immediately after release)
      • Generate vsdoc file via InfoBasis JQuery IntelliSense Header Generator
            –   Generated stub file contains no code (only comments, only works wit v.1.3)
•   Usage options
    – If using VS 2008 SP1
      • Install hotfix KB958502 (see Visual Studio patched for better jQuery IntelliSense)
      • Add the vsdoc file to the project; do not reference it in code
      • Vsdoc file must have the same name as the original with –vsdoc suffix
    – If not using VS 2008 SP1 (also see the Resources slide)
      • Add the vsdoc file to the project
      • Wrap the vsdoc file in an invisible control (use appropriate name):
            <asp:Label Visible="false" runat="server">
            <script src="../Scripts/jQuery-1.3.1-vsdoc.js" type="text/javascript" />
            </asp:Label>
           • In JavaScript files, add at the top (use appropriate name):
            /// <reference path="jQuery-1.3.1-vsdoc.js"/>



10 of 18                                      Introduction to jQuery                   6/16/2010
jQuery code

•   Traditional jQuery code
    – Does not work after partial postback
           $(document).ready(function() // or $(function()
           {
             // JavaScript code here
             // …
           });

•   ASP.NET AJAX-specific jQuery
    – Works after partial postback
           // $(function()
           function pageLoad(sender, args)
           {
             // JavaScript code here
             // …
           }
           // });
    – But…


11 of 18                                     Introduction to jQuery   6/16/2010
On pageLoad()

•   pageLoad is not the same as $(document).ready
    – pageLoad is called on initial page load and after every partial postback
    – Can cause repeated event bindings
      • One event (such as click) triggers event handler multiple times
•   What to do?
    – Call unbind before any defining any bindings for an element (selector)
             function pageLoad(sender, args){
               $('a[id$=\'ItemName\']').unbind();
               $('a[id$=\'ItemName\']').click(function(e){…}
             }
           • See $(document).ready() and pageLoad() are not the same! by Dave Ward
    –      Or use live for event binding inside of $(document).ready:
             $(document).ready(function(){
               $('a[id$=\'ItemName\']').live("click", function(e){…});
             });
           • live binds all current and future elements (selectors)
           • live works for most common, but not all event types
           • See jQuery live() and ASP.NET Ajax asynchronous postback by Arnold Matusz



12 of 18                                        Introduction to jQuery                   6/16/2010
Find controls via jQuery

•   If you do not know IDs of elements (e.g. in Repeater)
    – Example: Make sure that check box A gets checked and disabled when
      user checks box B (both check boxes belong to a repeater item and have
      IDs chkA and chkB)
           $('input:checkbox[id$=\'chkB\']').click(function(e)
           {
             var elemID      = $(e.target).attr('id');
             var prefixID    = elemID.replace(/chkB$/i, "");
             var elemIDchkA = "#" + elemID.replace(/chkB$/, "chkA");

             if (this.checked)
             {
               $(elemIDchkA).attr('checked', 'true');
               $(elemIDchkA).attr('disabled', 'true');
             }
             else
               $(elemIDchkA).removeAttr('disabled');
           });




13 of 18                                  Introduction to jQuery       6/16/2010
What is $(this)?

•   this can have different contexts
    – Most common contexts
      • Context #1: JavaScript DOM element
            –    Inside of a callback function (click, hover, …)
           • Context #2: jQuery object
            –    Inside of custom jQuery function
           • Context #3: JavaScript object
            –    Such as an array element

•   What about $(this)?
    –      $(this) converts a DOM object into a jQuery object
           • To convert a jQuery object to a DOM object use:
            –    $(…).get(0) or $(…)[0]

•   See also
    –      What is this? By Mike Alsup
    –      jQuery's this: demystified by Remy Sharp



14 of 18                                      Introduction to jQuery   6/16/2010
Debugging jQuery code

•         Tools
      –        Firebug (Firebug Lite)
               • Just use it
      –        FireQuery
               • Allows injecting jQuery into Web pages that don't have it loaded
      –        FireFinder
               • Finds selectors

•         Articles
      •        How to Debug Your jQuery Code by Elijah Manor




    15 of 18                                  Introduction to jQuery                6/16/2010
What's next?

•   Interesting topics
    –      Client templates in ASP.NET 4.0 AJAX
    –      jQuery plugins
    –      jQuery UI
    –      Internationalization




16 of 18                               Introduction to jQuery   6/16/2010
Videos

•   Presentations/talks/demos/videocasts/samples
    –      Performance Improvements in Browsers by John Resig at Google (92 min)
    –      MIX08 Presentation : Real-World AJAX with ASP.NET Video by Nikhil Kothari (references to
           presentations/demos/talks/samples)
    –      ASP.NET 3.5: Adding AJAX Functionality to an Existing ASP.NET Page by Todd Miranda
    –      ASP.NET Podcast Show #128 - AJAX with jQuery by Wallace B. (Wally) McClure




17 of 18                                      Introduction to jQuery                       6/16/2010
Resources

•   JavaScript
    –      Create Advanced Web Applications With Object-Oriented Techniques by Ray Djajadinata
•   jQuery
    –      The Grubbsian: jQuery (a few interesting articles)
    –      jQuery for JavaScript programmers by Simon Willison
•   jQuery, ASP.NET, AJAX
    –      Tales from the Evil Empire by Bertrand Le Roy
    –      Blog - Microsoft .NET, ASP.NET, AJAX and more by Visoft, Inc.
•   IntelliSense
    –      JQuery 1.3 and Visual Studio 2008 IntelliSense by James Hart
    –      (Better) JQuery IntelliSense in VS2008 by Brad Vin
    –      JScript IntelliSense FAQ
•   Rich Internet Applications (RIA)
    –      Developing rich Internet applications (RIA) by Alek Davis (links to many samples)
•   CSS
    –      Which CSS Grid Framework Should You Use for Web Design?


18 of 18                                       Introduction to jQuery                6/16/2010

								
To top