add(selector, elements, html, selector, context) -> jQuery (Miscellaneous Traversing)
# A string containing a selector expression to match additional elements against.
$("div").css("border", "2px solid red")
.add("p")
.css("background", "yellow");
addClass(className, function(index, class)) -> jQuery (Attributes)
# One or more class names to be added to the class attribute of each matched element.
$("p:last").addClass("selected");
after(content, function(index)) -> jQuery (DOM Insertion, Outside)
# An element, HTML string, or jQuery object to insert after each element in the set of matched elements.
$("p").after("<b>Hello</b>");
ajaxComplete(handler(event, XMLHttpRequest, ajaxOptions)) -> jQuery (Global Ajax Event Handlers)
# The function to be invoked.
$("#msg").ajaxComplete(function(event,request, settings){
$(this).append("<li>Request Complete.</li>");
});
ajaxError(handler(event, XMLHttpRequest, ajaxOptions, thrownError)) -> jQuery (Global Ajax Event Handlers)
# The function to be invoked.
$("#msg").ajaxError(function(event, request, settings){
$(this).append("<li>Error requesting page " + settings.url + "</li>");
});
ajaxSend(handler(event, XMLHttpRequest, ajaxOptions)) -> jQuery (Global Ajax Event Handlers)
# The function to be invoked.
$("#msg").ajaxSend(function(evt, request, settings){
$(this).append("<li>Starting request at " + settings.url + "</li>");
});
ajaxStart(handler()) -> jQuery (Global Ajax Event Handlers)
# The function to be invoked.
$("#loading").ajaxStart(function(){
$(this).show();
});
ajaxStop(handler()) -> jQuery (Global Ajax Event Handlers)
# The function to be invoked.
$("#loading").ajaxStop(function(){
$(this).hide();
});
ajaxSuccess(handler(event, XMLHttpRequest, ajaxOptions)) -> jQuery (Global Ajax Event Handlers)
# The function to be invoked.
$("#msg").ajaxSuccess(function(evt, request, settings){
$(this).append("<li>Successful Request!</li>");
});
all() -> (Basic)
# Selects all elements.
var elementCount = $("*").css("border","3px solid red").length;
$("body").prepend("<h3>" + elementCount + " elements found</h3>");
andSelf() -> jQuery (Miscellaneous Traversing)
# Add the previous set of elements on the stack to the current set.
$("div").find("p").andSelf().addClass("border");
$("div").find("p").addClass("background");
animate(properties, duration, easing, callback, properties, options) -> jQuery (Custom)
# Perform a custom animation of a set of CSS properties.
// Using multiple unit types within one animation.
$("#go").click(function(){
$("#block").animate({
width: "70%",
opacity: 0.4,
marginLeft: "0.6in",
fontSize: "3em",
borderWidth: "10px"
}, 1500 );
});
animated() -> (Basic Filter)
# Select all elements that are in the progress of an animation at the time the selector is run.
$("#run").click(function(){
$("div:animated").toggleClass("colored");
});
function animateIt() {
$("#mover").slideToggle("slow", animateIt);
}
animateIt();
append(content, function(index, html)) -> jQuery (DOM Insertion, Inside)
# An element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
$("p").append("<strong>Hello</strong>");
appendTo(target) -> jQuery (DOM Insertion, Inside)
# A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.
$("span").appendTo("#foo"); // check append() examples
attr(attributeName) -> String (Attributes)
# The name of the attribute to get.
var title = $("em").attr("title");
$("div").text(title);
attr(attributeName, value, map, attributeName, function(index, attr)) -> jQuery (Attributes)
# The name of the attribute to set.
$("img").attr({
src: "/images/hat.gif",
title: "jQuery",
alt: "jQuery Logo"
});
$("div").text($("img").attr("alt"));
attributeContains(attribute, value) -> (Attribute)
# An attribute name.
$("input[name*='man']").val("has man in it!");
attributeContainsPrefix(attribute, value) -> (Attribute)
# An attribute name.
$('a[hreflang|=en]').css('border','3px dotted green');
attributeContainsWord(attribute, value) -> (Attribute)
# An attribute name.
$("input[name~=man]").val("mr. man is in it!");
attributeEndsWith(attribute, value) -> (Attribute)
# An attribute name.
$("input[name$='letter']").val("a letter");
attributeEquals(attribute, value) -> (Attribute)
# An attribute name.
$("input[name='newsletter']").next().text(" is newsletter");
attributeHas(attribute) -> (Attribute)
# An attribute name.
$("div[id]").one("click", function(){
var idString = $(this).text() + " = " + $(this).attr("id");
$(this).text(idString);
});
attributeMultiple(attributeFilter1, attributeFilter2, attributeFilterN) -> (Attribute)
# An attribute filter.
$("input[id][name$='man']").val("only this one");
attributeNotEqual(attribute, value) -> (Attribute)
# An attribute name.
$("input[name!=newsletter]").next().append("<b>; not newsletter</b>");
attributeStartsWith(attribute, value) -> (Attribute)
# An attribute name.
$("input[name^='news']").val("news here!");
before(content, function) -> jQuery (DOM Insertion, Outside)
# An element, HTML string, or jQuery object to insert before each element in the set of matched elements.
$("p").before("<b>Hello</b>");
bind(eventType, eventData, handler(eventObject), events) -> jQuery (Event Handler Attachment)
# A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.
$("p").bind("click", function(event){
var str = "( " + event.pageX + ", " + event.pageY + " )";
$("span").text("Click happened! " + str);
});
$("p").bind("dblclick", function(){
$("span").text("Double-click happened in " + this.nodeName);
});
$("p").bind("mouseenter mouseleave", function(event){
$(this).toggleClass("over");
});
blur(handler(eventObject)) -> jQuery (Form Events)
# Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.
$("p").blur();
button() -> (Form)
# Selects all button elements and elements of type button.
var input = $(":button").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
change(handler(eventObject)) -> jQuery (Form Events)
# Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
checkbox() -> (Form)
# Selects all elements of type checkbox.
var input = $("form input:checkbox").wrap('<span></span>').parent().css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
checked() -> (Form)
# Matches all elements that are checked.
function countChecked() {
var n = $("input:checked").length;
$("div").text(n + (n <= 1 ? " is" : " are") + " checked!");
}
countChecked();
$(":checkbox").click(countChecked);
child(parent, child) -> (Hierarchy)
# Any valid selector.
$("ul.topnav > li").css("border", "3px double red");
children(selector) -> jQuery (Tree Traversal)
# A string containing a selector expression to match elements against.
$("#container").click(function (e) {
$("*").removeClass("hilite");
var $kids = $(e.target).children();
var len = $kids.addClass("hilite").length;
$("#results span:first").text(len);
$("#results span:last").text(e.target.tagName);
e.preventDefault();
return false;
});
class(class) -> (Basic)
# A class to search for. An element can have multiple classes; only one of them must match.
$(".myClass").css("border","3px solid red");
clearQueue(queueName) -> jQuery (Custom)
# A string containing the name of the queue. Defaults to fx, the standard effects queue.
$("#start").click(function () {
$("div").show("slow");
$("div").animate({left:'+=200'},5000);
$("div").queue(function () {
$(this).addClass("newcolor");
$(this).dequeue();
});
$("div").animate({left:'-=200'},1500);
$("div").queue(function () {
$(this).removeClass("newcolor");
$(this).dequeue();
});
$("div").slideUp();
});
$("#stop").click(function () {
$("div").clearQueue();
$("div").stop();
});
click(handler(eventObject)) -> jQuery (Mouse Events)
# Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
$("p").click(function () {
$(this).slideUp();
});
$("p").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});
clone(withDataAndEvents) -> jQuery (Copying)
# A Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4 element data will be copied as well.
$("b").clone().prependTo("p");
closest(selector, selector, context) -> jQuery (Tree Traversal)
# A string containing a selector expression to match elements against.
$(document).bind("click", function (e) {
$(e.target).closest("li").toggleClass("hilight");
});
closest(selectors, context) -> Array (Tree Traversal)
# An array or string containing a selector expression to match elements against (can also be a jQuery object).
var close = $("li:first").closest(["ul", "body"]);
$.each(close, function(i){
$("li").eq(i).html( this.selector + ": " + this.elem.nodeName );
});
contains(text) -> (Content Filter)
# Select all elements that contain the specified text.
$("div:contains('John')").css("text-decoration", "underline");
contents() -> jQuery (Miscellaneous Traversing)
# Get the children of each element in the set of matched elements, including text nodes.
$("p").contents().filter(function(){ return this.nodeType != 1; }).wrap("<b/>");
context() -> Element (Plugin Authoring)
# The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document.
$("ul")
.append("<li>" + $("ul").context + "</li>")
.append("<li>" + $("ul", document.body).context.nodeName + "</li>");
css(propertyName) -> String (CSS)
# A CSS property.
$("div").click(function () {
var color = $(this).css("background-color");
$("#result").html("That div is <span style='color:" +
color + ";'>" + color + "</span>.");
});
css(propertyName, value, propertyName, function(index, value), map) -> jQuery (CSS)
# A CSS property name.
$("p").mouseover(function () {
$(this).css("color","red");
});
data(key) -> Object (Data)
# Name of the data stored.
$("button").click(function(e) {
var value;
switch ($("button").index(this)) {
case 0 :
value = $("div").data("blah");
break;
case 1 :
$("div").data("blah", "hello");
value = "Stored!";
break;
case 2 :
$("div").data("blah", 86);
value = "Stored!";
break;
case 3 :
$("div").removeData("blah");
value = "Removed!";
break;
}
$("span").text("" + value);
});
data(key, value, obj) -> jQuery (Data)
# A string naming the piece of data to set.
$("div").data("test", { first: 16, last: "pizza!" });
$("span:first").text($("div").data("test").first);
$("span:last").text($("div").data("test").last);
dblclick(handler(eventObject)) -> jQuery (Mouse Events)
# Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.
$("p").dblclick( function () { alert("Hello World!"); });
delay(duration, queueName) -> jQuery (Custom)
# An integer indicating the number of milliseconds to delay execution of the next item in the queue.
$("button").click(function() {
$("div.first").slideUp(300).delay(800).fadeIn(400);
$("div.second").slideUp(300).fadeIn(400);
});
delegate(selector, eventType, handler, selector, eventType, eventData, handler) -> jQuery (Event Handler Attachment)
# Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
$("body").delegate("p", "click", function(){
$(this).after("<p>Another paragraph!</p>");
});
dequeue(queueName) -> jQuery (Custom)
# A string containing the name of the queue. Defaults to fx, the standard effects queue.
$("button").click(function () {
$("div").animate({left:'+=200px'}, 2000);
$("div").animate({top:'0px'}, 600);
$("div").queue(function () {
$(this).toggleClass("red");
$(this).dequeue();
});
$("div").animate({left:'10px', top:'30px'}, 700);
});
descendant(ancestor, descendant) -> (Hierarchy)
# Any valid selector.
$("form input").css("border", "2px dotted blue");
detach(selector) -> jQuery (DOM Removal)
# A selector expression that filters the set of matched elements to be removed.
$("p").click(function(){
$(this).toggleClass("off");
});
var p;
$("button").click(function(){
if ( p ) {
p.appendTo("body");
p = null;
} else {
p = $("p").detach();
}
});
die() -> jQuery (Event Handler Attachment)
# Remove all event handlers previously attached using .live() from the elements.
die(eventType, handler) -> jQuery (Event Handler Attachment)
# Remove an event handler previously attached using .live() from the elements.
function aClick() {
$("div").show().fadeOut("slow");
}
$("#bind").click(function () {
$("#theone").live("click", aClick)
.text("Can Click!");
});
$("#unbind").click(function () {
$("#theone").die("click", aClick)
.text("Does nothing...");
});
disabled() -> (Form)
# Selects all elements that are disabled.
$("input:disabled").val("this is it");
each(function(index, Element)) -> jQuery (Collection Manipulation)
# A function to execute for each matched element.
$(document.body).click(function () {
$("div").each(function (i) {
if (this.style.color != "blue") {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
});
element(element) -> (Basic)
# An element to search for. Refers to the tagName of DOM nodes.
$("div").css("border","9px solid red");
empty() -> (Content Filter)
# Select all elements that have no children (including text nodes).
$("td:empty").text("Was empty!").css('background', 'rgb(255,220,200)');
empty() -> jQuery (DOM Removal)
# Remove all child nodes of the set of matched elements from the DOM.
$("button").click(function () {
$("p").empty();
});
enabled() -> (Form)
# Selects all elements that are enabled.
$("input:enabled").val("this is it");
end() -> jQuery (Miscellaneous Traversing)
# End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
jQuery.fn.showTags = function (n) {
var tags = this.map(function () {
return this.tagName;
})
.get().join(", ");
$("b:eq(" + n + ")").text(tags);
return this;
};
$("p").showTags(0)
.find("span")
.showTags(1)
.css("background", "yellow")
.end()
.showTags(2)
.css("font-style", "italic");
eq(index) -> (Basic Filter)
# Zero-based index of the element to match.
$("td:eq(2)").css("color", "red");
eq(index, -index) -> jQuery (Filtering)
# An integer indicating the 0-based position of the element.
$("div").eq(2).addClass("blue");
error(handler(eventObject)) -> jQuery (Browser Events)
# Bind an event handler to the "error" JavaScript event.
$(window).error(function(){
return true;
});
even() -> (Basic Filter)
# Selects even elements, zero-indexed. See also odd.
$("tr:even").css("background-color", "#bbbbff");
event.currentTarget() -> Element (Event Object)
# The current DOM element within the event bubbling phase.
$("p").click(function(event) {
alert( event.currentTarget === this ); // true
});
event.data() -> Anything (Event Object)
# Contains the optional data passed to jQuery.fn.bind when the current executing handler was bound.
$("a").each(function(i) {
$(this).bind('click', {index:i}, function(e){
alert('my index is ' + e.data.index);
});
});
event.isDefaultPrevented() -> Boolean (Event Object)
# Returns whether event.preventDefault() was ever called on this event object.
$("a").click(function(event){
alert( event.isDefaultPrevented() ); // false
event.preventDefault();
alert( event.isDefaultPrevented() ); // true
});
event.isImmediatePropagationStopped() -> Boolean (Event Object)
# Returns whether event.stopImmediatePropagation() was ever called on this event object.
$("p").click(function(event){
alert( event.isImmediatePropagationStopped() );
event.stopImmediatePropagation();
alert( event.isImmediatePropagationStopped() );
});
event.isPropagationStopped() -> Boolean (Event Object)
# Returns whether event.stopPropagation() was ever called on this event object.
$("p").click(function(event){
alert( event.isPropagationStopped() );
event.stopPropagation();
alert( event.isPropagationStopped() );
});
event.pageX() -> Number (Event Object)
# The mouse position relative to the left edge of the document.
$(document).bind('mousemove',function(e){
$("#log").text("e.pageX: " + e.pageX + ", e.pageY: " + e.pageY);
});
event.pageY() -> Number (Event Object)
# The mouse position relative to the top edge of the document.
$(document).bind('mousemove',function(e){
$("#log").text("e.pageX: " + e.pageX + ", e.pageY: " + e.pageY);
});
event.preventDefault() -> undefined (Event Object)
# If this method is called, the default action of the event will not be triggered.
$("a").click(function(event) {
event.preventDefault();
$('<div/>')
.append('default ' + event.type + ' prevented')
.appendTo('#log');
});
event.relatedTarget() -> Element (Event Object)
# The other DOM element involved in the event, if any.
$("a").mouseout(function(event) {
alert(event.relatedTarget.nodeName); // "DIV"
});
event.result() -> Object (Event Object)
# This attribute contains the last value returned by an event handler that was triggered by this event, unless the value was undefined.
$("p").click(function(event) {
return "hey"
});
$("p").click(function(event) {
alert( event.result );
});
event.stopImmediatePropagation() -> (Event Object)
# Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree
$("p").click(function(event){
event.stopImmediatePropagation();
});
$("p").click(function(event){
// This function won't be executed
$(this).css("background-color", "#f00");
});
$("div").click(function(event) {
// This function will be executed
$(this).css("background-color", "#f00");
});
event.stopPropagation() -> (Event Object)
# Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$("p").click(function(event){
event.stopPropagation();
// do something
});
event.target() -> Element (Event Object)
# The DOM element that initiated the event.
$("body").click(function(event) {
$("#log").html("clicked: " + event.target.nodeName);
});
event.timeStamp() -> Number (Event Object)
# This attribute returns the number of milliseconds since January 1, 1970, when the event is triggered.
var last, diff;
$('div').click(function(event) {
if ( last ) {
diff = event.timeStamp - last
$('div').append('time since last event: ' + diff + '<br/>');
} else {
$('div').append('Click again.<br/>');
}
last = event.timeStamp;
});
event.type() -> String (Event Object)
# Describes the nature of the event.
$("a").click(function(event) {
alert(event.type); // "click"
});
event.which() -> String (Event Object)
# For key or button events, this attribute indicates the specific button or key that was pressed.
$('#whichkey').bind('keydown',function(e){
$('#log').html(e.type + ': ' + e.which );
});
fadeIn(duration, callback) -> jQuery (Fading)
# Display the matched elements by fading them to opaque.
$(document.body).click(function () {
$("div:hidden:first").fadeIn("slow");
});
fadeOut(duration, callback) -> jQuery (Fading)
# Hide the matched elements by fading them to transparent.
$("p").click(function () {
$("p").fadeOut("slow");
});
fadeTo(duration, opacity, callback) -> jQuery (Fading)
# Adjust the opacity of the matched elements.
$("p:first").click(function () {
$(this).fadeTo("slow", 0.33);
});
file() -> (Form)
# Selects all elements of type file.
var input = $("input:file").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
filter(selector, function(index)) -> jQuery (Filtering)
# A string containing a selector expression to match elements against.
$("div").css("background", "#c8ebcc")
.filter(".middle")
.css("border-color", "red");
find(selector) -> jQuery (Tree Traversal)
# A string containing a selector expression to match elements against.
$("p").find("span").css('color','red');
first() -> jQuery (Filtering)
# Reduce the set of matched elements to the first in the set.
$("p span").first().addClass('highlight');
first() -> (Basic Filter)
# Selects the first matched element.
$("tr:first").css("font-style", "italic");
first-child() -> (Child Filter)
# Selects all elements that are the first child of their parent.
$("div span:first-child")
.css("text-decoration", "underline")
.hover(function () {
$(this).addClass("sogreen");
}, function () {
$(this).removeClass("sogreen");
});
focus(handler(eventObject)) -> jQuery (Form Events)
# Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.
$("input").focus(function () {
$(this).next("span").css('display','inline').fadeOut(1000);
});
focusin(handler(eventObject)) -> jQuery (Keyboard Events)
# Bind an event handler to the "focusin" JavaScript event.
$("p").focusin(function() {
$(this).find("span").css('display','inline').fadeOut(1000);
});
focusout(handler(eventObject)) -> jQuery (Keyboard Events)
# Bind an event handler to the "focusout" JavaScript event.
$("p").focusout(function() {
$(this).find("span").css('display','inline').fadeOut(1000);
});
get(index) -> Element, Array (DOM Element Methods)
# A zero-based integer indicating which element to retrieve.
function disp(divs) {
var a = [];
for (var i = 0; i < divs.length; i++) {
a.push(divs[i].innerHTML);
}
$("span").text(a.join(" "));
}
disp( $("div").get().reverse() );
gt(index) -> (Basic Filter)
# Select all elements at an index greater than index within the matched set.
$("td:gt(4)").css("text-decoration", "line-through");
has(selector, contained) -> jQuery (Filtering)
# A string containing a selector expression to match elements against.
$("ul").append("<li>" + ($("ul").has("li").length ? "Yes" : "No") + "</li>");
$("ul").has("li").addClass("full");
has(selector) -> (Content Filter)
# Selects elements which contain at least one element that matches the specified selector.
$("div:has(p)").addClass("test");
hasClass(className) -> Boolean (Attributes)
# The class name to search for.
$("div#result1").append($("p:first").hasClass("selected").toString());
$("div#result2").append($("p:last").hasClass("selected").toString());
$("div#result3").append($("p").hasClass("selected").toString());
header() -> (Basic Filter)
# Selects all elements that are headers, like h1, h2, h3 and so on.
$(":header").css({ background:'#CCC', color:'blue' });
height(value, function(index, height)) -> jQuery (CSS)
# An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string).
$("div").one('click', function () {
$(this).height(30)
.css({cursor:"auto", backgroundColor:"green"});
});
height() -> Integer (CSS)
# Get the current computed height for the first element in the set of matched elements.
function showHeight(ele, h) {
$("div").text("The height for the " + ele +
" is " + h + "px.");
}
$("#getp").click(function () {
showHeight("paragraph", $("p").height());
});
$("#getd").click(function () {
showHeight("document", $(document).height());
});
$("#getw").click(function () {
showHeight("window", $(window).height());
});
hidden() -> (Version 1.0)
# Selects all elements that are hidden.
// in some browsers :hidden includes head, title, script, etc... so limit to body
$("span:first").text("Found " + $(":hidden", document.body).length +
" hidden elements total.");
$("div:hidden").show(3000);
$("span:last").text("Found " + $("input:hidden").length + " hidden inputs.");
hide(duration, callback) -> jQuery (Basics)
# Hide the matched elements.
$("p").hide();
$("a").click(function () {
$(this).hide();
return true;
});
hover(handlerIn(eventObject), handlerOut(eventObject)) -> jQuery (Mouse Events)
# Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
$("li").hover(
function () {
$(this).append($("<span> ***</span>"));
},
function () {
$(this).find("span:last").remove();
}
);
//li with fade class
$("li.fade").hover(function(){$(this).fadeOut(100);$(this).fadeIn(500);});
hover(handlerInOut(eventObject)) -> jQuery (Mouse Events)
# Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.
$("li")
.filter(":odd")
.hide()
.end()
.filter(":even")
.hover(
function () {
$(this).toggleClass("active")
.next().stop(true, true).slideToggle();
}
);
html(htmlString, function(index, html)) -> jQuery (Attributes)
# A string of HTML to set as the content of each matched element.
$("div").html("<span class='red'>Hello <b>Again</b></span>");
html() -> String (Attributes)
# Get the HTML contents of the first element in the set of matched elements.
$("p").click(function () {
var htmlStr = $(this).html();
$(this).text(htmlStr);
});
id(id) -> (Basic)
# An ID to search for, specified via the id attribute of an element.
$("#myDiv").css("border","3px solid red");
image() -> (Form)
# Selects all elements of type image.
var input = $("input:image").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
index(selector, element) -> Number (DOM Element Methods)
# A selector representing a jQuery collection in which to look for an element.
$("div").click(function () {
// this is the dom element clicked
var index = $("div").index(this);
$("span").text("That was div index #" + index);
});
innerHeight() -> Integer (CSS)
# Get the current computed height for the first element in the set of matched elements, including padding but not border.
var p = $("p:first");
$("p:last").text( "innerHeight:" + p.innerHeight() );
innerWidth() -> Integer (CSS)
# Get the current computed width for the first element in the set of matched elements, including padding but not border.
var p = $("p:first");
$("p:last").text( "innerWidth:" + p.innerWidth() );
input() -> (Form)
# Selects all input, textarea, select and button elements.
var allInputs = $(":input");
var formChildren = $("form > *");
$("#messages").text("Found " + allInputs.length + " inputs and the form has " +
formChildren.length + " children.");
// so it won't submit
$("form").submit(function () { return false; });
insertAfter(target) -> jQuery (DOM Insertion, Outside)
# A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter.
$("p").insertAfter("#foo"); // check after() examples
insertBefore(target) -> jQuery (DOM Insertion, Outside)
# A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter.
$("p").insertBefore("#foo"); // check before() examples
is(selector) -> Boolean (Filtering)
# A string containing a selector expression to match elements against.
$("div").one('click', function () {
if ($(this).is(":first-child")) {
$("p").text("It's the first div.");
} else if ($(this).is(".blue,.red")) {
$("p").text("It's a blue or red div.");
} else if ($(this).is(":contains('Peter')")) {
$("p").text("It's Peter!");
} else {
$("p").html("It's nothing <em>special</em>.");
}
$("p").hide().slideDown("slow");
$(this).css({"border-style": "inset", cursor:"default"});
});
jQuery(html, ownerDocument, html, props) -> jQuery (Core)
# A string of HTML to create on the fly. Note that this parses HTML, not XML.
$("<div><p>Hello</p></div>").appendTo("body")
jQuery(selector, context, element, elementArray, jQuery object) -> jQuery (Core)
# A string containing a selector expression
$("div > p").css("border", "1px solid gray");
jQuery(callback) -> jQuery (Core)
# The function to execute when the DOM is ready.
$(function(){
// Document is ready
});
jQuery.ajax(settings) -> XMLHttpRequest (Low-Level Interface)
# A set of key/value pairs that configure the Ajax request. All options are optional. A default can be set for any option with $.ajaxSetup().
$.ajax({
type: "GET",
url: "test.js",
dataType: "script"
});
jQuery.ajaxSetup(options) -> (Low-Level Interface)
# A set of key/value pairs that configure the default Ajax request. All options are optional.
$.ajaxSetup({
url: "/xmlhttp/",
global: false,
type: "POST"
});
$.ajax({ data: myData });
jQuery.boxModel() -> Boolean (Utilities)
# Deprecated in jQuery 1.3 (see jQuery.support). States if the current page, in the user's browser, is being rendered using the W3C CSS Box Model.
$("p").html("The box model for this iframe is: <span>" +
jQuery.boxModel + "</span>");
jQuery.browser() -> Map (Properties of the Global jQuery Object)
# We recommend against using this property, please try to use feature detection instead (see jQuery.support). Contains flags for the useragent, read from navigator.userAgent. While jQuery.browser will not be removed from future versions of jQuery, every effort to use jQuery.support and proper feature detection should be made.
jQuery.each(jQuery.browser, function(i, val) {
$("<div>" + i + " : <span>" + val + "</span>")
.appendTo(document.body);
});
jQuery.browser.version() -> String (Properties of the Global jQuery Object)
# The version number of the rendering engine for the user's browser.
$("p").html("The browser version is: <span>" +
jQuery.browser.version + "</span>");
jQuery.contains(container, contained) -> Boolean (Utilities)
# The DOM element that may contain the other element.
jQuery.contains(document.documentElement, document.body); // true jQuery.contains(document.body, document.documentElement); // false
jQuery.data(element, key, value) -> jQuery (Data)
# The DOM element to associate with the data.
var div = $("div")[0];
jQuery.data(div, "test", { first: 16, last: "pizza!" });
$("span:first").text(jQuery.data(div, "test").first);
$("span:last").text(jQuery.data(div, "test").last);
jQuery.data(element, key, element) -> Object (Data)
# The DOM element to query for the data.
$("button").click(function(e) {
var value, div = $("div")[0];
switch ($("button").index(this)) {
case 0 :
value = jQuery.data(div, "blah");
break;
case 1 :
jQuery.data(div, "blah", "hello");
value = "Stored!";
break;
case 2 :
jQuery.data(div, "blah", 86);
value = "Stored!";
break;
case 3 :
jQuery.removeData(div, "blah");
value = "Removed!";
break;
}
$("span").text("" + value);
});
jQuery.dequeue(element, queueName) -> jQuery (Data)
# A DOM element from which to remove and execute a queued function.
$("button").click(function () {
$("div").animate({left:'+=200px'}, 2000);
$("div").animate({top:'0px'}, 600);
$("div").queue(function () {
$(this).toggleClass("red");
$.dequeue( this );
});
$("div").animate({left:'10px', top:'30px'}, 700);
});
jQuery.each(collection, callback(indexInArray, valueOfElement)) -> Object (Utilities)
# The object or array to iterate over.
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("Mine is " + this + ".");
return (this != "three"); // will stop running after "three"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
jQuery.error(message) -> (Plugin Authoring)
# The message to send out.
jQuery.error = console.error;
jQuery.extend(target, object1, objectN, deep, target, object1, objectN) -> Object (Utilities)
# An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument.
var object1 = {
apple: 0,
banana: {weight: 52, price: 100},
cherry: 97
};
var object2 = {
banana: {price: 200},
durian: 100
};
$.extend(object1, object2);
jQuery.fx.off() -> Boolean (Custom)
# Globally disable all animations.
var toggleFx = function() {
$.fx.off = !$.fx.off;
};
toggleFx();
$("button").click(toggleFx)
$("input").click(function(){
$("div").toggle("slow");
});
jQuery.get(url, data, callback(data, textStatus, XMLHttpRequest), dataType) -> XMLHttpRequest (Shorthand Methods)
# A string containing the URL to which the request is sent.
$.get("test.php");
jQuery.getJSON(url, data, callback(data, textStatus)) -> XMLHttpRequest (Shorthand Methods)
# A string containing the URL to which the request is sent.
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data){
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});
jQuery.getScript(url, success(data, textStatus)) -> XMLHttpRequest (Shorthand Methods)
# A string containing the URL to which the request is sent.
$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
$("#go").click(function(){
$(".block").animate( { backgroundColor: 'pink' }, 1000)
.animate( { backgroundColor: 'blue' }, 1000);
});
});
jQuery.globalEval(code) -> (Utilities)
# The JavaScript code to execute.
function test(){
jQuery.globalEval("var newVar = true;")
}
test();
// newVar === true
jQuery.grep(array, function(elementOfArray, indexInArray), invert) -> Array (Utilities)
# Finds the elements of an array which satisfy a filter function. The original array is not affected.
var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];
$("div").text(arr.join(", "));
arr = jQuery.grep(arr, function(n, i){
return (n != 5 && i > 4);
});
$("p").text(arr.join(", "));
arr = jQuery.grep(arr, function (a) { return a != 9; });
$("span").text(arr.join(", "));
jQuery.inArray(value, array) -> Number (Utilities)
# The value to search for.
var arr = [ 4, "Pete", 8, "John" ];
$("span:eq(0)").text(jQuery.inArray("John", arr));
$("span:eq(1)").text(jQuery.inArray(4, arr));
$("span:eq(2)").text(jQuery.inArray("Karl", arr));
jQuery.isArray(obj) -> boolean (Utilities)
# Object to test whether or not it is an array.
$("b").append( "" + $.isArray([]) );
jQuery.isEmptyObject(object) -> Boolean (Utilities)
# The object that will be checked to see if it's empty.
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false
jQuery.isFunction(obj) -> boolean (Utilities)
# Object to test whether or not it is a function.
function stub() {
}
var objs = [
function () {},
{ x:15, y:20 },
null,
stub,
"function"
];
jQuery.each(objs, function (i) {
var isFunc = jQuery.isFunction(objs[i]);
$("span").eq(i).text(isFunc);
});
jQuery.isPlainObject(object) -> Boolean (Utilities)
# The object that will be checked to see if it's a plain object.
jQuery.isPlainObject({}) // true
jQuery.isPlainObject("test") // false
jQuery.isXMLDoc(node) -> Boolean (Utilities)
# The DOM node that will be checked to see if it's in an XML document.
jQuery.isXMLDoc(document) // false jQuery.isXMLDoc(document.body) // false
jQuery.makeArray(obj) -> Array (Utilities)
# Any object to turn into a native Array.
var elems = document.getElementsByTagName("div"); // returns a nodeList
var arr = jQuery.makeArray(elems);
arr.reverse(); // use an Array method on list of dom elements
$(arr).appendTo(document.body);
jQuery.map(array, callback(elementOfArray, indexInArray)) -> Array (Utilities)
# The Array to translate.
var arr = [ "a", "b", "c", "d", "e" ];
$("div").text(arr.join(", "));
arr = jQuery.map(arr, function(n, i){
return (n.toUpperCase() + i);
});
$("p").text(arr.join(", "));
arr = jQuery.map(arr, function (a) { return a + a; });
$("span").text(arr.join(", "));
jQuery.merge(first, second) -> Array (Utilities)
# Merge the contents of two arrays together into the first array.
$.merge( [0,1,2], [2,3,4] )
jQuery.noConflict(removeAll) -> Object (Core)
# A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).
jQuery.noConflict();
// Do something with jQuery
jQuery("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';
jQuery.noop() -> Function (Utilities)
# An empty function.
jQuery.param(obj, obj, traditional) -> String (Collection Manipulation)
# An array or object to serialize.
var params = { width:1680, height:1050 };
var str = jQuery.param(params);
$("#results").text(str);
jQuery.parseJSON(json) -> Object (Utilities)
# The JSON string to parse.
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
jQuery.post(url, data, success(data, textStatus, XMLHttpRequest), dataType) -> XMLHttpRequest (Shorthand Methods)
# A string containing the URL to which the request is sent.
$.post("test.php");
jQuery.proxy(function, context, context, name) -> Function (Event Handler Attachment)
# The function whose context will be changed.
var obj = {
name: "John",
test: function() {
alert( this.name );
$("#test").unbind("click", obj.test);
}
};
$("#test").click( jQuery.proxy( obj, "test" ) );
// This also works:
// $("#test").click( jQuery.proxy( obj.test, obj ) );
jQuery.pushStack(elements, elements, name, arguments) -> jQuery (Plugin Authoring)
# An array of elements to push onto the stack and make into a new jQuery object.
jQuery([])
.pushStack( document.getElementsByTagName("div") )
.remove()
.end();
jQuery.queue(element, queueName, newQueue, element, queueName, callback()) -> jQuery (Data)
# A DOM element where the array of queued functions is attached.
$(document.body).click(function () {
$("div").show("slow");
$("div").animate({left:'+=200'},2000);
jQuery.queue( $("div")[0], "fx", function () {
$(this).addClass("newcolor");
jQuery.dequeue( this );
});
$("div").animate({left:'-=200'},500);
jQuery.queue( $("div")[0], "fx", function () {
$(this).removeClass("newcolor");
jQuery.dequeue( this );
});
$("div").slideUp();
});
jQuery.queue(element, queueName) -> Array (Data)
# A DOM element to inspect for an attached queue.
$("#show").click(function () {
var n = jQuery.queue( $("div")[0], "fx" );
$("span").text("Queue length is: " + n.length);
});
function runIt() {
$("div").show("slow");
$("div").animate({left:'+=200'},2000);
$("div").slideToggle(1000);
$("div").slideToggle("fast");
$("div").animate({left:'-=200'},1500);
$("div").hide("slow");
$("div").show(1200);
$("div").slideUp("normal", runIt);
}
runIt();
jQuery.removeData(element, name) -> jQuery (Data)
# A DOM element from which to remove data.
var div = $("div")[0];
$("span:eq(0)").text("" + $("div").data("test1"));
jQuery.data(div, "test1", "VALUE-1");
jQuery.data(div, "test2", "VALUE-2");
$("span:eq(1)").text("" + jQuery.data(div, "test1"));
jQuery.removeData(div, "test1");
$("span:eq(2)").text("" + jQuery.data(div, "test1"));
$("span:eq(3)").text("" + jQuery.data(div, "test2"));
jQuery.support() -> Object (Properties of the Global jQuery Object)
# A collection of properties that represent the presence of different browser features or bugs.
$("p").html("This frame uses the W3C box model: <span>" +
jQuery.support.boxModel + "</span>");
jQuery.trim(str) -> String (Utilities)
# The string to trim.
$("button").click(function () {
var str = " lots of spaces before and after ";
alert("'" + str + "'");
str = jQuery.trim(str);
alert("'" + str + "' - no longer");
});
jQuery.unique(array) -> Array (Utilities)
# The Array of DOM elements.
var divs = $("div").get(); // unique() must take a native array
// add 3 elements of class dup too (they are divs)
divs = divs.concat($(".dup").get());
$("div:eq(1)").text("Pre-unique there are " + divs.length + " elements.");
divs = jQuery.unique(divs);
$("div:eq(2)").text("Post-unique there are " + divs.length + " elements.")
.css("color", "red");
keydown(handler(eventObject)) -> jQuery (Keyboard Events)
# A function to execute each time the event is triggered.
var xTriggered = 0;
$('#target').keydown(function(event) {
if (event.keyCode == '13') {
event.preventDefault();
}
xTriggered++;
var msg = 'Handler for .keydown() called ' + xTriggered + ' time(s).';
$.print(msg, 'html');
$.print(event);
});
$('#other').click(function() {
$('#target').keydown();
});
keypress(handler(eventObject)) -> jQuery (Keyboard Events)
# Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.
var xTriggered = 0;
$('#target').keypress(function(event) {
if (event.keyCode == '13') {
event.preventDefault();
}
xTriggered++;
var msg = 'Handler for .keypress() called ' + xTriggered + ' time(s).';
$.print(msg, 'html');
$.print(event);
});
$('#other').click(function() {
$('#target').keypress();
});
keyup(handler(eventObject)) -> jQuery (Keyboard Events)
# Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.
var xTriggered = 0;
$('#target').keyup(function(event) {
if (event.keyCode == '13') {
event.preventDefault();
}
xTriggered++;
var msg = 'Handler for .keyup() called ' + xTriggered + ' time(s).';
$.print(msg, 'html');
$.print(event);
});
$('#other').click(function() {
$('#target').keyup();
});
last() -> jQuery (Filtering)
# Reduce the set of matched elements to the final one in the set.
$("p span").last().addClass('highlight');
last() -> (Basic Filter)
# Selects the last matched element.
$("tr:last").css({backgroundColor: 'yellow', fontWeight: 'bolder'});
last-child() -> (Child Filter)
# Selects all elements that are the last child of their parent.
$("div span:last-child")
.css({color:"red", fontSize:"80%"})
.hover(function () {
$(this).addClass("solast");
}, function () {
$(this).removeClass("solast");
});
length() -> Number (Properties of jQuery Object Instances)
# The number of elements in the jQuery object.
$(document.body).click(function () {
$(document.body).append($("<div>"));
var n = $("div").length;
$("span").text("There are " + n + " divs." +
"Click to add more.");
}).trigger('click'); // trigger the click to start
live(eventType, handler, eventType, eventData, handler) -> jQuery (Event Handler Attachment)
# Attach a handler to the event for all elements which match the current selector, now or in the future.
$("p").live("click", function(){
$(this).after("<p>Another paragraph!</p>");
});
load(handler(eventObject)) -> jQuery (Document Loading)
# Bind an event handler to the "load" JavaScript event.
$(window).load(function () {
// run code
});
load(url, data, complete(responseText, textStatus, XMLHttpRequest)) -> jQuery (Shorthand Methods)
# A string containing the URL to which the request is sent.
$("#new-nav").load("/ #jq-footerNavigation li");
lt(index) -> (Basic Filter)
# Zero-based index.
$("td:lt(4)").css("color", "red");
map(callback(index, domElement)) -> jQuery (Filtering)
# A function object that will be invoked for each element in the current set.
$("p").append( $("input").map(function(){
return $(this).val();
}).get().join(", ") );
mousedown(handler(eventObject)) -> jQuery (Mouse Events)
# Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.
$("p").mouseup(function(){
$(this).append('<span style="color:#F00;">Mouse up.</span>');
}).mousedown(function(){
$(this).append('<span style="color:#00F;">Mouse down.</span>');
});
mouseenter(handler(eventObject)) -> jQuery (Mouse Events)
# Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.
var i = 0;
$("div.overout").mouseover(function(){
$("p:first",this).text("mouse over");
$("p:last",this).text(++i);
}).mouseout(function(){
$("p:first",this).text("mouse out");
});
var n = 0;
$("div.enterleave").mouseenter(function(){
$("p:first",this).text("mouse enter");
$("p:last",this).text(++n);
}).mouseleave(function(){
$("p:first",this).text("mouse leave");
});
mouseleave(handler(eventObject)) -> jQuery (Mouse Events)
# Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.
var i = 0;
$("div.overout").mouseover(function(){
$("p:first",this).text("mouse over");
}).mouseout(function(){
$("p:first",this).text("mouse out");
$("p:last",this).text(++i);
});
var n = 0;
$("div.enterleave").mouseenter(function(){
$("p:first",this).text("mouse enter");
}).mouseleave(function(){
$("p:first",this).text("mouse leave");
$("p:last",this).text(++n);
});
mousemove(handler(eventObject)) -> jQuery (Mouse Events)
# Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.
$("div").mousemove(function(e){
var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
$("span:first").text("( e.pageX, e.pageY ) - " + pageCoords);
$("span:last").text("( e.clientX, e.clientY ) - " + clientCoords);
});
mouseout(handler(eventObject)) -> jQuery (Mouse Events)
# Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.
var i = 0;
$("div.overout").mouseout(function(){
$("p:first",this).text("mouse out");
$("p:last",this).text(++i);
}).mouseover(function(){
$("p:first",this).text("mouse over");
});
var n = 0;
$("div.enterleave").bind("mouseenter",function(){
$("p:first",this).text("mouse enter");
}).bind("mouseleave",function(){
$("p:first",this).text("mouse leave");
$("p:last",this).text(++n);
});
mouseover(handler(eventObject)) -> jQuery (Mouse Events)
# Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.
var i = 0;
$("div.overout").mouseover(function() {
i += 1;
$(this).find("span").text( "mouse enter x " + i );
}).mouseout(function(){
$(this).find("span").text("mouse out ");
});
var n = 0;
$("div.enterleave").mouseenter(function() {
n += 1;
$(this).find("span").text( "mouse enter x " + n );
}).mouseleave(function() {
$(this).find("span").text("mouse leave");
});
mouseup(handler(eventObject)) -> jQuery (Mouse Events)
# Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.
$("p").mouseup(function(){
$(this).append('<span style="color:#F00;">Mouse up.</span>');
}).mousedown(function(){
$(this).append('<span style="color:#00F;">Mouse down.</span>');
});
multiple(selector1, selector2, selectorN) -> (Basic)
# Any valid selector.
$("div,span,p.myClass").css("border","3px solid red");
next(selector) -> jQuery (Tree Traversal)
# A string containing a selector expression to match elements against.
$("button[disabled]").next().text("this button is disabled");
next adjacent(prev, next) -> (Hierarchy)
# Any valid selector.
$("label + input").css("color", "blue").val("Labeled!")
next siblings(prev, siblings) -> (Hierarchy)
# Any valid selector.
$("#prev ~ div").css("border", "3px groove blue");
nextAll(selector) -> jQuery (Tree Traversal)
# A string containing a selector expression to match elements against.
$("div:first").nextAll().addClass("after");
nextUntil(selector) -> jQuery (Tree Traversal)
# A string containing a selector expression to indicate where to stop matching following sibling elements.
$("#term-2").nextUntil("dt")
.css("background-color", "red")
not(selector) -> (Basic Filter)
# A selector with which to filter by.
$("input:not(:checked) + span").css("background-color", "yellow");
$("input").attr("disabled", "disabled");
not(selector, elements, function(index)) -> jQuery (Filtering)
# A string containing a selector expression to match elements against.
$("div").not(".green, #blueone")
.css("border-color", "red");
nth-child(index) -> (Child Filter)
# The index of each child to match, starting with 1, the string even or odd, or an equation ( eg. :nth-child(even), :nth-child(4n) )
$("ul li:nth-child(2)").append("<span> - 2nd!</span>");
odd() -> (Basic Filter)
# Selects odd elements, zero-indexed. See also even.
$("tr:odd").css("background-color", "#bbbbff");
offset() -> Object (CSS)
# Get the current coordinates of the first element in the set of matched elements, relative to the document.
var p = $("p:last");
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );
offset(coordinates, function(index, coords)) -> jQuery (CSS)
# An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements.
$("p:last").offset({ top: 10, left: 30 });
offsetParent() -> jQuery (Tree Traversal)
# Get the closest ancestor element that is positioned.
$('li.item-a').offsetParent().css('background-color', 'red');
one(eventType, eventData, handler(eventObject)) -> jQuery (Event Handler Attachment)
# Attach a handler to an event for the elements. The handler is executed at most once per element.
var n = 0;
$("div").one("click", function(){
var index = $("div").index(this);
$(this).css({ borderStyle:"inset",
cursor:"auto" });
$("p").text("Div at index #" + index + " clicked." +
" That's " + ++n + " total clicks.");
});
only-child() -> (Child Filter)
# Selects all elements that are the only child of their parent.
$("div button:only-child").text("Alone").css("border", "2px blue solid");
outerHeight(includeMargin) -> Integer (CSS)
# A Boolean indicating whether to include the element's margin in the calculation.
var p = $("p:first");
$("p:last").text( "outerHeight:" + p.outerHeight() + " , outerHeight(true):" + p.outerHeight(true) );
outerWidth(includeMargin) -> Integer (CSS)
# A Boolean indicating whether to include the element's margin in the calculation.
var p = $("p:first");
$("p:last").text( "outerWidth:" + p.outerWidth()+ " , outerWidth(true):" + p.outerWidth(true) );
parent(selector) -> jQuery (Tree Traversal)
# A string containing a selector expression to match elements against.
$("*", document.body).each(function () {
var parentTag = $(this).parent().get(0).tagName;
$(this).prepend(document.createTextNode(parentTag + " > "));
});
parent() -> (Content Filter)
# Select all elements that are the parent of another element, including text nodes.
$("td:parent").fadeTo(1500, 0.3);
parents(selector) -> jQuery (Tree Traversal)
# A string containing a selector expression to match elements against.
var parentEls = $("b").parents()
.map(function () {
return this.tagName;
})
.get().join(", ");
$("b").append("<strong>" + parentEls + "</strong>");
parentsUntil(selector) -> jQuery (Tree Traversal)
# A string containing a selector expression to indicate where to stop matching ancestor elements.
$('li.item-a').parentsUntil('.level-1')
.css('background-color', 'red');
password() -> (Form)
# Selects all elements of type password.
var input = $("input:password").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
position() -> Object (CSS)
# Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
var p = $("p:first");
var position = p.position();
$("p:last").text( "left: " + position.left + ", top: " + position.top );
prepend(content, function(index, html)) -> jQuery (DOM Insertion, Inside)
# An element, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.
$("p").prepend("<b>Hello </b>");
prependTo(target) -> jQuery (DOM Insertion, Inside)
# A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter.
$("span").prependTo("#foo"); // check prepend() examples
prev(selector) -> jQuery (Tree Traversal)
# A string containing a selector expression to match elements against.
var $curr = $("#start");
$curr.css("background", "#f99");
$("button").click(function () {
$curr = $curr.prev();
$("div").css("background", "");
$curr.css("background", "#f99");
});
prevAll(selector) -> jQuery (Tree Traversal)
# A string containing a selector expression to match elements against.
$("div:last").prevAll().addClass("before");
prevUntil(selector) -> jQuery (Tree Traversal)
# A string containing a selector expression to indicate where to stop matching preceding sibling elements.
$("#term-2").prevUntil("dt")
.css("background-color", "red")
queue(queueName) -> Array (Custom)
# A string containing the name of the queue. Defaults to fx, the standard effects queue.
$("#show").click(function () {
var n = $("div").queue("fx");
$("span").text("Queue length is: " + n.length);
});
function runIt() {
$("div").show("slow");
$("div").animate({left:'+=200'},2000);
$("div").slideToggle(1000);
$("div").slideToggle("fast");
$("div").animate({left:'-=200'},1500);
$("div").hide("slow");
$("div").show(1200);
$("div").slideUp("normal", runIt);
}
runIt();
queue(queueName, newQueue, queueName, callback( next )) -> jQuery (Custom)
# A string containing the name of the queue. Defaults to fx, the standard effects queue.
$(document.body).click(function () {
$("div").show("slow");
$("div").animate({left:'+=200'},2000);
$("div").queue(function () {
$(this).addClass("newcolor");
$(this).dequeue();
});
$("div").animate({left:'-=200'},500);
$("div").queue(function () {
$(this).removeClass("newcolor");
$(this).dequeue();
});
$("div").slideUp();
});
radio() -> (Form)
# Selects all elements of type radio.
var input = $("form input:radio").wrap('<span></span>').parent().css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
ready(handler) -> jQuery (Document Loading)
# Specify a function to execute when the DOM is fully loaded.
$(document).ready(function () {
$("p").text("The DOM is now loaded and can be manipulated.");
});
remove(selector) -> jQuery (DOM Removal)
# A selector expression that filters the set of matched elements to be removed.
$("button").click(function () {
$("p").remove();
});
removeAttr(attributeName) -> jQuery (Attributes)
# An attribute to remove.
$("button").click(function () {
$(this).next().removeAttr("disabled")
.focus()
.val("editable now");
});
removeClass(className, function(index, class)) -> jQuery (Attributes)
# A class name to be removed from the class attribute of each matched element.
$("p:even").removeClass("blue");
removeData(name) -> jQuery (Data)
# A string naming the piece of data to delete.
$("span:eq(0)").text("" + $("div").data("test1"));
$("div").data("test1", "VALUE-1");
$("div").data("test2", "VALUE-2");
$("span:eq(1)").text("" + $("div").data("test1"));
$("div").removeData("test1");
$("span:eq(2)").text("" + $("div").data("test1"));
$("span:eq(3)").text("" + $("div").data("test2"));
replaceAll(target) -> jQuery (DOM Replacement)
# A selector expression indicating which element(s) to replace.
$("<b>Paragraph. </b>").replaceAll("p"); // check replaceWith() examples
replaceWith(newContent, function) -> jQuery (DOM Replacement)
# The content to insert. May be an HTML string, DOM element, or jQuery object.
$("button").click(function () {
$(this).replaceWith("<div>" + $(this).text() + "</div>");
});
reset() -> (Form)
# Selects all elements of type reset.
var input = $("input:reset").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
resize(handler(eventObject)) -> jQuery (Browser Events)
# Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.
$(window).resize(function() {
$('body').prepend('<div>' + $(window).width() + '</div>');
});
scroll(handler(eventObject)) -> jQuery (Browser Events)
# Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.
$("p").clone().appendTo(document.body);
$("p").clone().appendTo(document.body);
$("p").clone().appendTo(document.body);
$(window).scroll(function () {
$("span").css("display", "inline").fadeOut("slow");
});
scrollLeft() -> Integer (CSS)
# Get the current horizontal position of the scroll bar for the first element in the set of matched elements.
var p = $("p:first");
$("p:last").text( "scrollLeft:" + p.scrollLeft() );
scrollLeft(value) -> jQuery (CSS)
# An integer indicating the new position to set the scroll bar to.
$("div.demo").scrollLeft(300);
scrollTop() -> Integer (CSS)
# Get the current vertical position of the scroll bar for the first element in the set of matched elements.
var p = $("p:first");
$("p:last").text( "scrollTop:" + p.scrollTop() );
scrollTop(value) -> jQuery (CSS)
# An integer indicating the new position to set the scroll bar to.
$("div.demo").scrollTop(300);
select(handler(eventObject)) -> jQuery (Form Events)
# Bind an event handler to the "select" JavaScript event, or trigger that event on an element.
$(":input").select( function () {
$("div").text("Something was selected").show().fadeOut(1000);
});
selected() -> (Form)
# Selects all elements that are selected.
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.trigger('change');
selector() -> String (Plugin Authoring)
# A selector representing selector originally passed to jQuery().
$("ul")
.append("<li>" + $("ul").selector + "</li>")
.append("<li>" + $("ul li").selector + "</li>")
.append("<li>" + $("div#foo ul:not([class])").selector + "</li>");
serialize() -> String (Forms)
# Encode a set of form elements as a string for submission.
function showValues() {
var str = $("form").serialize();
$("#results").text(str);
}
$(":checkbox, :radio").click(showValues);
$("select").change(showValues);
showValues();
serializeArray() -> Array (Forms)
# Encode a set of form elements as an array of names and values.
function showValues() {
var fields = $(":input").serializeArray();
$("#results").empty();
jQuery.each(fields, function(i, field){
$("#results").append(field.value + " ");
});
}
$(":checkbox, :radio").click(showValues);
$("select").change(showValues);
showValues();
show(duration, callback) -> jQuery (Basics)
# Display the matched elements.
$("button").click(function () {
$("p").show("slow");
});
siblings(selector) -> jQuery (Tree Traversal)
# A string containing a selector expression to match elements against.
var len = $(".hilite").siblings()
.css("color", "red")
.length;
$("b").text(len);
size() -> Number (DOM Element Methods)
# Return the number of DOM elements matched by the jQuery object.
$(document.body).click(function () { $(document.body).append($("<div>"));
var n = $("div").size();
$("span").text("There are " + n + " divs." + "Click to add more.");}).click(); // trigger the click to start
slice(start, end) -> jQuery (Filtering)
# An integer indicating the 0-based position after which the elements are selected. If negative, it indicates an offset from the end of the set.
function colorEm() {
var $div = $("div");
var start = Math.floor(Math.random() *
$div.length);
var end = Math.floor(Math.random() *
($div.length - start)) +
start + 1;
if (end == $div.length) end = undefined;
$div.css("background", "");
if (end)
$div.slice(start, end).css("background", "yellow");
else
$div.slice(start).css("background", "yellow");
$("span").text('$("div").slice(' + start +
(end ? ', ' + end : '') +
').css("background", "yellow");');
}
$("button").click(colorEm);
slideDown(duration, callback) -> jQuery (Sliding)
# Display the matched elements with a sliding motion.
$(document.body).click(function () {
if ($("div:first").is(":hidden")) {
$("div").slideDown("slow");
} else {
$("div").hide();
}
});
slideToggle(duration, callback) -> jQuery (Sliding)
# Display or hide the matched elements with a sliding motion.
$("button").click(function () {
$("p").slideToggle("slow");
});
slideUp(duration, callback) -> jQuery (Sliding)
# Hide the matched elements with a sliding motion.
$(document.body).click(function () {
if ($("div:first").is(":hidden")) {
$("div").show("slow");
} else {
$("div").slideUp();
}
});
stop(clearQueue, jumpToEnd) -> jQuery (Custom)
# Stop the currently-running animation on the matched elements.
// Start animation
$("#go").click(function(){
$(".block").animate({left: '+=100px'}, 2000);
});
// Stop animation when button is clicked
$("#stop").click(function(){
$(".block").stop();
});
// Start animation in the opposite direction
$("#back").click(function(){
$(".block").animate({left: '-=100px'}, 2000);
});
submit(handler(eventObject)) -> jQuery (Form Events)
# Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.
$("form").submit(function() {
if ($("input:first").val() == "correct") {
$("span").text("Validated...").show();
return true;
}
$("span").text("Not valid!").show().fadeOut(1000);
return false;
});
submit() -> (Form)
# Selects all elements of type submit.
var submitEl = $("td :submit")
.parent('td')
.css({background:"yellow", border:"3px red solid"})
.end();
$('#result').text('jQuery matched ' + submitEl.length + ' elements.');
// so it won't submit
$("form").submit(function () { return false; });
// Extra JS to make the HTML easier to edit (None of this is relevant to the ':submit' selector
$('#exampleTable').find('td').each(function(i, el) {
var inputEl = $(el).children(),
inputType = inputEl.attr('type') ? ' type="' + inputEl.attr('type') + '"' : '';
$(el).before('<td>' + inputEl[0].nodeName + inputType + '</td>');
})
text() -> String (DOM Insertion, Inside)
# Get the combined text contents of each element in the set of matched elements, including their descendants.
var str = $("p:first").text();
$("p:last").html(str);
text() -> (Form)
# Selects all elements of type text.
var input = $("form input:text").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
text(textString, function(index, text)) -> jQuery (DOM Insertion, Inside)
# A string of text to set as the content of each matched element.
$("p").text("<b>Some</b> new text.");
toArray() -> Array (DOM Element Methods)
# Retrieve all the DOM elements contained in the jQuery set, as an array.
function disp(divs) {
var a = [];
for (var i = 0; i < divs.length; i++) {
a.push(divs[i].innerHTML);
}
$("span").text(a.join(" "));
}
disp( $("div").toArray().reverse() );
toggle(handler(eventObject), handler(eventObject), handler(eventObject)) -> jQuery (Basics)
# Bind two or more handlers to the matched elements, to be executed on alternate clicks.
$("li").toggle(
function () {
$(this).css({"list-style-type":"disc", "color":"blue"});
},
function () {
$(this).css({"list-style-type":"disc", "color":"red"});
},
function () {
$(this).css({"list-style-type":"", "color":""});
}
);
toggle(duration, callback, showOrHide) -> jQuery (Basics)
# Display or hide the matched elements.
$("button").click(function () {
$("p").toggle();
});
toggleClass(className, className, switch, function(index, class), switch) -> jQuery (Attributes)
# One or more class names (separated by spaces) to be toggled for each element in the matched set.
$("p").click(function () {
$(this).toggleClass("highlight");
});
trigger(eventType, extraParameters) -> jQuery (Event Handler Attachment)
# Execute all handlers and behaviors attached to the matched elements for the given event type.
$("button:first").click(function () {
update($("span:first"));
});
$("button:last").click(function () {
$("button:first").trigger('click');
update($("span:last"));
});
function update(j) {
var n = parseInt(j.text(), 10);
j.text(n + 1);
}
triggerHandler(eventType, extraParameters) -> Object (Event Handler Attachment)
# Execute all handlers attached to an element for an event.
$("#old").click(function(){
$("input").trigger("focus");
});
$("#new").click(function(){
$("input").triggerHandler("focus");
});
$("input").focus(function(){
$("<span>Focused!</span>").appendTo("body").fadeOut(1000);
});
unbind(eventType, handler(eventObject), event) -> jQuery (Event Handler Attachment)
# Remove a previously-attached event handler from the elements.
function aClick() {
$("div").show().fadeOut("slow");
}
$("#bind").click(function () {
// could use .bind('click', aClick) instead but for variety...
$("#theone").click(aClick)
.text("Can Click!");
});
$("#unbind").click(function () {
$("#theone").unbind('click', aClick)
.text("Does nothing...");
});
undelegate(selector, eventType, selector, eventType, handler) -> jQuery (Event Handler Attachment)
# Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.
function aClick() {
$("div").show().fadeOut("slow");
}
$("#bind").click(function () {
$("body").delegate("#theone", "click", aClick)
.find("#theone").text("Can Click!");
});
$("#unbind").click(function () {
$("body").undelegate("#theone", "click", aClick)
.find("#theone").text("Does nothing...");
});
unload(handler(eventObject)) -> jQuery (Document Loading)
# A function to execute when the event is triggered.
$(window).unload( function () { alert("Bye now!"); } );
unwrap() -> jQuery (DOM Insertion, Around)
# Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
$("button").toggle(function(){
$("p").wrap("<div></div>");
}, function(){
$("p").unwrap();
});
val() -> String, Array (Attributes)
# Get the current value of the first element in the set of matched elements.
function displayVals() {
var singleValues = $("#single").val();
var multipleValues = $("#multiple").val() || [];
$("p").html("<b>Single:</b> " +
singleValues +
" <b>Multiple:</b> " +
multipleValues.join(", "));
}
$("select").change(displayVals);
displayVals();
val(value, function(index, value)) -> jQuery (Attributes)
# A string of text or an array of strings to set as the value property of each matched element.
$("button").click(function () {
var text = $(this).text();
$("input").val(text);
});
visible() -> (Version 1.0)
# Selects all elements that are visible.
$("div:visible").click(function () {
$(this).css("background", "yellow");
});
$("button").click(function () {
$("div:hidden").show("fast");
});
width(value, function(index, width)) -> jQuery (CSS)
# An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).
$("div").one('click', function () {
$(this).width(30)
.css({cursor:"auto", "background-color":"blue"});
});
width() -> Integer (CSS)
# Get the current computed width for the first element in the set of matched elements.
function showWidth(ele, w) {
$("div").text("The width for the " + ele +
" is " + w + "px.");
}
$("#getp").click(function () {
showWidth("paragraph", $("p").width());
});
$("#getd").click(function () {
showWidth("document", $(document).width());
});
$("#getw").click(function () {
showWidth("window", $(window).width());
});
wrap(wrappingElement, wrappingFunction) -> jQuery (DOM Insertion, Around)
# An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.
$("p").wrap("<div></div>");
wrapAll(wrappingElement) -> jQuery (DOM Insertion, Around)
# An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.
$("p").wrapAll("<div></div>");
wrapInner(wrappingElement, wrappingFunction) -> jQuery (DOM Insertion, Around)
# An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements.
$("p").wrapInner("<b></b>");