Web Programming Step by Step, 2nd Edition

Lecture XX: jQuery

Reading: jquery.com

Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Valid HTML5 Valid CSS

The jQuery Library

Learning jQuery will be an exercise in your ability to navigate online APIs and documentation:

Problems with JavaScript

JavaScript is a powerful language, but it has many flaws:

jQuery framework

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"
 type="text/javascript"></script>

jQuery Design Principles

jQuery is so powerful in part because of these design principles

window.onload

We cannot use the DOM before the page has been constructed. jQuery gives us a more compatibile way to do this.

Exercise: jQuery boilerplate

We will be working on a bouncing images example.

  • Use jQuery to alert some text when the square is clicked. (Use regular DOM syntax when needed)

Aspects of the DOM and jQuery

jQuery node identification

The $ aka jQuery function selects elements from the DOM using most any CSS selector.

jQuery Selectors

jQuery / DOM comparison

DOM method jQuery equivalent
getElementById("id") $("#id")
getElementsByTagName("tag") $("tag")
getElementsByName("somename") $("[name='somename']")
querySelector("selector") $("selector")
querySelectorAll("selector") $("selector")

Exercise: square identification

  • Use jQuery selectors to identify elements with these properties in a hypothetical page:
    • All p tags that have no children, but only if they don't have a class of ignore
    • Any element with the text "REPLACE_ME" in it.
    • All div tags with a child that has a class of special
    • All heading elements (h1, h2, h3, h4, h5, h6)
    • Every other visible li.
  • Use the DOM API to target the #square and periodically change it's position in a random direction.
  • Use jQuery selectors instead of the DOM API.

jQuery Terminology

the jQuery function
refers to the global jQuery object or the $ function depending on the context
a jQuery object
the object returned by the jQuery function that often represents a group of elements
selected elements
the DOM elements that you have selected for, most likely by some CSS selector passed to the jQuery function and possibly later filtered further

The jQuery object

// false
document.getElementById("id") == $("#myid");
document.querySelectorAll("p") == $("p");

// true
document.getElementById("id") == $("#myid")[0];
document.getElementById("id") == $("#myid").get(0);

document.querySelectorAll("p")[0] == $("p")[0];

Using $ as a wrapper

// convert regular DOM objects to a jQuery object
var elem = document.getElementById("myelem");
elem = $(elem);

var elems = document.querySelectorAll(".special");
elems = $(elems);

DOM context identification

DOM tree
var list = document.getElementsByTagName("ul")[0];
var specials = list.querySelectorAll('li.special');

find / context parameter

jQuery gives two identical ways to do contextual element identification

var elem = $("#myid");

// These are identical
var specials = $("li.special", elem);
var specials = elem.find("li.special");

jQuery traversal methods

Exercise: #box children

  • Use the DOM API to target the children of the box element and change their position.
  • Use the jQuery library to do the same.

Looping over the DOM

Inside the jQuery each loop

$("li").each(function(idx, e) {
	// do stuff with e
});

Getting/setting CSS classes in jQuery

function highlightField() {
	// turn text yellow and make it bigger
	if (!$("#myid").hasClass("invalid")) {
		$("#myid").addClass("highlight");
	}
}

Accessing styles in jQuery

function biggerFont() {
	// turn text yellow and make it bigger
	var size = parseInt($("#clickme").css("font-size"));
	$("#clickme").css("font-size", size + 4 + "pt");
}

Common bug: incorrect usage of existing styles

// bad!
$("#main").css("top", $("#main").css("top") + 100 + "px");

Exercise: style update, positioning

  • Update the bouncing images javascript code to use better jQuery style.
  • Use javascript to initially position the element with id square directly in the center of it's parent.
  • Add code to make the #square change direction when it reaches the boundary of it's parent.

jQuery method behavior

jQuery method parameters

Many jQuery object methods are overloaded

getter syntax:
$("#myid").css(propertyName);
setter syntax:
$("#myid").css(propertyName, value);
multi-setter syntax:
$("#myid").css({
	'propertyName1': value1,
	'propertyName2': value2,
	...
	});
modifier syntax:
$("#myid").css(propertyName, function(idx, oldValue) {
	return newValue;
});

What do you think the multi-modifier syntax is?

common jQuery mistake

// bad jQuery
$("#main").css("top", parseInt($("#main").css("top")) + 100 + "px");

jQuery method returns

When there is no other return to make, jQuery methods return the same jQuery object back to you

method return type
$("#myid"); jQuery object
$("#myid").children(); jQuery object
$("#myid").css("margin-left"); String
$("#myid").css("margin-left", "10px"); jQuery object
$("#myid").addClass("special"); jQuery object

jQuery chaining


$("#main").css("color", "red");
$("#main").attr("id", "themainarea");
$("#main").addClass("special");

The implictly returned jQuery object allows for chaining of method calls.

$("img")
	.css("color", "red")
	.addClass("special")
	.src = "foo.png";

Expression return value at each line:

// [<img />, ...]
// [<img style="color: red" />, ...]
// [<img class="special" style="color: red" />, ...]
// cannot chain further because this is an assignment :(

Exercise: another style update

  • Add several divs with a class of square to the html.
  • Make sure that our code still makes all of them move around the page randomly.
  • Clean up the code to take full advantage of jQuery syntax.
  • Change the background-color of each square when it hits a wall.

jQuery attr() function

$("img")				// poor jQuery style
	.css("color", "red")
	.addClass("special")
	.src = "foo.png";
$("img")				// good jQuery style
	.css("color", "red")
	.addClass("special")
	.attr("src", "foo.png");
	// we could chain further right here

More node manipulation with jQuery

Suppose you already have a jQuery object, e.g. $("#myid")

jQuery method functionality
.hide() toggle CSS display: none on
.show() toggle CSS display: none off
.empty() remove everything inside the element, innerHTML = ""
.html() get/set the innerHTML without escaping html tags
.text() get/set the innerHTML, HTML escapes the text first
.val() get/set the value of a form input, select, textarea, ...
.height() get/set the height in pixels, returns a Number
.width() get/set the width in pixels, return a Number

DOM innerHTML hacking

Why not just code the previous example this way?

document.getElementById("myid").innerHTML += "<p>A paragraph!</p>";
  • Imagine that the new node is more complex:
    • ugly: bad style on many levels (e.g. JS code embedded within HTML)
    • error-prone: must carefully distinguish " and '
    • can only add at beginning or end, not in middle of child list
document.getElementById("myid").innerHTML += "<p style='color: red; " +
		"margin-left: 50px;' " +
		"onclick='myOnClick();'>" +
		"A paragraph!</p>";

Creating new nodes

name description
document.createElement("tag") creates and returns a new empty DOM node representing an element of that type
document.createTextNode("text") creates and returns a text node containing given text
// create a new <h2> node
var newHeading = document.createElement("h2");
newHeading.innerHTML = "This is a heading";
newHeading.style.color = "green";

Modifying the DOM tree

Every DOM element object has these methods:

name description
appendChild(node) places given node at end of this node's child list
insertBefore(newold) places the given new node in this node's child list just before old child
removeChild(node) removes given node from this node's child list
replaceChild(newold) replaces given child with new node
var p = document.createElement("p");
p.innerHTML = "A paragraph!";
document.getElementById("myid").appendChild(p);

Removing a node from the page

var bullets = document.getElementsByTagName("li");
for (var i = 0; i < bullets.length; i++) {
	if (bullets[i].innerHTML.indexOf("child") >= 0) {
		bullets[i].parentNode.removeChild(bullets[i]);
	}
}

jQuery manipulation methods

Create nodes in jQuery

The $ function to the rescue again

var newElement = $("<div>");
$("#myid").append(newElement);

jQuery programmers typically 1 line it

$("#myid").append($("<div>"));

The previous example becomes this with jQuery


var bullets = document.getElementsByTagName("li");
for (var i = 0; i < bullets.length; i++) {
	if (bullets[i].innerHTML.indexOf("children") >= 0) {
		bullets[i].parentNode.removeChild(bullets[i]);
	}
}
$("li:contains('child')").remove();

Exercise: lots of squares

  • Add some number of .square divs to the page using jQuery.
  • Change the divs to be img tags with a src of laughing_man.jpg.

Creating complex nodes in jQuery

The terrible way, this is no better than innerHTML hacking
$("<p id='myid' class='special'>My paragraph is awesome!</p>")
The bad way, decent jQuery, but we can do better
$("<p>")
	.attr("id", "myid")
	.addClass("special")
	.text("My paragraph is awesome!");
The good way
$("<p>", {
	"id": "myid",
	"class": "special",
	"text": "My paragraph is awesome!"
});

jQuery $ function signatures

Responding to the page ready event
$(function);
Identifying elements
$("selector", [context]);
Upgrading DOM elements
$(elements);
Creating new elements
$("<html>", [properties]);

DOM example

Here is what it might look like if you tried to insert an image before each special span tag in a div using the DOM's API.

var spans = document.querySelectorAll("#ex1 span.special");
for (var i = 0; i < spans.length; i++) {
	var img = document.createElement("img");
	img.src = "images/laughing_man.jpg";
	img.alt = "laughing man";
	img.style.verticalAlign = "middle";
	img.style.border = "2px solid black";
	img.onclick = function() {
		alert("clicked");
	}
	spans[i].insertBefore(img, spans[i].firstChild);
}
Special Special Not Special Special Not Special

Poor jQuery example

$("#ex2 span.special").each(function(i, elem) {
	var img = $("<img>")
		.attr("src", "images/laughing_man.jpg")
		.attr("alt", "laughing man")
		.css("vertical-align", "middle")
		.css("border", "2px solid black")
		.click(function() {
			alert("clicked");
		});
	$(elem).prepend(img);
});
Special Special Not Special Special Not Special

Good jQuery example

$("#ex3 span.special").prepend($("<img>", {
	"src": "images/laughing_man.jpg",
	"alt": "laughing man",
	"css": {
		"vertical-align": "middle",
		"border": "2px solid black"
	},
	"click": function() {
		alert("clicked");
	}
}));
Special Special Not Special Special Not Special

Event-handling in jQuery

Recall: JavaScript events

abort blur change click dblclick error focus
keydown keypress keyup load mousedown mousemove mouseout
mouseover mouseup reset resize select submit unload

Attaching event handlers the jQuery way

element.onevent = function;
element.event(function);
// call the playNewGame function when the Play button is clicked
$("#play").click(playNewGame);

function playNewGame(evt) {
	// respond to the click event
}

Attaching many event handlers

You often need to attach an event handler to a group of elements.

Exercise: hover bounce

We will elaborate on the bounce.html example.

  • Add code so that when we mouseover an img it's src changes to dai_gurren.jpg
  • If we mouse over the #square element, change it's background-color instead.

Custom DOM events

Custom jQuery events

The jQuery event object

function handler(event) {
	// an event handler function ...
}
method / property name description
type what kind of event, such as "click" or "mousedown"
target the element on which the event handler was registered
preventDefault() prevents browser from performing its usual action in response to the event
stopPropagation() prevents the event from bubbling up further
stopImmediatePropagation() prevents the event from bubbling and prevents any other handlers from being executed

Mouse event example

<pre id="target">Move the mouse over me!</pre>
window.onload = function() {
	$("#target").mouseover(showCoords);
};

function showCoords(event) {
	$("#target").html(
		  "page   : (" + event.pageX + ", " + event.pageY + ")\n"
		+ "screen : (" + event.screenX + ", " + event.screenY + ")\n"
		+ "client : (" + event.clientX + ", " + event.clientY + ")"
	);
}
Move the mouse over me!

Fixing redundant code with this

<fieldset>
	<label><input type="radio" name="ducks" value="Huey"  /> Huey</label>
	<label><input type="radio" name="ducks" value="Dewey" /> Dewey</label>
	<label><input type="radio" name="ducks" value="Louie" /> Louie</label>
</fieldset>
$(":radio").click(processDucks);
function processDucks() {
	if ($("huey").checked) {
		alert("Huey is checked!");
	} else if ($("dewey").checked) {
		alert("Dewey is checked!");
	} else {
		alert("Louie is checked!");
	}
	alert(this.value + " is checked!");
}

Page/window events

namedescription
load, unload the browser loads/exits the page
resize the browser window is resized
error an error occurs when loading a document or an image
contextmenu the user right-clicks to pop up a context menu
$(window).on('contextmenu', function);

Stopping an event's browser behavior

<form id="exampleform" action="http://foo.com/foo.php">...</form>
$(function() {
	$("#exampleform").submit(checkData);
});

function checkData(event) {
	if ($("#city").val() == "" || $("#state").val().length != 2) {
		alert("Error, invalid city/state.");  // show error message
		event.preventDefault();
	}
}

Which element gets the event

<body>
	<div>
		<p>
			Events are <em>crazy</em>!
		</p>
	</div>
</body>
$(function() {
	$("body, div, p, em").click(hello);
});

function hello() {
	alert("You clicked on the " + $(this).attr("tag"));
}

What happens when I click on the span? Which element will get the event?

Answer: All of them!

Event bubbling

event flow
<body>
	<div>
		<p>
			Events are <em>crazy</em>!
		</p>
	</div>
</body>

Bubbling example

<body>
	<div>
		<p>
			Events are <em>crazy</em>!
		</p>
	</div>
</body>
$(function() {
	$("body, div, p, em").click(hello);
});

function hello() {
	alert("You clicked on the " + this.nodeName);
}

Runnable example

Stopping an event from bubbling

Use the stopPropagation() method of the jQuery event to stop it form bubbling up.

<body>
	<div>
		<p>
			Events are <em>crazy</em>!
		</p>
	</div>
</body>
$(function() {
	$("body, div, p, em").click(hello);
});

function hello(evt) {
	alert("You clicked on the " + this.nodeName);
	evt.stopPropagation();
}

Runnable example

Multiple handlers

<body>
	<div>
		<p>
			Events are <em>crazy</em>!
		</p>
	</div>
	<p>Another paragraph!</p>
</body>
$(function() {
	$("body, div, p, em").click(hello);
	$("div > p").click(anotherHandler);
});

function hello() {
	alert("You clicked on the " + this.nodeName);
}
function anotherHandler() {
	alert("You clicked on the inner P tag");
}

What happens when the first p tag is clicked? Runnable example

Stopping an event right now

function anotherHandler(evt) {
	alert("You clicked on the inner P tag");
	evt.stopImmediatePropagation();
}

Runnable example

stopImmediatePropogation() example

$("div a").click(function() {
   // Do something
});

$("div a").click(function(evt) {
   // Do something else
   evt.stopImmediatePropagation();
});

$("div a").click(function() {
   // THIS NEVER FIRES
});

$("div").click(function() {
   // THIS NEVER FIRES
});

jQuery handler return value

<form id="exampleform">
	...
	<button>Done</button>
</form>
$(function() {
	$("#exampleform").submit(cleanUpData);
	$("button").click(checkData);
});

function checkData() {
	if ($("#city").val() == "" || $("#state").val().length != 2) {
		alert("Error, invalid city/state.");  // show error message
		return false;
	}
}

jQuery and Ajax

jQuery's ajax method

$.ajax({
	"url": "http://foo.com",
	"option" : "value",
	"option" : "value",
	...
	"option" : "value"
});

$.ajax() options

option description
url The URL to make a request from
type whether to use POST or GET
data an object literal filled with query parameters and their values
dataType The type of data you are expecting to recieve, one of: "text", "html", "json", "xml"
timeout an amount of time in seconds to wait for the server before giving up
success event: called when the request finishes successfully
error event: called when the request fails
complete event: called when the request finishes successfully or erroneously

jQuery Ajax example

$.ajax({
	"url": "foo/bar/mydata.txt",
	"type": "GET",
	"success": myAjaxSuccessFunction,
	"error": ajaxFailure
});
function myAjaxSuccessFunction(data) {
	// do something with the data
}
function ajaxFailure(xhr, status, exception) {
	console.log(xhr, status, exception);
}

Exercise: output comparison tool

This example uses this output page

  • Add Ajax code to load in a hw output file into the textarea

Ajax data parameter

The data passed to your success handler will be in whatever format you specified in the dataType option

Handling Ajax errors

$.ajax(
	"url": "http://foo.com",
	"type": "GET",
	"success": functionName,
	"error": ajaxFailure
});
...
function ajaxFailure(xhr, status, exception) {
	console.log(xhr, status, exception);
}

Exercise: Ajax error

  • Add an item to the drop-down that does not exist on the server
  • Make sure our code fails noticeably when the Ajax call fails

Better jQuery Ajax

Rather than specify all of the options in an object literal...

$.ajax({
	"url": "http://foo.com",
	"type": "GET",
	"success": functionName,
	"error": ajaxFailure
});

one can pass the URL as the first parameter and the rest as an object literal.

$.ajax("http://foo.com", {
	"type": "GET",
	"success": functionName,
	"error": ajaxFailure
});

Why? It makes it even easier to see what this Ajax request is doing.

Even Better jQuery Ajax

Rather than supply the handlers as fields in the options object...

$.ajax("http://foo.com", {
	"type": "GET",
	"success": functionName,
	"error": ajaxFailure
});

use these event handler function calls done() and fail() instead

$.ajax("http://foo.com", {
	"type": "GET"
})
	.done(functionName)
	.fail(ajaxFailure);

They do the same thing as the success and error options respectively except that they are method calls and let up break up the syntax a little.

Debugging Ajax code

Chrome Ajax

Passing query parameters to a request

$.ajax("lookup_account.php", {
	"type": "get",
	"data": {
		"name": "Ed Smith",
		"age": 29,
		"password": "abcdef"
	},
})
	.done(function)
	.fail(ajaxFailure);

Creating a POST request

$.ajax("url", {
	"type": "POST",
	"data": {
		"name": value,
		"name": value,
		...,
		"name": value
	},
})
	.done(function)
	.fail(ajaxFailure);

$.get() and $.post() shortcuts

$.get(url, [data])
	.done(function)
	.fail(function);
$.post(url, [data])
	.done(function)
	.fail(function);

More about $.get() and $.post()

function description
$.ajax() A general function for making Ajax requests, other Ajax functions rely on this
$.get() makes a GET request via Ajax
$.post() makes a POST request via Ajax

Why bother making the distinction if it all boils down to a call to $.ajax() under the hood

Exercise: quotes

This example uses the quotes page

  • When the button is clicked fetch a quote from quote.php.
  • Provide the count parameter to quote.php so we can get multiple quotes.

jQuery's $.ajaxSetup() function

Often your Ajax requests use very similar option values.

$.ajaxSetup({
	"option": "value",
	"option": "value",
	...
});

Ajax user feedback

ajax loader animated gif

User feedback with always()

The general technique is to show() some feedback when the Ajax request starts and hide() it again once it finishes.

$.get("url")
	.done(function)
	.error(function)
	.always(function() {
		$("#loader").hide();
	});
$("#loader").show();

Global Ajax events

event method description
.ajaxStart() fired when new Ajax activity begins
.ajaxStop() fired when Ajax activity has halted
.ajaxSend() fired each time an Ajax request is made
.ajaxSuccess() fired each time an Ajax request finishes successfully
.ajaxError() fired each time an Ajax request finishes with errors
.ajaxComplete() fired each time an Ajax request finishes

User feedback example

$(function() {
	$("#loader")
		.hide()
		.ajaxStart(function() {
			$(this).show();
		}).ajaxStop(function() {
			$(this).hide();
		});

	$("#mybutton").click(function() {
		$.get("http://foo.com")
			.done(function)
			.error(ajaxFailure);
	});
});

Fetching XML using Ajax (template)

node tree
$.get("foo.xml")
	.done(functionName);

function functionName(xmlDom) {
	// do stuff with the xmlDom just like you would with the HTML dom
}

XML DOM and jQuery

You use the same jQuery functions to interact with the XML DOM, with one minor tweak:

Ajax XML DOM example

<?xml version="1.0" encoding="UTF-8"?>
<employees>
	<lawyer money="99999.00" />
	<janitor name="Ed"> <vacuum model="Hoover" /> </janitor>
	<janitor name="Bill">no vacuum, too poor</janitor>
</employees>
// how much money does the lawyer make?
$(xmlDom).find("lawyer").attr("money");	// "99999.00"

// array of 2 janitors
var janitors = $(xmlDom).find("janitor");
janitors.find("vacuum").attr("model");		// "Hoover"
janitors.last().text();										// "no vacuum, too poor"

Larger XML file example

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
	<book category="cooking">
		<title lang="en">Everyday Italian</title>
		<author>Giada De Laurentiis</author>
		<year>2005</year><price>30.00</price>
	</book>
	<book category="computers">
		<title lang="en">XQuery Kick Start</title>
		<author>James McGovern</author>
		<year>2003</year><price>49.99</price>
	</book>
	<book category="children">
		<title lang="en">Harry Potter</title>
		<author>J K. Rowling</author>
		<year>2005</year><price>29.99</price>
	</book>
	<book category="computers">
		<title lang="en">Learning XML</title>
		<author>Erik T. Ray</author>
		<year>2003</year><price>39.95</price>
	</book>
</bookstore>

Navigating node tree example

// make a paragraph for each book about computers
$(xmlDom).find("book[category='computer']").each(function(idx, e) {
	// extract data from XML
	var title = $(e).find("title").text();
	var author = $(e).find("author").text();

	// make an HTML <p> tag containing data from XML
	$("<p>")
		.text(title + ", by " + author)
		.appendTo($(document.body));
});

Debugging response XML in Firebug

Firebug Debug Ajax

JSON and AJAX (AJAJ?...)

$.get("foo.json")
	.done(functionName);

function functionName(jsonObj) {
	// do stuff with the jsonObj
}

jQuery UI

jQuery UI overview

jQuery UI : a JavaScript library, built on top of jQuery, that adds:

Downloading and using jQuery UI

<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"
	type="text/javascript"></script>

<script
	src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"
	type="text/javascript"></script>

<!-- If you want the default ui widget stylings -->
<link
	href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/ui-lightness/jquery-ui.css"
	rel="stylesheet" type="text/css" />

Visual effects

(appearing)



(disappearing)

(Getting attention)

jquery ui logo
Click effects above

Applying effects to an element

element.effect();            // for some effects
element.effect(effectName);   // for most effects
$("#sidebar").slideUp();

// No need to loop over selected elements, as usual
$("#results > button").effect("pulsate");

Effect options

element.effect(effectName, {
	option: value,
	option: value,
	...
});
$("#myid").effect("explode", {
	"pieces": 25
});

Normal

25 Pieces

Effects chaining

$('#demo_chaining')
	.effect('pulsate')
	.effect('highlight')
	.effect('explode');

Effect duration

$('#myid').effect('puff', {}, duration)

Custom effects - animate()

$('#myid').animate(properties, [duration]);
$('#myid')
	.animate({
		'font-size': '80px',
		'color': 'green'
	}, 1000);

This is a demo!!!

Custom effects easing

$('#myid')
	.animate(properties, [duration], [easing]);
$('#myid')
	.animate({
		'font-size': '80px',
		'color': 'green'
	}, 1000, 'easeOutBounce');

This is a demo!!!

Effects Easing

Better Custom Effects* - toggleClass()

This is a demo!!!

Adding delay()

$('#myid')
	.effect('pulsate')
	.delay(1000)
	.slideUp()
	.delay(3000)
	.show('fast');

Effect complete event

$("#myid").effect('puff', [options], [duration], [function]);
$('#myid').effect('clip', {}, 'default', function() {
	alert('finished');
});

Good effects syntax

Drag and drop

jQuery UI provides several methods for creating drag-and-drop functionality:

Sortable

$('#myid ul').sortable([options]);

Sortable demo

<ol id="simpsons">
	<li>Homer</li>
	<li>Marge</li>
	<li>Bart</li>
	<li>Lisa</li>
	<li>Maggie</li>
</ol>
$(function() {
	$("#simpsons").sortable();
});
  1. Homer
  2. Marge
  3. Bart
  4. Lisa
  5. Maggie

Sortable list events

event description
change when any list item hovers over a new position while dragging
update when a list item is dropped into a new position (more useful)
$(function() {
	$("simpsons").sortable({
		'update': function(event, ui) {
			// Do stuff here
		}
	});
});

Sortable list events example

$(function() {
	$("#simpsons").sortable({
		'update': listUpdate
	});
});

function listUpdate(event, ui) {
	// can do anything I want here; effects, an Ajax request, etc.
	ui.item.effect('shake');
}
  1. Homer
  2. Marge
  3. Bart
  4. Lisa
  5. Maggie

Sortable "methods"

$('#my_list').sortable('methodName', [arguments]);

// Some examples
$('#my_list').sortable('destroy');
$('#my_list').sortable('option', 'cursor', 'pointer');

Draggable

$('#myid').draggable([options]);

Draggable example

<div id="draggabledemo1">Draggable demo 1. Default options.</div>
<div id="draggabledemo2">Draggable demo 2.
	{'grid': [40,40], 'revert': true}</div>
$('#draggabledemo1').draggable();
$('#draggabledemo2').draggable({
	'revert': true,
	'grid': [40, 40]
});
logo Draggable demo 1.
Default options.
logo Draggable demo 2.
{snap:[60, 60], revert:true}

Droppable

$('#myid').droppable([options]);

Drag/drop shopping demo

<img id="shirt" src="images/shirt.png" alt="shirt" />
<img id="cup" src="images/cup.png" alt="cup" />
<div id="droptarget"></div>
$('#shirt').draggable();
$('#cup').draggable();
$('#droptarget').droppable({
	'drop': productDrop
});

function productDrop(event, ui) {
	alert("You dropped " + ui.item.attr('id'));
}
shirt cup

Auto-completing text fields

autocomplete

Scriptaculous offers ways to make a text box that auto-completes based on prefix strings *:

* (won't be necessary once HTML5 datalist element is well supported)

Using a local autocompleter

var data = ["foo", "food", "foobar", "foolish", "foiled", "cake"];
$('#myid').autocompleter({
	'source': data
});

Local autocompleter demo

<input id="bands70s" size="40" type="text" />
<div id="bandlistarea"></div>
$('#bands70s').autocomplete({
	'source': data,
	'appendTo': '#bandlistarea'
});
Specify a 70's band:

Using an AJAX autocompleter

$('#my_input').autocomplete({
	'source': 'http://foo.com/webservice.php'
});
if (!isset($_GET['term'])) {
	header('HTTP/1.1 400 Invalid Request - No term parameter provided');
	die('No term parameter provided.');
}
$term = $_GET['term'];
$results = getCompleterResults($term);	 // an array() return value
print json_encode($results);

accordion widget

<div class="accordion">
	<h1><a href="#">Section 1</a></h1>
	<div>Section 1 Content</div>
	...
</div>
Section 1

Mauris mauris ante, blandit et.

Section 2

Sed non urna. Donec et ante.

Section 3

Nam enim risus, molestie et, porta ac.

Section 4

Cras dictum. Pellentesque habitant morbi.

tabs widget

<div class="tabs">
	<ul>
		<li><a href="#tab1">Tab 1</a></li>
		<li><a href="#tab2">Tab 2</a></li>
		...
	</ul>
	<div id="tab1">Tab 1 Content</div>
	<div id="tab2">Tab 2 Content</div>
	...
</div>

Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus.

Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante.

Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti.

jQuery UI theming

kind classes
Layout Helpers .ui-helper-hidden, .ui-helper-reset, .ui-helper-clearfix
Widget Containers .ui-widget, .ui-widget-header, .ui-widget-content
Interaction States .ui-state-default, .ui-state-hover, .ui-state-focus, .ui-state-active
Interaction Cues .ui-state-highlight, .ui-state-error, .ui-state-error-text, .ui-state-disabled, .ui-priority-primary, .ui-priority-secondary

Applying UI styles

<link
	href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/theme/jquery-ui.css"
	rel="stylesheet" type="text/css" />

jQuery Plugins

There are some guidelines that you must follow as a jQuery plugin:

jQuery Plugin template

This template demonstrates some of the guidelines of a jQuery plugin

jQuery.fn.myplugin = function(options) {
	var defaults = {...};
	var params = jQuery.extend(defaults, options);
	this.each(function(idx, e) {
		// do stuff with jQuery(e) instead of $(e)
	});
	// If you don't need a return, then enable chaining
	return this;
};

Exercise: jQuery W3C Plugin