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.
Learning jQuery will be an exercise in your ability to navigate online APIs and documentation:
JavaScript is a powerful language, but it has many flaws:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
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.
window.onload = function() {
// do stuff with the DOM
}
$(document).ready(function() {
// do stuff with the DOM
});
$(function() {
// do stuff with the DOM
});
We will be working on a bouncing images example.
The $
aka jQuery
function selects elements from the DOM using most any CSS selector.
// id selector
var elem = $("#myid");
// group selector
var elems = $("#myid, p");
// context selector
var elems = $("#myid < div p");
// complex selector
var elems = $("#myid < h1.special:not(.classy)");
DOM method | jQuery equivalent |
---|---|
getElementById("id")
|
$("#id")
|
getElementsByTagName("tag")
|
$("tag")
|
getElementsByName("somename")
|
$("[name='somename']")
|
querySelector("selector")
|
$("selector")
|
querySelectorAll("selector")
|
$("selector")
|
p
tags that have no children, but only if they don't have a class of ignore
div
tags with a child that has a class of special
h1
, h2
, h3
, h4
, h5
, h6
)li
.#square
and periodically change it's position in a random direction.jQuery
object or the $
function depending on the context$
function always (even for ID selectors) returns an array-like object called a 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];
$
as a wrapper$
adds extra functionality to DOM elements$
will give it the jQuery upgrade
// convert regular DOM objects to a jQuery object
var elem = document.getElementById("myelem");
elem = $(elem);
var elems = document.querySelectorAll(".special");
elems = $(elems);
querySelectorAll()
and querySelector()
on any DOM
object.var list = document.getElementsByTagName("ul")[0]; var specials = list.querySelectorAll('li.special');
find
/ context parameterjQuery 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");
#box
childrenbox
element and change their position.
var elems = document.querySelectorAll("li");
for (var i = 0; i < elems.length; i++) {
var e = elems[i];
// do stuff with e
}
$("li").each(function(idx, e) {
// do stuff with e
});
for each
loop on either because they are not technically arrays, just array-like objects.
$("li").each(function(idx, e) {
// do stuff with e
});
false
to exit the loop early$
if we want:
$("li").each(function(idx, e) {
e = $(e);
// do stuff with e
});
this
keyword refers to the same selected element as e, so this is better jQuery
$("li").each(function() {
// do stuff with this
});
function highlightField() {
// turn text yellow and make it bigger
if (!$("#myid").hasClass("invalid")) {
$("#myid").addClass("highlight");
}
}
addClass
, removeClass
, hasClass
, toggleClass
manipulate CSS classesclassName
DOM property, but don't have to manually split by spaces
function biggerFont() {
// turn text yellow and make it bigger
var size = parseInt($("#clickme").css("font-size"));
$("#clickme").css("font-size", size + 4 + "pt");
}
css
function of the jQuery object allows reading pre-existing stylesfont-size
syntax instead of fontSize
css(property)
gets the property value, css(property, value)
sets the property value// bad!$("#main").css("top", $("#main").css("top") + 100 + "px");
"200px" + 100 + "px"
, "200px100px"
// correct
$("#main").css("top", parseInt($("#main").css("top")) + 100 + "px");
square
directly in the center of it's parent.#square
change direction when it reaches the boundary of it's parent.<ul> <li style="font-size: 10px">10px font size</li> <li style="font-size: 20px">20px font size</li> <li style="font-size: 30px">30px font size</li> </ul>
$("li").css("font-size"); // returns '10px'
$("li").css("font-size", "15px"); // sets all selected elements to '8px'
<ul> <li style="font-size: 15px">10px font size</li> <li style="font-size: 15px">20px font size</li> <li style="font-size: 15px">30px font size</li> </ul>
Many jQuery object methods are overloaded
$("#myid").css(propertyName);
$("#myid").css(propertyName, value);
$("#myid").css({ 'propertyName1': value1, 'propertyName2': value2, ... });
$("#myid").css(propertyName, function(idx, oldValue) { return newValue; });
What do you think the multi-modifier syntax is?
// bad jQuery$("#main").css("top", parseInt($("#main").css("top")) + 100 + "px");
$("#main").css("top", function(idx, old) {
return parseInt(old) + 100 + "px";
}); // good jQuery
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 |
$("#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 :(
div
s with a class of square
to the html.background-color
of each square when it hits a wall.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
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 |
innerHTML
hackingWhy not just code the previous example this way?
document.getElementById("myid").innerHTML += "<p>A paragraph!</p>";
"
and '
document.getElementById("myid").innerHTML += "<p style='color: red; " + "margin-left: 50px;' " + "onclick='myOnClick();'>" + "A paragraph!</p>";
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";
Every DOM element object has these methods:
name | description |
---|---|
appendChild(node)
|
places given node at end of this node's child list |
insertBefore(new, old)
|
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(new, old)
|
replaces given child with new node |
var p = document.createElement("p"); p.innerHTML = "A paragraph!"; document.getElementById("myid").appendChild(p);
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]); } }
removeChild
method to remove the given child from the page
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();
.square div
s to the page using jQuery.div
s to be img
tags with a src
of laughing_man.jpg.$("<p id='myid' class='special'>My paragraph is awesome!</p>")
$("<p>") .attr("id", "myid") .addClass("special") .text("My paragraph is awesome!");
$("<p>", { "id": "myid", "class": "special", "text": "My paragraph is awesome!" });
$
function signatures$(function);
$("selector", [context]);
$(elements);
$("<html>", [properties]);
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); }
$("#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); });
$("#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"); } }));
abort
|
blur
|
change
|
click
|
dblclick
|
error
|
focus
|
keydown
|
keypress
|
keyup
|
load
|
mousedown
|
mousemove
|
mouseout
|
mouseover
|
mouseup
|
reset
|
resize
|
select
|
submit
|
unload
|
click
event (onclick
) is just one of many events that can be handled
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 }
event
method
$("#play").click();
You often need to attach an event handler to a group of elements.
var btns = document.querySelectorAll("#game > button.control"); for (var i = 0; i < gameButtons.length; i++) { btns[i].observe("click", gameButtonClick); } function gameButtonClick(evt) { ... }
$("#game > button.control").click(gameButtonClick); function gameButtonClick(evt) { ... }
We will elaborate on the bounce.html example.
mouseover
an img
it's
src
changes to dai_gurren.jpg
#square
element, change it's background-color
instead.
addEventListener
DOM method.
document.getElementById("myid").addEventListener("click", function);
var evt = document.createEvent("click"); evt.initEvent("click", true, true); document.getElementById("myid").dispatchEvent("click");
$("#myid").on("event", handler);
$("#myid").trigger("event");
var evt = $.Event("event");
// do stuff with evt to make it special
$("#myid").trigger(evt);
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 |
<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!
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!"); }
name | description |
---|---|
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
object.
$(window).on('contextmenu', function);
<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();
}
}
preventDefault()
method on 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!
<body> <div> <p> Events are <em>crazy</em>! </p> </div> </body>
<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); }
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(); }
<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
function anotherHandler(evt) { alert("You clicked on the inner P tag"); evt.stopImmediatePropagation(); }
stopImmediatePropagation()
to prevent any further handlers from being executed.$("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 });
evt.preventDefault()
evt.stopPropagation()
<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;
}
}
$.ajax({ "url": "http://foo.com", "option" : "value", "option" : "value", ... "option" : "value" });
$.ajax()
methodurl
to fetch, as a String,type
of the request, GET or POSTXMLHttpRequest
; works well in all browsers$.ajax()
optionsoption | 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 |
$.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);
}
success
and error
eventsThis example uses this output page
textarea
The data passed to your success handler will be in whatever format you specified in the dataType
option
dataType
of text returns raw text no matter its apparent data typedataType
of html returns raw html textdataType
of xml returns an XML document objectdataType
of json returns a JSON object$.ajax( "url": "http://foo.com", "type": "GET", "success": functionName, "error": ajaxFailure }); ... function ajaxFailure(xhr, status, exception) { console.log(xhr, status, exception); }
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.
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.
$.ajax("lookup_account.php", { "type": "get", "data": { "name": "Ed Smith", "age": 29, "password": "abcdef" }, }) .done(function) .fail(ajaxFailure);
"?" +
...
data
object literal
"name=Ed+Smith&age=29&password=abcdef"
)POST
request$.ajax("url", { "type": "POST", "data": { "name": value, "name": value, ..., "name": value }, }) .done(function) .fail(ajaxFailure);
type
should be changed to "POST"
(GET
is default)$.get()
and $.post()
instead$.get()
and $.post()
shortcuts$.ajax()
function
$.get(url, [data]) .done(function) .fail(function);
$.post(url, [data]) .done(function) .fail(function);
$.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
This example uses the quotes page
quote.php
.count
parameter to quote.php
so we can get multiple quotes.$.ajaxSetup()
functionOften your Ajax requests use very similar option values.
"timeout": 1000
"cache": Math.random()
"error": ajaxFailure
$.ajaxSetup({ "option": "value", "option": "value", ... });
always()
The general technique is to show()
some feedback when the Ajax request starts
and hide()
it again once it finishes.
always()
function is an event that the Ajax request fires everytime the request finishes, whether it was successful or not$.get("url") .done(function) .error(function) .always(function() { $("#loader").hide(); }); $("#loader").show();
click()
event methodevent 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 |
$(function() { $("#loader") .hide() .ajaxStart(function() { $(this).show(); }).ajaxStop(function() { $(this).hide(); }); $("#mybutton").click(function() { $.get("http://foo.com") .done(function) .error(ajaxFailure); }); });
$.get("foo.xml")
.done(functionName);
function functionName(xmlDom) {
// do stuff with the xmlDom just like you would with the HTML dom
}
xmlDom
is the XML equivalent of document
in the HTML DOM, it is not the root tagYou use the same jQuery functions to interact with the XML DOM, with one minor tweak:
$(xmlDom).find("tagName");
// You can use complicated CSS selectors
$(xmlDom).find("ingredient[quantity='5']");
$(xmlDom).find("tagName") .parent() .children() .each(function);
$(xmlDom).find("directions") .attr("time", "0") .text("make the dish :P");
<?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"
<?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>
// 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)); });
$.get("foo.json")
.done(functionName);
function functionName(jsonObj) {
// do stuff with the jsonObj
}
jQuery UI : a JavaScript library, built on top of jQuery, that adds:
<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" />
.js
files to your project folder
(appearing)
(disappearing)
(Getting attention)
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");
animate()
element.effect(effectName, { option: value, option: value, ... });
$("#myid").effect("explode", { "pieces": 25 });
Normal
25 Pieces
{}
)$('#demo_chaining') .effect('pulsate') .effect('highlight') .effect('explode');
duration
optionslow
, normal
, fast
or any number in milliseconds$('#myid').effect('puff', {}, duration)
animate()
$('#myid').animate(properties, [duration]);
$('#myid') .animate({ 'font-size': '80px', 'color': 'green' }, 1000);
This is a demo!!!
$('#myid') .animate(properties, [duration], [easing]);
$('#myid') .animate({ 'font-size': '80px', 'color': 'green' }, 1000, 'easeOutBounce');
This is a demo!!!
toggleClass()
toggleClass
method with its optional duration
parameter
.special { font-size: 50px; color: red; }
$('#myid').toggleClass('special', 3000);
This is a demo!!!
delay()
$('#myid') .effect('pulsate') .delay(1000) .slideUp() .delay(3000) .show('fast');
$("#myid").effect('puff', [options], [duration], [function]);
this
keyword as usual to address the element the effect was attached to$('#myid').effect('clip', {}, 'default', function() { alert('finished'); });
$('#myid').effect('pulsate', {}, 'default', function() { $(this).effect('explode', {'pieces': 25}, 'default', function() { $(this).show('slow', {}, 'default', function() { $(this).hide('fast'); }); }); });
$('#myid') .effect('pulsate') .effect('explode', { 'pieces': 25 }).show('slow') .hide('fast');This works because the effects are queued up rather than applied immediately.
jQuery UI provides several methods for creating drag-and-drop functionality:
Sortable
$('#myid ul').sortable([options]);
ul
, ol
) as being able to be dragged into any orderDraggable
s and Droppable
sdisabled
appendTo
axis
cancel
connectWith
containment
cursor
cursorAt
delay
distance
dropOnEmpty
forceHelperSize
opacity
revert
tolerance
.sortable('destroy')
on the sortable elementSortable
demo<ol id="simpsons"> <li>Homer</li> <li>Marge</li> <li>Bart</li> <li>Lisa</li> <li>Maggie</li> </ol>
$(function() { $("#simpsons").sortable(); });
Sortable
list eventsevent | 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
}
});
});
ui
parameter with info about the eventSortable
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');
}
destroy
disable
enable
option
refresh
cancel
$('#my_list').sortable('methodName', [arguments]);
// Some examples
$('#my_list').sortable('destroy');
$('#my_list').sortable('option', 'cursor', 'pointer');
Draggable
$('#myid').draggable([options]);
Options:
disabled
appendTo
addClasses
connectToSortable
delay
distance
grid
Methods:
destroy
disable
enable
option
widget
Events:
create
start
drag
stop
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] });
Droppable
$('#myid').droppable([options]);
Options:
disabled
accept
activeClass
hoverClass
scope
greedy
tolerance
Methods:
destroy
disable
enable
option
widget
Events:
create
over
out
drop
activate
deactivate
<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')); }
Scriptaculous offers ways to make a text box that auto-completes based on prefix strings *:
var data = ["foo", "food", "foobar", "fooly", "cake"]; $('#my_text_input').autocompleter({ 'source': data });
term
parameter with the current value of the input field
$('#my_text_input').autocompleter({ 'source': 'http://foo.com/webservice.php' });
* (won't be necessary once HTML5 datalist
element is well supported)
var data = ["foo", "food", "foobar", "foolish", "foiled", "cake"]; $('#myid').autocompleter({ 'source': data });
label
and value
fields
var data = [ {'label': 'Track and Field', 'value': 'track'}, {'label': 'Gymnastics', 'value': 'gymnastics'}, ... ];
ul
elements full of choices as you typeappendTo
option to specify where the list is inserted<input id="bands70s" size="40" type="text" /> <div id="bandlistarea"></div>
$('#bands70s').autocomplete({ 'source': data, 'appendTo': '#bandlistarea' });
$('#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);
term
parameterlabel
and value
fieldsaccordion
widgetaccordion
<div class="accordion"> <h1><a href="#">Section 1</a></h1> <div>Section 1 Content</div> ... </div>
tabs
widgethref
attributes should match id
s of elements on the page<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.
class
es gratuitously so that we can style our widgets however we wantclass
es which exist for all widgetsclass
eskind | class es |
---|---|
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
|
ui class
es in your CSS to roll your own theme<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/theme/jquery-ui.css" rel="stylesheet" type="text/css" />
jQuery.fn
is this prototypeThere are some guidelines that you must follow as a jQuery plugin:
$
, instead use its alias jQuery
This template demonstrates some of the guidelines of a jQuery plugin
extend
function which merges two objects into onejQuery.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; };