Introduction To jQuery
Upcoming SlideShare
Loading in...5

Introduction To jQuery



Westlaw Monthly UI Meeting, 12/08

Westlaw Monthly UI Meeting, 12/08



Total Views
Views on SlideShare
Embed Views



8 Embeds 72 40 14 7 6 2 1 1 1



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.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
  • @rohitjoshirox yap.... :)
    Are you sure you want to
    Your message goes here
  • best jquery slides I have ever seen . Thumbs up :)
    Are you sure you want to
    Your message goes here
  • great tutorial...10 thumbs up from me
    Are you sure you want to
    Your message goes here
  • Its the great one; made it so clear to understand and very very interesting to learn by this presentation. thanks a huge Dave!!
    Are you sure you want to
    Your message goes here
  • wow, thx, i'll take a look of your document, hopes it will do good for me :)
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment
  • Meant as a primer Entice you to learn more yourself

Introduction To jQuery Introduction To jQuery Presentation Transcript

  • Introduction To jQuery Dave Berthiaume Thomson Reuters Westlaw Web2 UI Meeting December 2, 2008
    • Open source JavaScript library/framework
    • Created by John Resig in Jan. 2006
    • Mantra: “Faster, smaller and more extensible”
    • Cross-browser compatible
      • IE 6+, Firefox 2+, Safari 2.0+, Opera 9+
    • Fully supported by Microsoft as of Oct 2008 (with Intellisense)
    • Very small footprint
      • 95k development version (uncompressed)
      • 54k (minified)
      • 19k (minified and gzipped)
    What is jQuery?
    • Built with plug-in architecture
    • Easy to learn / use
    • Chaining methods
    • Unobtrusive Javascript
    • CSS v1-3 compatible
    • Namespacing (plays nice with ASP.NET AJAX)
    • Great docs and community
    • Designed to change the way you write Javascript
    What is jQuery? View slide
  • Who’s Using It? And many, many, more…
    • Google
    • Dell
    • Microsoft
    • CBS
    • NBC
    • Major League Baseball
    • Amazon
    • Bank of America
    • Mozilla
    • Netflix
    • Digg
    • Wordpress
    View slide
    • jQuery() function
      • Everything starts with a call to jQuery()
      • Since it’s called so often, the $ variable is set up as an alias to jQuery()
    • Basic structure:
      • FindSomething.DoSomething
      • $(SomethingToFind).DoSomething();
    How Does It work?
    • To find something, we can use common CSS syntax:
      • $(css selector)
      • This is known as a “selector”
      • Returns a jQuery object containing an array of elements that match the selector
      • The returned jQuery object is known as a “collection”, “wrapper” or “wrapped set”
    • The returned object contains a number of predefined methods that can act on the group of elements returned by selector
    Selector Basics
    • $(‘img’)
      • Selects all images
    • $(‘p a’)
      • Selects all links nested under a paragraph
    • $(‘div.myClass’)
      • Selects all divs with a class of “myClass”
    • $(‘#myElement’)
      • Selects element with an id of “myElement”
    • $(‘#nav li.current a’)
      • Selects all links under any list item with class=“current” that exist under the “nav” element
    Simple Selector Examples
  • Custom Selectors These are just a few of the 20+ available :checkbox Selects checkboxes :checked Selects checkboxes or radio buttons that are checked :contains(foo) Selects elements containing the text “foo” :disabled Selects disabled form elements :header Selects elements that are headers (<h1>, etc) :input Selects form elements (input, select, textarea, button) :not Negates the specified filter :selected Selects option elements that are selected :submit Selects submit buttons
    • :checkbox:checked:enabled
      • Selects checkboxes that are enabled and checked
    • input:not(:checkbox)
      • Selects non-checkbox <input> elements
    • div p:not(:hidden)
      • Selects all visible <p> elements nested under a div
    Using Custom Selectors
  • Selecting By Position
    • p:odd
      • Returns every odd paragraph element
    • li:last-child
      • Returns last item of each list (last child of parent element)
    • td:eq(2)
      • Returns third table cell
    • Selectors start counting from 0 (except :nth-child , which starts from 1 for CSS compatibility)
    :first :only-child :even and :odd :last :nth-child(n) :eq(n) :first-child :nth-child(even|odd) :gt(n) :last-child :nth-child(Xn+Y) :lt(n)
  • More Selector Examples Powerful stuff! $(‘li:last’) Selects last list item $(‘tr:nth-child(1)’) Selects the first row of each table $(‘tr:nth-child(even)') Selects even numbered table rows $(‘body > div:has(a)’) Selects direct <div> children of <body> containing links $(‘img[alt]’) Selects images with ALT attribute $(‘a[href*]’) Matches all <a> elements that reference the jQuery site $(‘a[href$=pdf]’) Selects links to PDF files $(‘a[href^=https://]’) Selects all links starting with “https://”
    • Can leverage your knowledge of CSS selectors to get up and running fast
    • Learn about the more advanced selectors jQuery supports:
    Selectors Summary
  • Selectors Demo
    • Once we have our collection, we can execute jQuery commands on it:
    • $(‘div.hideMe’).hide();
      • All divs with a class of “hideMe” will be faded out and become hidden
    • One of the most powerful features of jQuery is chaining
    • jQuery commands (when finished with their action) return the same group of elements, ready for another action
    • $(‘div.hideMe’).hide().addClass(‘removed’);
      • After the divs are hidden, we give them all a class “removed”
    • DOM operations can be expensive. No need to loop over elements- All done behind the scenes
    • Chains can continue indefinitely
    • Get text:
      • $(‘span#msg’).text();
    • Set text:
      • $(‘span#msg’).text(‘The thing was updated’);
    • Get HTML (of first matched element):
      • $(‘div.intro’).html();
    • Set HTML:
      • $(‘div.intro’).html(‘<em>Look, HTML</em>’);
    • Get value (for first matching element):
      • var href = $(‘a.nav’).attr(‘href’);
    • Set value:
      • $(‘a.nav’).attr(‘href’,’ ’);
      • $(‘a.nav’).attr({
      • ‘ href’: ‘ ’,
      • ‘ id’: ‘westlaw’ } );
    • Remove attribute:
      • $(‘#intro’).removeAttr(‘id’);
    • attr() also accepts a function:
      • $(‘*’).attr(‘title’, function(index) {
      • return ‘I am element ‘ + index +
      • ‘ with an id of ‘
      • });
      • Runs through all elements on the page, setting the title attribute on each
    • $(‘#intro’).addClass(‘highlighted’);
    • $(‘#intro’).removeClass(‘highlighted’);
    • $(‘#intro’).toggleClass(‘highlighted’);
    • $(‘div’).hasClass(‘highlighted’);
      • True if at least 1 element has the class
    • $(‘p’).css(‘font-size’, ‘20px’);
    • $(‘p’).css({‘font-size’:’20px’, ‘color’:’red’});
    • css() also accepts a function:
      • $(‘div.expandable’).css(‘width’, function() {
      • return $(this).width() + 20 + ‘px’;
      • });
      • Expands the width of all selected elements by 20px
    • More on “this” later
    • width()
    • height()
      • Replacement for style.width , style.height
      • Computes and returns size of element
      • Return numbers instead of strings
    • width(value)
    • height(value)
      • $(‘’).width(500); is same as:
      • $(‘’).css(‘width’, ‘500px’);
    Height and Width
    • You can treat collections as arrays:
      • $(‘div.myClass’).length = number of matched elements
      • $(‘div.myClass’)[0] = the first <div> in the collection
    • Or you can call methods on collections:
      • $(‘div.myClass’).size() = number of matched elements
      • $(‘div.myClass’).get(0) = the first <div> in the collection
    Collections As Arrays
    • Adds elements to the collection:
    • $(‘img[alt]’).addClass(‘thickBorder’)
    • .add(‘img[title]’)
    • .addClass(‘seeThrough’)
    • Can also be used to add new elements:
      • $(‘p’).add(‘<div>Hi there!</div>’)
    • This adds elements to the collection , not the DOM
    The add() Method
    • Returns a subset of the wrapped set, based on position of elements within the set (zero-based)
    • Returns a new set
    • $(‘*’).slice(2,3);
      • Creates new set containing only the third element on the page
    • $(‘*’).slice(0,4);
      • Creates new set containing the first four elements on the page
    • $(‘*’).slice(4);
      • Creates new set containing all but the first four elements on the page
    The slice() Method
    • Filters out elements from the collection
    • Can accept a selector or a function as a parameter
    • Selector as parameter:
    • $(‘img’).addClass(‘seeThrough’)
    • .filter(‘[title*=dog]’)
    • .addClass(‘thickBorder’)
      • Reduces set to images with a title attribute containing ‘dog’
    The filter() Method
    • When passed a function, invokes that function for each wrapped element and removes any whose method invocation returns false .
    • $(‘td’).filter(function(){
    • return this.innerHTML.match(/^d+$/)
    • })
      • Creates a collection of <td> elements that contain a numeric value
    • “ this” is the current element being processed
    The filter() Method
    • Searches through a collection, returns a new set that contains all elements that match a passed selector expression
    • Powerful when combined with chaining:
    • $(‘p’).find(‘span’).fadeIn();
      • Starts with all paragraphs and searches for descendant <span> elements
      • Same as $(‘p span’)
    • Can also be used with variable:
    • var mySet = $(‘p’);
    • mySet.find(‘span’);
    The find() Method
    • filter() selects a subset of the already selected elements:
      • $('td').filter(expr)
        • Removes any <td> elements that don't match the filter criteria
    • find() selects a set of elements that are descendants of the already selected elements
      • $('td').find('span')
        • Will find <span> elements inside <td> elements
        • Functionally similar to $('td span');
    filter() vs find()
    • Easiest way to inspect or modify the component elements of a matched set
    • Traverses matched set invoking the passed iterator function for each
    • Can be used to easily set a property value onto all elements in a collection
    • $(‘img’).each(function(n){
    • this.alt=‘This is image[‘ + n
    • + ‘] with an id of ‘ +;
    • });
    The each() Command
    • Can also be used to collect all values for a specific property into an array:
    • var allAlts = new Array();
    • $(‘img’).each(function(){
    • allAlts.push(this.alt);
    • });
    • To obtain property from just a single element, remember set can be treated like a Javascript array:
    • var altVal = $(‘#myImg’)[0].alt;
    The each() Command
    • You can get new wrapped sets from existing sets based on relationships
    • These methods return a new collection, leaving the original set unchanged:
    • $(‘div:first’).nextAll().addClass(‘after’);
      • Locates first <div> on page, creates new collection of all siblings that follow, and assigns them a class
    Relationships children() nextAll() prev() contents() parent() prevAll() next() parents() siblings()
  • Commands Demo
    • $(‘p’).each(function() {
    • var id =;
    • var $this = $(this);
    • var images = $this.find(‘img’);
    • });
    • “ this” is a DOM element
    • Wrap in $() to make it a jQuery object
    • Now you can issue jQuery commands
    • $ prefix on variable name is a common convention to indicate it’s a jQuery object
    What is “this”?
    • The $ function is versatile enough to perform many duties
    • We can create DOM elements on the fly by passing the $() function a string that contains the HTML markup for those elements
    • To create a new paragraph element:
      • $(‘<p>Hi there!</p>’)
      • Creates a “disembodied” element that is not part of the DOM
    Creating New Elements
    • Use one of jQuery’s DOM manipulation functions to attach new elements to the correct element
      • <p id=‘foo’>Follow me!</p>
      • $(‘<p>Hi there!</p>’).insertAfter(‘#foo’);
      • Result:
        • Follow me!
        • Hi there!
    Add New Element To DOM append() insertAfter() before() appendTo() prepend() insertBefore() insert() prependTo()
    • Some chains can generate multiple sets:
    • $(‘img’).clone().appendTo(‘#somewhere’);
      • In this example, clone() creates a second set
      • This is the set that appendTo() operates on
    • What if we want to apply a command to the original set? You can’t tack it onto the existing chain.
    Managing Chains
    • The end() method, when used in a jQuery chain, will back up to a previous wrapped set and return it as a value
    • Subsequent operations will apply to the previous set
    • $(‘img’).clone().appendTo(‘#somewhere’)
    • .end().addClass(‘beenCloned’);
    • Without the end() command, addClass() would have operated on the set of clones
    The end() Command
    • Establish event handlers on DOM elements by using the bind() command:
    • $(‘img’).bind(‘click’,function(event) {
    • alert(‘Hi there!’);
    • });
    • To remove all bindings:
    • $(‘img’).unbind(‘click’);
    Event Model
    • jQuery provides shortcut commands to these specific event handlers:
    Specific Event Binding $(‘img’).click(function(event) { alert(‘Hi there!’); }); blur focus mousedown resize change keydown mousemove scroll click keypress mouseout select dblclick keyup mouseover submit error load mouseup unload
    • Cancel a default action and prevent it from bubbling:
      • $(‘form’).bind(‘submit’, function() {
      •   return false; 
      • })
    • Cancel only the default action:
      • $(‘form’).bind(‘submit’, function(event){    event.preventDefault();  });
    • Stop only an event from bubbling:
      • $(‘form’).bind(‘submit’, function(event){    event.stopPropagation();  });
    Event Propagation
    • trigger() method:
      • $(‘:submit’).trigger(‘click’);  
    • Shortcut methods:
      • $(‘:submit’).click();
    • jQuery also supports custom events
    Triggering Event Handlers blur click focus select submit
    • window.onload fires after :
      • DOM is fully initialized
      • Images are loaded
      • External resources are loaded
      • Page is displayed in the browser
    • Can cause noticeable delays since startup scripts can be “blocked” from execution
    Startup Script
    • jQuery provides a way to execute code immediately after the DOM has been initialized:
    • $(document).ready(function() {
    • alert(‘Document is ready’);
    • });
    • Shorthand form:
    • $(function() {
    • alert(‘Document is ready’);
    • });
    Document Ready
    • $(function() {
    • alert(‘Step 1’);
    • });
    • $(function() {
    • alert(‘Step 2’);
    • });
    • Can be used multiple times within the HTML document
    • Multiple instances will execute in the order they are defined
    Document Ready
    • Bad practice:
    • <a onclick=“doIt()” href=“foo.html”>Click!</a>
    • Good practice:
    • <a href=“foo.html” class=“doIt”>Click!</a>
    • $(‘a.doIt’).click(function(){
    • // Do something here
    • alert(‘You did something. Woo-Hoo!’);
    • });
    Unobtrusive Javascript
  • Zebra Stripe Demo
    • Some visibility functionality is built into core jQuery:
        • $(‘h1’).hide();
        • $(‘h1’).show();
        • $(‘h1’).toggle();
    • Works by setting “display” to “none” or “block”
    Show / Hide Elements
    • The hide/show/toggle commands are more complex than you might think
    • Calling them with no parameters instantaneously shows/hides the elements
    • Passing a “speed” provides a gradual animation effect
    • Optional parameters:
      • Speed
        • Numeric (milliseconds)
        • Predefined string (‘slow’, ‘normal’, ‘fast’)
      • Callback
        • Optional function invoked when animation completes
    Show / Hide Elements Gradually
    • $(‘h1’).hide();
      • Instantly hides elements
    • $(‘h1’).hide(2000);
      • Hiding takes place gradually over 2 seconds
    • $(‘h1’).hide(‘slow’);
      • Predefined ‘slow’ transition time
    • $(‘h1’).hide(‘fast’);
      • Predefined ‘fast’ transition time
    Show / Hide Examples
    • Fading
        • $(‘h1’).fadeIn();
        • $(‘h1’).fadeOut(2000);
        • $(‘h1’).fadeTo(‘fast’, 0.5);
    • Sliding
        • $(‘h1’).slideUp();
        • $(‘h1’).slideDown(‘slow’);
        • $(‘h1’).slideToggle(3000);
    • show() / hide() / toggle() change scaling and opacity
    • Fading/sliding methods effect only opacity
    Fade / Slide Effects
    • $(‘#block’).animate({
    • width: ‘+=60px’,
    • opacity: 0.4,
    • fontSize: ‘3em’,
    • borderWidth: ‘10px’
    • }, 1500);
    • Many more effects available via plug-ins and the jQuery UI library
    Custom Animations
  • Effects Demo
    • <div id=‘container’></div>
    • Old school:
    • var span = document.createElement(‘span’);
    • span.innerHTML = ‘My Text’;
    • span.className = ‘myClass’;
    • var container = getElementById(‘container’);
    • container.appendChild(span);
    Before / After Example
    • <div id=‘container’></div>
    • Old school:
    • var span = document.createElement(‘span’);
    • span.innerHTML = ‘My Text’;
    • span.className = ‘myClass’;
    • var container = getElementById(‘container’);
    • container.appendChild(span);
    • With jQuery:
    • $(‘<span/>’).text(‘My Text’).addClass(‘myClass’).
    • appendTo(‘div#container’);
    Before / After Example
    • To enable Intellisense support, add this to the top of your .js file:
    • /// <reference path=&quot;~/shared/js/jquery-vsdoc.js&quot;/>
    • /// <reference path=&quot;~/shared/js/jquery-vsdoc.js&quot;/>
    • $(function() {
    • $(‘a’).click(function() {
    • var $this = $(this);
    • var linkText = $this.find(‘img’).attr(‘alt’);
    • if (linkText == undefined) {
    • linkText = $this.text();
    • }
    • West.Westlaw.Web.UI.Services.LinkTracking.
    • OnHyperlinkClick(linkText);
    • });
    • });
    Putting It All Together
      • $.browser
        • When you HAVE to perform browser detection
        • Contains properties for browser values
      • $.boxModel
        • W3C or Internet Explorer
      • $.styleFloat
        • Name used to represent the float CSS style in the element’s style property
        • Use for property name:
          •[$.styleFloat] = ‘left’
    “ Global” Flags
  • Utility Functions $.trim() Trims strings $.each() Iterates through properties and collections $.grep() Filters arrays $.map() Iterates through array, translating items into new array $.inArray() Returns index position of value in array $.makeArray() Converts array-like object into an array $.unique() Returns array of unique elements in original array $.extend() Extend target object with properties of other objects $.getScript() Dynamically load a script from url
    • jQuery is extensible through plug-ins, which add new methods to the jQuery object
    • Example plug-in usage:
      • $(‘img[src$=.png]’).ifixpng();
    • Create your own, using $.fn:
    • $.fn.hideLinks = function() {
    • return this.find(‘a[href]’).hide().end();
    • }
      • fn is actually a shortcut to ‘prototype’
    • Now use it:
      • $(‘p’).hideLinks();
    Plug-in Examples
    Documentation / Tutorials
    API Documentation
    API Documentation
    Cheat Sheets
  • Books Designer-focused Developer-focused
    • Moved many user interface plug-ins into one core
    • Supported by core contributors
    • Includes (currently in v1.6):
    jQuery UI
      • Drag / Drop
      • Sortable
      • Selectables
      • Resizables
      • Accordion
      • Calendar
      • Slider
      • Table
      • Tabs
      • Shadow
      • Auto Complete
      • Color Picker
      • Progress Bar
      • Spinner
      • Magnifier
    • Coming in 1.7: Layout controls, menus, tooltips, more
  • jQuery UI Demos
    • jQuery is largely complementary to the MS ASP.NET AJAX library, but there is some overlap:
      • AJAX
      • CSS manipulation
      • Client-side UI controls
        • AJAX Control Toolkit
        • jQuery UI
      • Event handling
    • No clear indication from Microsoft yet as to future direction
    Library Overlap
    • ASP.NET AJAX + jQuery = Microsoft AJAX Framework
    Microsoft AJAX Framework ASP.NET AJAX jQuery AJAX Requests Components and Controls Client Templates AJAX Control Toolkit Selectors Animations Plugins
    • Use MS Library for:
      • AJAX / UpdatePanels
      • Creating custom classes and controls
    • Use jQuery for:
      • DOM manipulation
      • CSS manipulation
      • Event binding/handling
    • UI controls: AJAX Control Toolkit or jQuery UI?
      • Look to AJAX Control Toolkit first (better integration)
      • jQuery UI offers better selection (not in code base yet)
    • Official site:
    • Microsoft presentation:
    • Usage examples:
    • Google group:
    • AJAX Experience presentations:
    • 12 year old’s jQuery presentation:
  • Questions?