A jQuery-powered introduction to jQuery - by Mario Alviano

http://archives.alviano.com/teaching/jquery/seminario/

or

http://tinyurl.com/alviano-jquery

Back

Introduction

jQuery features

  • jQuery is a general-purpose JavaScript library
  • Common JavaScript interactions made easy by jQuery
    • HTML document traversing
    • Event handling
    • Animating
    • Ajax interactions
  • Strength of the framework
    • Lightweight footprint: few KBs of scripts
    • CSS3 compliant: support (and extends) CSS selectors
    • Cross-browser: runs in almost all browsers

Model-View-Controller HTML5

The jQuery wrapper

  • The framework relies on a JavaScript class wrapping an array of DOM elements
  • Instances of this class are obtained by calling the jQuery function
    • jQuery(selector) or $(selector)
      Selects DOM elements according to a CSS selector

      Example

      • jQuery("div p a") or $("div p a")
        Selects all links contained in a paragraph which is contained in a div
      • jQuery("div.content td.number") or $("div.content td.number")
        Selects all table cells with class number which are contained in a div with class content

    • jQuery(function) or $(function)
      Adds a function to the onload method of the document

      Example

      • jQuery(function() { alert("Hello, World!!!"); }) or $(function() { alert("Hello, World!!!"); })
        Shows an alert after loading the document

    • jQuery(html code) or $(html code)
      Creates DOM elements (to be attached to document)

      Example

      • jQuery("<strong>Hello!</strong>") or $("<strong>Hello!</strong>")
        Creates a string strongly emphasized
      • jQuery("<div><img src='somewhere' /></div>") or $("<div><img src='somewhere' /></div>")
        Creates a div containing an image

    • A useful alias for the jQuery function: $(...) ShowHide

Setup the framework

Just include the jQuery script file in the 'head' section:

<script src="http://code.jquery.com/jquery-X.Y.Z.min.js"></script>

Back

Select DOM elements

A declarative approach for selecting DOM elements

Managing the wrapped set

  • Selected (or created) DOM elements are stored in a wrapped array
  • All operations on arrays are applicable to the wrapped set
  • The wrapped set can be modified by adding and removing elements
    • size()
    • get(index)
    • index(element)
    • slice(begin, end)
    • not(expression)
    • filter(expression)
    • has(expression)
    • Out of the scope of this talk!
  • Operations for manipulating DOM elements in the wrapped set
    • More interesting and discussed in the next slides!

Basic selectors

SelectorDescription
*Matches any element.
EMatches all elements with tag name E.
EF Matches all elements with tag name F that are descendants of E.
E>FMatches all elements with tag name F that are direct children of E.
E+FMatches all elements with tag name F that are immediately preceded by sibling E.
E~FMatches all elements with tag name F preceded by any sibling E.
E.CMatches all elements with tag name E with class name C. Omitting E is the same as *.C.
E#IMatches all elements with tag name E with the id of I. Omitting E is the same as *#I.
E[A]Matches all elements with tag name E that have attribute A of any value.
E[A=V]Matches all elements with tag name E that have attribute A whose value is exactly V.
E[A^=V]Matches all elements with tag name E that have attribute A whose value starts with V.
E[A$=V]Matches all elements with tag name E that have attribute A whose value ends with V.
E[A!=V]Matches all elements with tag name E that have attribute A whose value doesn't match the value V, or that lack attribute A completely.
E[A*=V]Matches all elements with tag name E that have attribute A whose value contains V.

Positional filters

SelectorDescription
:firstMatches the first match within the context. li a:first returns the first link that’s a descendant of a list item.
:lastMatches the last match within the context. li a:last returns the last link that’s a descendant of a list item.
:first-childMatches the first child element within the context. li:first-child returns the first list item of each list.
:last-childMatches the last child element within the context. li:last-child returns the last list item of each list.
:only-childReturns all elements that have no siblings.
:nth-child(n)Matches the nth child element within the context. li:nth-child(2) returns the second list item of each list.
:nth-child(even|odd)Matches even or odd children within the context. li:nth- child(even) returns the even list items of each list.
:nth-child(Xn+Y)Matches the nth child element computed by the supplied formula. If Y is 0, it may be omitted. li:nth-child(3n) returns every third list item, whereas li:nth-child(5n+1) returns the item after every fifth element.
:evenMatches even elements within the context. li:even returns every even list item.
:oddMatches odd elements within the context. li:odd returns every odd list item.
:eq(n)Matches the nth matching element.
:gt(n)Matches matching elements after and excluding the nth matching element.
:lt(n)Matches matching elements before and excluding the nth matching element.

Other CSS3 filters

SelectorDescription
:checkedSelects only checkboxes or radio elements in checked state.
:disabledSelects only elements in disabled state.
:enabledSelects only elements in enabled state.
:not(selector)Negates the specified selector.

New filters

SelectorDescription
:animatedSelects only elements that are currently under animated control.
:buttonSelects only button elements (input[type=submit], input[type=reset], input[type=button], or button).
:checkboxSelects only checkbox elements (input[type=checkbox]).
:contains(food)Selects only elements containing the text food.
:fileSelects only file input elements (input[type=file]).
:has(selector)Selects only elements that contain at least one element that matches the specified selector.
:headerSelects only elements that are headers; for example, <h1> through <h6> elements.
:hiddenSelects only elements that are hidden.
:imageSelects only image input elements (input[type=image]).
:inputSelects only form elements (input, select, textarea, button).
:parentSelects only elements that have children (including text), but not empty elements.
:passwordSelects only password elements (input[type=password]).
:radioSelects only radio elements (input[type=radio]).
:resetSelects only reset buttons (input[type=reset] or button[type=reset]).
:selectedSelects only
:submitSelects only submit buttons (button[type=submit] or input[type=submit]).
:textSelects only text elements (input[type=text]).
:visibleSelects only elements that are visible.
Back

DOM manipulation

Adding and removing CSS classes

  • addClass(names)
    Adds the specified classes to the wrapped set
  • removeClass(names)
    Removes the specified classes to the wrapped set
  • toggleClass(names)
    Each specified class is removed from each element in the wrapped set that have the class, and added to the other elements.

Example 1

Adds the 'small' class to all images contained in divs with class 'thumb' (within this block) Execute

Removes the 'small' class to all images contained in divs with class 'thumb' (within this block) Execute

Toggles the 'small' class to all images contained in divs with class 'thumb' (within this block) Execute

Example 2

SelectorDescription
:checkedSelects only checkboxes or radio elements in checked state.
:disabledSelects only elements in disabled state.
:enabledSelects only elements in enabled state.
:not(selector)Negates the specified selector.


Adds the 'alt' class to all even rows of tables (within this block) Execute


Removes the 'alt' class to all even rows of tables (within this block) Execute


Toggles the 'alt' class to all rows of tables (within this block) Execute

Setting element content (part 1)

  • html(content)
    Sets the passed HTML fragment as the content of all matched elements
  • text(content)
    Sets the passed text as the content of all matched elements

Example 1

This is a div with class 'inject'.

Execute

Execute

  • append(content)
    Appends the passed content to the content of all matched elements.
    If 'content' is a jQuery selection, the elements in the wrapped set are moved into the first target element and copied in the other elements.

Example 2

This is a div with class 'inject'.

Execute

Execute

  • prepend(content)
    Prepends the passed content to the content of all matched elements.
    If 'content' is a jQuery selection, the elements in the wrapped set are moved into the first target element and copied in the other elements.

Example 3

This is a div with class 'inject'.

Execute

Execute

Setting element content (part 2)

  • before(content)
    Inserts the passed content before each matched elements.
    If 'content' is a jQuery selection, the elements in the wrapped set are moved before the first target element and copied in the other elements.

Example 4

This is a div with class 'inject'.

Execute

Execute

  • after(content)
    Inserts the passed content after each matched elements.
    If 'content' is a jQuery selection, the elements in the wrapped set are moved after the first target element and copied in the other elements.

Example 5

This is a div with class 'inject'.

Execute

Execute

  • Similar functions with reverse targets-content order
    • appendTo(targets)
    • prependTo(targets)
    • insertBefore(targets)
    • insertAfter(targets)
  • Other manipulation functions
    • remove()
    • detach()
    • empty()
    • clone()

Getting and setting form content

  • val()
    Returns the value of the input element in the wrapped set (or an array of values if the wrapped set contains more than one element)
  • val(content)
    Sets the value of the input element in the wrapped set
  • serialize()
    Returns a string representing all values in a form (useful for passing data to a server page)

Example 1

This is a div with class 'inject'.

Execute

Execute

Execute

Back

Events and animations

Manage event handlers

  • bind(event, handler)
    Adds a handler function to the specified event of all elements in the wrapped set
  • one(event, handler)
    Like bind, but the handler is removed after firing
  • unbind(event, handler)
    Removes a handler for the specified event of all elements in the wrapped set.
    If handler is omitted, all handlers of the specified event are removed.

Example 1

This is a div with class 'inject'.

Execute

Execute

var myListener = function(){ alert('Hello, World!!!'); }; (decleared in main.js) Execute

Common events

Animate DOM elements

  • show(speed, callback)
    Makes wrapped elements visible. An optional speed among 'slow', 'normal' and 'fast' can be specified. An optional function to be invoked after the animation can also be specified.
  • hide(speed, callback)
    Makes wrapped elements invisible. An optional speed among 'slow', 'normal' and 'fast' can be specified. An optional function to be invoked after the animation can also be specified.
  • toggle(speed, callback)
    Makes visible wrapped elements invisible, and invisible wrapped elements visibile. An optional speed among 'slow', 'normal' and 'fast' can be specified. An optional function to be invoked after the animation can also be specified.

Example 1

Execute

Execute

Execute

  • Similar functions
    • fadeIn(speed, callback)
    • fadeOut(speed, callback)
    • slideDown(speed, callback)
    • slideUp(speed, callback)
    • slideToggle(speed, callback)
    • fadeTo(speed, opacity, callback)

Example 2

Execute

Execute

Execute

Execute

Execute

Execute

Common events

Event
blur
change
click
dblclick
error
focus
focusin
focusout
keydown
keypress
keyup
load
mousedown
mouseenter
mouseleave
mousemove
mouseout
mouseover
mouseup
ready
resize
scroll
select
submit
unload
Back

Simple Ajax

What is Ajax?

  • An acronym for Asynchronous JavaScript and XML
  • A group of methods used on the client-side to create asynchronous web applications
  • Allows to send data to, and retrieve data from, a server in the background
  • Based on the XMLHttpRequest object
  • Unfortunately, it is not easy to use this tool...
  • Likely, jQuery provides high-level functions for Ajax interactions

How does it work?

  • $.load(url, parameters, callback)
    Initiates an Ajax request to the specified URL with the request parameters. The response text replaces the content of all matched elements.
    • url: the URL of the server-side resource
    • parametes: data to be passed as request parameters (optional)
    • callback: a function handling retrivied data (optional)

Example 1

This is a div with class 'inject'.
Choose a pet:

Execute

  • $.get(url, parameters, callback, type)
    $.post(url, parameters, callback, type)
    Initiates a GET/POST request to the server using the specified URL with any passed parameters as the query string.
    • url: the URL of the server-side resource
    • parametes: data to be passed as request parameters (optional)
    • callback: a function handling retrivied data (optional)
    • type: 'html', 'text', 'xml', 'json', 'script', or 'jsonp' (optional)

Example 2

This is a div with class 'inject'.
Choose a pet:

Execute

Back

jQuery frameworks

jQuery UI

  • A comprehensive set of core interaction plugins, UI widgets and visual effects
  • All this using a jQuery-style and a event-driven architecture
  • Focus on web standards, accessiblity, flexible styling, and user-friendly design
  • Compatible with IE 6.0+, Firefox 3+, Safari 3.1+, Opera 9.6+, and Google Chrome
jQuery UI demos

jQuery Mobile

  • A unified, HTML5-based user interface system for all popular mobile device platforms
  • Built on the rock-solid jQuery and jQuery UI foundation
  • Flexible, easily themeable design
  • Easily embeddable in a native iOS or Android app
  • Note: mixing jQuery Mobile and jQuery UI is not a good idea!
  • You already experienced jQuery Mobile possibilities during this presentation!
jQuery Mobile demos

Resources on the web

  • Free book: jQuery Fundamentals - by Rebecca Murphey Read the book
  • jQuery in Action labs Visit the site
  • Exercises (selectors)

    Open the Selectors Lab
    1. Select all images
    2. Select all list items of second level or more
    3. Select all list items of first level
    4. Select all list items containing a link
    5. Select all list items that don't contain a link
    6. Select all input elements
    7. Select all input elements that checked
    8. Select all input elements that are not checked
    9. Select all odd rows of tables
    10. Repeat all previous exercises by limiting the selection to the first element
    11. Repeat all previous exercises by limiting the selection to the last element
    12. Repeat all previous exercises by limiting the selection to the i-th element
  • Exercises (operations)

    Open the Operations Lab
    1. Fade out all images
    2. Slide down all images
    3. Move the first row of the table after the last row (execute more times and have fun!)
    4. Replace the content of the first label with the text in the input field
    5. Remove all divs containing checkboxes, but not those containing other divs
    6. Fade out the i-th row from the table; then, fade it in back!
    7. As the previous exercise, but the row must be the one specified by the checkbox group
    8. Copy the first image after all items in the radio group
    9. Bind each previous exercise to the submit button
    10. As the previous exercise, but using the funtion 'one()'