Welcome to TiddlyWiki created by Jeremy Ruston, Copyright © 2007 UnaMesa Association
<<jQueryDocsImport>>
[[Navigation]]
<<tagsplorer "jQuery API">>
/***
|''Name''|SimpleSearchPlugin|
|''Description''|displays search results as a simple list of matching tiddlers|
|''Authors''|FND|
|''Version''|0.4.1|
|''Status''|stable|
|''Source''|http://devpad.tiddlyspot.com/#SimpleSearchPlugin|
|''CodeRepository''|http://svn.tiddlywiki.org/Trunk/contributors/FND/plugins/SimpleSearchPlugin.js|
|''License''|[[Creative Commons Attribution-ShareAlike 3.0 License|http://creativecommons.org/licenses/by-sa/3.0/]]|
|''Keywords''|search|
!Revision History
!!v0.2.0 (2008-08-18)
* initial release
!!v0.3.0 (2008-08-19)
* added Open All button (renders Classic Search option obsolete)
* sorting by relevance (title matches before content matches)
!!v0.4.0 (2008-08-26)
* added tag matching
!To Do
* tag matching optional
* animations for container creation and removal
* when clicking on search results, do not scroll to the respective tiddler (optional)
* use template for search results
!Code
***/
//{{{
if(!version.extensions.SimpleSearchPlugin) { //# ensure that the plugin is only installed once
version.extensions.SimpleSearchPlugin = { installed: true };
if(!config.extensions) { config.extensions = {}; }
config.extensions.SimpleSearchPlugin = {
heading: "Search Results",
containerId: "searchResults",
btnCloseLabel: "close",
btnCloseTooltip: "dismiss search results",
btnCloseId: "search_close",
btnOpenLabel: "Open all",
btnOpenTooltip: "open all search results",
btnOpenId: "search_open",
displayResults: function(matches, query) {
story.refreshAllTiddlers(true); // update highlighting within story tiddlers
var el = document.getElementById(this.containerId);
query = '"""' + query + '"""'; // prevent WikiLinks
if(el) {
removeChildren(el);
} else { //# fallback: use displayArea as parent
var container = document.getElementById("displayArea");
el = document.createElement("div");
el.id = this.containerId;
el = container.insertBefore(el, container.firstChild);
}
var msg = "!" + this.heading + "\n";
if(matches.length > 0) {
msg += "''" + config.macros.search.successMsg.format([matches.length.toString(), query]) + ":''\n";
this.results = [];
for(var i = 0 ; i < matches.length; i++) {
this.results.push(matches[i].title);
msg += "* [[" + matches[i].title + "]]\n";
}
} else {
msg += "''" + config.macros.search.failureMsg.format([query]) + "''"; // XXX: do not use bold here!?
}
createTiddlyButton(el, this.btnCloseLabel, this.btnCloseTooltip, config.extensions.SimpleSearchPlugin.closeResults, "button", this.btnCloseId);
wikify(msg, el);
if(matches.length > 0) { // XXX: redundant!?
createTiddlyButton(el, this.btnOpenLabel, this.btnOpenTooltip, config.extensions.SimpleSearchPlugin.openAll, "button", this.btnOpenId);
}
},
closeResults: function() {
var el = document.getElementById(config.extensions.SimpleSearchPlugin.containerId);
removeNode(el);
config.extensions.SimpleSearchPlugin.results = null;
highlightHack = null;
},
openAll: function(ev) {
story.displayTiddlers(null, config.extensions.SimpleSearchPlugin.results);
return false;
}
};
config.shadowTiddlers.StyleSheetSimpleSearch = "/*{{{*/\n" +
"#" + config.extensions.SimpleSearchPlugin.containerId + " {\n" +
"\toverflow: auto;\n" +
"\tpadding: 5px 1em 10px;\n" +
"\tbackground-color: [[ColorPalette::TertiaryPale]];\n" +
"}\n\n" +
"#" + config.extensions.SimpleSearchPlugin.containerId + " h1 {\n" +
"\tmargin-top: 0;\n" +
"\tborder: none;\n" +
"}\n\n" +
"#" + config.extensions.SimpleSearchPlugin.containerId + " ul {\n" +
"\tmargin: 0.5em;\n" +
"\tpadding-left: 1.5em;\n" +
"}\n\n" +
"#" + config.extensions.SimpleSearchPlugin.containerId + " .button {\n" +
"\tdisplay: block;\n" +
"\tborder-color: [[ColorPalette::TertiaryDark]];\n" +
"\tpadding: 5px;\n" +
"\tbackground-color: [[ColorPalette::TertiaryLight]];\n" +
"}\n\n" +
"#" + config.extensions.SimpleSearchPlugin.containerId + " .button:hover {\n" +
"\tborder-color: [[ColorPalette::SecondaryMid]];\n" +
"\tbackground-color: [[ColorPalette::SecondaryLight]];\n" +
"}\n\n" +
"#" + config.extensions.SimpleSearchPlugin.btnCloseId + " {\n" +
"\tfloat: right;\n" +
"\tmargin: -5px -1em 5px 5px;\n" +
"}\n\n" +
"#" + config.extensions.SimpleSearchPlugin.btnOpenId + " {\n" +
"\tfloat: left;\n" +
"\tmargin-top: 5px;\n" +
"}\n" +
"/*}}}*/";
store.addNotification("StyleSheetSimpleSearch", refreshStyles);
// override Story.search()
Story.prototype.search = function(text, useCaseSensitive, useRegExp) {
highlightHack = new RegExp(useRegExp ? text : text.escapeRegExp(), useCaseSensitive ? "mg" : "img");
var matches = store.search(highlightHack, null, "excludeSearch");
var q = useRegExp ? "/" : "'";
config.extensions.SimpleSearchPlugin.displayResults(matches, q + text + q);
};
// override TiddlyWiki.search() to sort by relevance
TiddlyWiki.prototype.search = function(searchRegExp, sortField, excludeTag, match) {
var candidates = this.reverseLookup("tags", excludeTag, !!match);
var primary = [];
var secondary = [];
var tertiary = [];
for(var t = 0; t < candidates.length; t++) {
if(candidates[t].title.search(searchRegExp) != -1) {
primary.push(candidates[t]);
} else if(candidates[t].tags.join(" ").search(searchRegExp) != -1) {
secondary.push(candidates[t]);
} else if(candidates[t].text.search(searchRegExp) != -1) {
tertiary.push(candidates[t]);
}
}
var results = primary.concat(secondary).concat(tertiary);
if(sortField) {
results.sort(function(a, b) {
return a[sortField] < b[sortField] ? -1 : (a[sortField] == b[sortField] ? 0 : +1);
});
}
return results;
};
} //# end of "install only once"
//}}}
/*{{{*/
#mainMenu ul {
overflow: hidden;
margin: 0;
padding: 0;
font-size: 0.9em;
line-height: 1.2em;
text-align: left;
list-style-type: none;
}
#mainMenu ul .listTitle {
display: none;
}
/*}}}*/
/***
|''Name''|TagsplorerMacro|
|''Description''|tag-based faceted tiddler navigation|
|''Author''|FND|
|''Version''|1.3.3|
|''Status''|stable|
|''Source''|http://svn.tiddlywiki.org/Trunk/contributors/FND/plugins/TagsplorerMacro.js|
|''CodeRepository''|http://svn.tiddlywiki.org/Trunk/contributors/FND/|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
|''CoreVersion''|2.6.0|
|''Keywords''|navigation tagging|
!Usage
{{{
<<tagsplorer [exclude:<tagName>] [tag] [tag] ... >>
}}}
!!Examples
<<tagsplorer exclude:excludeLists systemConfig>>
!Revision History
!!v1.0 (2010-03-21)
* initial release
!!v1.1 (2010-03-26)
* added sorting for tag and tiddler collections
* added section headings
* adjusted styling
!!v1.2 (2010-03-27)
* added exclude parameter for excludeLists support
!!v1.3 (2010-03-29)
* added automatic scrolling after tag selection
!To Do
* refresh handling
* "open all" functionality
* animations for new/removed tags/tiddlers (requires array diff'ing)
!StyleSheet
.tagsplorer {
border: 1px solid [[ColorPalette::TertiaryLight]];
padding: 5px;
background-color: [[ColorPalette::TertiaryPale]];
}
.tagsplorer h3,
.tagsplorer ul {
margin: 0;
padding: 0;
}
.tagsplorer h3 {
margin: 0 -5px;
padding: 0 5px;
border: none;
}
.tagsplorer h3.tags {
float: left;
margin-right: 1em;
}
.tagsplorer h3.tiddlers {
margin-top: 5px;
border-top: 1px solid [[ColorPalette::TertiaryLight]];
padding-top: 5px;
}
.tagsplorer .tagSelection {
overflow: auto;
list-style-type: none;
}
.tagsplorer .tagSelection li {
float: left;
}
.tagsplorer .tagSelection li a.tag {
border: 1px solid [[ColorPalette::TertiaryLight]];
border-top-right-radius: 0.7em;
-webkit-border-top-right-radius: 0.7em;
-moz-border-radius-topright: 0.7em;
border-bottom-right-radius: 0.7em;
-webkit-border-bottom-right-radius: 0.7em;
-moz-border-radius-bottomright: 0.7em;
padding: 0 0.5em 0 0.3em;
}
.tagsplorer .tiddlerList {
margin-left: 1.5em;
}
!Code
***/
//{{{
(function($) {
config.shadowTiddlers.StyleSheetTagsplorer = store.getTiddlerText(tiddler.title + "##StyleSheet");
store.addNotification("StyleSheetTagsplorer", refreshStyles);
var macro = config.macros.tagsplorer = {};
config.macros.tagsplorer = $.extend(macro, {
locale: {
tagsLabel: "Tags",
tiddlersLabel: "Tiddlers",
newTagLabel: "[+]",
newTagTooltip: "add tag to filter",
delTagTooltip: "remove tag from filter",
noTagsLabel: "N/A",
noTiddlersLabel: "N/A"
},
handler: function(place, macroName, params, wikifier, paramString, tiddler) {
var prms = paramString.parseParams("anon", null, true);
var excludeTag = getParam(prms, "exclude", null);
var tags = prms[0].anon || [];
var tiddlers = getTiddlers(tags, excludeTag);
var container = $('<div class="tagsplorer" />').
append('<h3 class="tags" />').children(":last").
text(this.locale.tagsLabel).end().
append('<ul class="tagSelection" />').
append('<h3 class="tiddlers" />').children(":last").
text(this.locale.tiddlersLabel).end().
append('<ul class="tiddlerList" />').
data("excludeTag", excludeTag);
macro.refreshTags(tags, container);
macro.refreshTiddlers(tiddlers, container);
container.appendTo(place);
},
newTagClick: function(ev) {
var btn = $(this);
var container = btn.closest(".tagsplorer");
var tags = container.find(".tagSelection").data("tags");
var tiddlers = container.find(".tiddlerList").data("tiddlers");
var tagSelection = getTagSelection(tiddlers, tags);
var popup = Popup.create(this, "ul");
if(tagSelection.length) {
$.each(tagSelection, function(i, tag) {
createTagElement(popup, tag, macro.locale.newTagTooltip, macro.onTagClick);
});
} else {
createTagElement(popup, macro.locale.noTagsLabel);
}
$(popup).data({
container: container,
tags: tags,
tiddlers: tiddlers
});
Popup.show();
ev.stopPropagation();
return false;
},
onTagClick: function(ev) {
var btn = $(this);
var popup = btn.closest(".popup");
var data = popup.data();
var tag = btn.text();
data.tags.pushUnique(tag);
data.tiddlers = filterTiddlers(data.tiddlers, tag);
if(config.options.chkAnimate && anim && typeof Scroller == "function") {
anim.startAnimating(new Scroller(data.container[0]));
} else {
window.scrollTo(0, ensureVisible(data.container[0]));
}
macro.refreshTags(data.tags, data.container);
macro.refreshTiddlers(data.tiddlers, data.container);
return !ev.ctrlKey;
},
delTag: function(ev) {
var btn = $(this);
var container = btn.closest(".tagsplorer");
var tags = container.find(".tagSelection").data("tags");
tags.remove(btn.text());
var tiddlers = getTiddlers(tags, container.data("excludeTag"));
btn.parent().remove();
macro.refreshTags(tags, container);
macro.refreshTiddlers(tiddlers, container);
return false;
},
refreshTags: function(tags, container) {
var orig = container.find(".tagSelection");
var clone = orig.clone().empty();
clone.data("tags", tags);
var self = this;
$.each(tags, function(i, tag) {
createTagElement(clone, tag, self.locale.delTagTooltip, self.delTag, "tag");
});
createTagElement(clone, this.locale.newTagLabel, this.locale.newTagTooltip, this.newTagClick).
addClass("button");
orig.replaceWith(clone);
},
refreshTiddlers: function(tiddlers, container) {
var orig = container.find(".tiddlerList");
var clone = orig.clone().empty();
clone.data("tiddlers", tiddlers);
if(tiddlers.length) {
$.each(tiddlers, function(i, tiddler) {
var el = $("<li />").appendTo(clone)[0];
createTiddlyLink(el, tiddler.title, true);
});
} else {
$("<li />").text(macro.locale.noTiddlersLabel).appendTo(clone);
}
orig.replaceWith(clone);
}
});
var getTiddlers = function(tags, excludeTag) {
var tiddlers = store.getTiddlers("title", excludeTag);
for(var i = 0; i < tags.length; i++) {
tiddlers = filterTiddlers(tiddlers, tags[i]);
}
return tiddlers;
};
var filterTiddlers = function(tiddlers, tag) {
return $.map(tiddlers, function(item, i) {
if(item.tags.contains(tag)) {
return item;
}
});
};
var getTagSelection = function(tiddlers, exclude) {
var tags = [];
for(var i = 0; i < tiddlers.length; i++) {
var _tags = tiddlers[i].tags;
for(var j = 0; j < _tags.length; j++) {
var tag = _tags[j];
if(!exclude.contains(tag)) {
tags.pushUnique(tag);
}
}
}
return tags.sort();
};
var createTagElement = function(container, label, tooltip, action, className) {
var el = $("<li />").appendTo(container);
return $('<a href="javascript:;" />').
addClass(className || "").
attr("title", tooltip || "").
text(label).
click(action || null).
appendTo(el);
};
})(jQuery);
//}}}
<!--{{{-->
<div class='toolbar' macro='toolbar [[ToolbarCommands::ViewToolbar]]'></div>
<div class='title' macro='view title'></div>
<div class='subtitle'><span macro='view modifier link'></span>, <span macro='view modified date'></span> (<span macro='message views.wikified.createdPrompt'></span> <span macro='view created date'></span>)</div>
<div class='tagging' macro='tagging'></div>
<div class='tagged' macro='tags'></div>
<div macro='webLinker systemConfig'></div>
<div class='viewer' macro='view text wikified'></div>
<div class='tagClear'></div>
<!--}}}-->
/***
|''Name''|WebLinkerMacro|
|''Description''|links tiddler title to web wisdom|
|''Author''|FND|
|''Version''|0.1.0|
|''Status''|@@experimental@@|
|''Source''|http://hoster.peermore.com/recipes/movies/tiddlers.wiki#WebLinkerMacro|
|''CodeRepository''|http://svn.tiddlywiki.org/Trunk/contributors/FND/|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
!Usage
{{{
<<webLinker [tag]>>
}}}
//tag// parameter controls activation
!!Examples
<<webLinker systemConfig>>
!Code
***/
//{{{
(function() {
config.macros.webLinker = {
handler: function(place, macroName, params, wikifier, paramString, tiddler) {
if(params.length && !tiddler.tags.contains(params[0])) {
for(var key in this.sources) {
var url = this.sources[key].format([tiddler.title]);
wikify("[[%0|%1]]\n".format([key, url]), place);
}
}
},
sources: {
IMDb: "http://www.imdb.com/find?s=all&q=%0",
Wikipedia: "http://en.wikipedia.org/wiki/Special:Search?search=%0"
}
};
})();
//}}}
//{{{
config.macros.webLinker.sources = {
"jQuery API": "http://api.jquery.com/%0/",
};
//}}}
Add elements to the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|no|A string containing a selector expression to match additional elements against.|
|elements|Elements|no|one or more elements to add to the set of matched elements.|
|html|HTML|no|An HTML fragment to add to the set of matched elements.|
|selector|Selector|no|A string containing a selector expression to match additional elements against.|
|context|Element|no|Add some elements rooted against the specified context.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.add()</code> method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to <code>.add()</code> can be pretty much anything that <code>$()</code> accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.</p>
<p>Consider a page with a simple list and a paragraph following it:</p>
<pre><ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
</ul>
<p>a paragraph</p></pre>
<p>We can select the list items and then the paragraph by using either a selector or a reference to the DOM element itself as the <code>.add()</code> method's argument:</p>
<pre>$('li').add('p').css('background-color', 'red');</pre>
<p>Or:</p>
<pre>$('li').add(document.getElementsByTagName('p')[0])
.css('background-color', 'red');</pre>
<p>The result of this call is a red background behind all four elements.
Using an HTML snippet as the <code>.add()</code> method's argument (as in the third version), we can create additional elements on the fly and add those elements to the matched set of elements. Let's say, for example, that we want to alter the background of the list items along with a newly created paragraph:</p>
<pre>$('li').add('<p id="new">new paragraph</p>')
.css('background-color', 'red');</pre>
<p>Although the new paragraph has been created and its background color changed, it still does not appear on the page. To place it on the page, we could add one of the insertion methods to the chain.</p>
<p>As of jQuery 1.4 the results from .add() will always be returned in document order (rather than a simple concatenation).</p>
</html>
!Examples
* {{multiLine{Finds all divs and makes a border. Then adds all paragraphs to the jQuery object to set their backgrounds yellow.
{{{
$("div").css("border", "2px solid red")
.add("p")
.css("background", "yellow");
}}}
}}}
* {{multiLine{Adds more elements, matched by the given expression, to the set of matched elements.
{{{
$("p").add("span").css("background", "yellow");
}}}
}}}
* {{multiLine{Adds more elements, created on the fly, to the set of matched elements.
{{{
$("p").clone().add("<span>Again</span>").appendTo(document.body);
}}}
}}}
* {{multiLine{Adds one or more Elements to the set of matched elements.
{{{
$("p").add(document.getElementById("a")).css("background", "yellow");
}}}
}}}
* {{multiLine{Demonstrates how to add (or push) elements to an existing collection
{{{
var collection = $("p");
// capture the new collection
collection = collection.add(document.getElementById("a"));
collection.css("background", "yellow");
}}}
}}}
Adds the specified class(es) to each of the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|className|String|no|One or more class names to be added to the class attribute of each matched element.|
|function(index, class)|Function|no|A function returning one or more space-separated class names to be added. Receives the index position of the element in the set and the old class value as arguments.|
|Arguments|c
!Description
<html><p>It's important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements.</p>
<p>More than one class may be added at a time, separated by a space, to the set of matched elements, like so:</p>
<pre>$('p').addClass('myClass yourClass');</pre>
<p>This method is often used with <code>.removeClass()</code> to switch elements' classes from one to another, like so:</p>
<pre>$('p').removeClass('myClass noClass').addClass('yourClass');</pre>
<p>Here, the <code>myClass</code> and <code>noClass</code> classes are removed from all paragraphs, while <code>yourClass</code> is added.</p>
<p>As of jQuery 1.4, the <code>.addClass()</code> method allows us to set the class name by passing in a function.</p>
<pre>$('ul li:last').addClass(function() {
return 'item-' + $(this).index();
});</pre>
<p>Given an unordered list with five <code><li></code> elements, this example adds the class "item-4" to the last <code><li></code>.</p>
</html>
!Examples
* {{multiLine{Adds the class 'selected' to the matched elements.
{{{
$("p:last").addClass("selected");
}}}
}}}
* {{multiLine{Adds the classes 'selected' and 'highlight' to the matched elements.
{{{
$("p:last").addClass("selected highlight");
}}}
}}}
Insert content, specified by the parameter, after each element in the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|content|String, Element, jQuery|no|An element, HTML string, or jQuery object to insert after each element in the set of matched elements.|
|function(index)|Function|no|A function that returns an HTML string to insert after each element in the set of matched elements.|
|Arguments|c
!Description
<html><p>The <code>.after()</code> and <code><a href="/insertAfter">.insertAfter()</a></code> methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With<code> .after()</code>, the selector expression preceding the method is the container after which the content is inserted. With <code>.insertAfter()</code>, on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.</p>
<p>Consider the following HTML:</p>
<pre><div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>We can create content and insert it after several elements at once:</p>
<pre>$('.inner').after('<p>Test</p>');</pre>
<p>Each inner <code><div></code> element gets this new content:</p>
<pre><div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">Goodbye</div>
<p>Test</p>
</div></pre>
<p>We can also select an element on the page and insert it after another:</p>
<pre>$('.container').after($('h2'));</pre>
<p>If an element selected this way is inserted elsewhere, it will be moved after the target (not cloned):</p>
<pre><div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<h2>Greetings</h2></pre>
<p>If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.</p>
<h4 id="disconnected-dom-nodes">Inserting Disconnected DOM nodes</h4>
<p>As of jQuery 1.4, <code>.before()</code> and <code>.after()</code> will also work on disconnected DOM nodes. For example, given the following code:</p>
<pre>$('<div/>').after('<p></p>');</pre>
<p>The result is a jQuery set containing a div and a paragraph, in that order. We can further manipulate that set, even before inserting it in the document.</p>
<pre>$('<div/>').after('<p></p>').addClass('foo')
.filter('p').attr('id', 'bar').html('hello')
.end()
.appendTo('body');</pre>
<p>This results in the following elements inserted just before the closing <code></body></code> tag:</p>
<pre>
<div class="foo"></div>
<p class="foo" id="bar">hello</p>
</pre>
<p>As of jQuery 1.4, <code>.after()</code> allows us to pass a function that returns the elements to insert.</p>
<pre>$('p').after(function() {
return '<div>' + this.className + '</div>';
});</pre>
<p>This inserts a <code><div></code> after each paragraph, containing the class name(s) of each paragraph in turn.</p>
</html>
!Examples
* {{multiLine{Inserts some HTML after all paragraphs.
{{{
$("p").after("<b>Hello</b>");
}}}
}}}
* {{multiLine{Inserts a DOM element after all paragraphs.
{{{
$("p").after( document.createTextNode("Hello") );
}}}
}}}
* {{multiLine{Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs.
{{{
$("p").after( $("b") );
}}}
}}}
Register a handler to be called when Ajax requests complete. This is an Ajax Event.
|!Name|!Type|!Optional|!Description|h
|handler(event, XMLHttpRequest, ajaxOptions)|Function|no|The function to be invoked.|
|Arguments|c
!Description
<html><p>Whenever an Ajax request completes, jQuery triggers the <code>ajaxComplete</code> event. Any and all handlers that have been registered with the <code>.ajaxComplete()</code> method are executed at this time.</p>
<p>To observe this method in action, we can set up a basic Ajax load request:</p>
<pre><div class="trigger">Trigger</div>
<div class="result"></div>
<div class="log"></div>
</pre>
<p>We can attach our event handler to any element:</p>
<pre>$('.log').ajaxComplete(function() {
$(this).text('Triggered ajaxComplete handler.');
});
</pre>
<p>Now, we can make an Ajax request using any jQuery method:</p>
<pre>$('.trigger').click(function() {
$('.result').load('ajax/test.html');
});</pre>
<p>When the user clicks the button and the Ajax request completes, the log message is displayed.</p>
<p><strong>Note:</strong> Because <code>.ajaxComplete()</code> is implemented as a method of jQuery object instances, we can use the <code>this</code> keyword as we do here to refer to the selected elements within the callback function.</p>
<p>All <code>ajaxComplete</code> handlers are invoked, regardless of what Ajax request was completed. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an <code>ajaxComplete</code> handler is executed, it is passed the event object, the <code>XMLHttpRequest</code> object, and the settings object that was used in the creation of the request. For example, we can restrict our callback to only handling events dealing with a particular URL:</p>
<pre>$('.log').ajaxComplete(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html') {
$(this).text('Triggered ajaxComplete handler.');
}
});</pre></html>
!Examples
* {{multiLine{Show a message when an Ajax request completes.
{{{
$("#msg").ajaxComplete(function(event,request, settings){
$(this).append("<li>Request Complete.</li>");
});
}}}
}}}
Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.
|!Name|!Type|!Optional|!Description|h
|handler(event, XMLHttpRequest, ajaxOptions, thrownError)|Function|no|The function to be invoked.|
|Arguments|c
!Description
<html><p>Whenever an Ajax request completes with an error, jQuery triggers the <code>ajaxError</code> event. Any and all handlers that have been registered with the <code>.ajaxError()</code> method are executed at this time.</p>
<p>To observe this method in action, we can set up a basic Ajax load request:</p>
<pre><div class="trigger">Trigger</div>
<div class="result"></div>
<div class="log"></div></pre>
<p>We can attach our event handler to any element:</p>
<pre>$('.log').ajaxError(function() {
$(this).text('Triggered ajaxError handler.');
});</pre>
<p>Now, we can make an Ajax request using any jQuery method:</p>
<pre>$('.trigger').click(function() {
$('.result').load('ajax/missing.html');
});</pre>
<p>When the user clicks the button and the Ajax request fails, because the requested file is missing, the log message is displayed.</p>
<p><strong>Note:</strong> Because <code>.ajaxError()</code> is implemented as a method of jQuery object instances, we can use the <code>this</code> keyword as we do here to refer to the selected elements within the callback function.</p>
<p>All <code>ajaxError</code> handlers are invoked, regardless of what Ajax request was completed. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an <code>ajaxError</code> handler is executed, it is passed the event object, the <code>XMLHttpRequest</code> object, and the settings object that was used in the creation of the request. If the request failed because JavaScript raised an exception, the exception object is passed to the handler as a fourth parameter. For example, we can restrict our callback to only handling events dealing with a particular URL:</p>
<pre>$('.log').ajaxError(function(e, xhr, settings, exception) {
if (settings.url == 'ajax/missing.html') {
$(this).text('Triggered ajaxError handler.');
}
});</pre></html>
!Examples
* {{multiLine{Show a message when an Ajax request fails.
{{{
$("#msg").ajaxError(function(event, request, settings){
$(this).append("<li>Error requesting page " + settings.url + "</li>");
});
}}}
}}}
|!Name|!Type|!Optional|!Description|h
|handler(event, XMLHttpRequest, ajaxOptions)|Function|no|The function to be invoked.|
|Arguments|c
!Description
<html>
<p>Whenever an Ajax request is about to be sent, jQuery triggers the <code>ajaxSend</code> event. Any and all handlers that have been registered with the <code>.ajaxSend()</code> method are executed at this time.</p>
<p>To observe this method in action, we can set up a basic Ajax load request:</p>
<pre><div class="trigger">Trigger</div>
<div class="result"></div>
<div class="log"></div></pre>
<p>We can attach our event handler to any element:</p>
<pre>$('.log').ajaxSend(function() {
$(this).text('Triggered ajaxSend handler.');
});</pre>
<p>Now, we can make an Ajax request using any jQuery method:</p>
<pre>$('.trigger').click(function() {
$('.result').load('ajax/test.html');
});</pre>
<p>When the user clicks the button and the Ajax request is about to begin, the log message is displayed.</p>
<p><strong>Note:</strong> Because <code>.ajaxSend()</code> is implemented as a method of jQuery instances, we can use the <code>this</code> keyword as we do here to refer to the selected elements within the callback function.</p>
<p>All <code>ajaxSend</code> handlers are invoked, regardless of what Ajax request is to be sent. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an <code>ajaxSend</code> handler is executed, it is passed the event object, the <code>XMLHttpRequest</code> object, and the <a href="http://api.jquery.com/jQuery.ajax/">settings object</a> that was used in the creation of the Ajax request. For example, we can restrict our callback to only handling events dealing with a particular URL:</p>
<pre>$('.log').ajaxSend(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html') {
$(this).text('Triggered ajaxSend handler.');
}
});</pre>
</html>
!Examples
* {{multiLine{Show a message before an Ajax request is sent.
{{{
$("#msg").ajaxSend(function(evt, request, settings){
$(this).append("<li>Starting request at " + settings.url + "</li>");
});
}}}
}}}
Register a handler to be called when the first Ajax request begins. This is an Ajax Event.
|!Name|!Type|!Optional|!Description|h
|handler()|Function|no|The function to be invoked.|
|Arguments|c
!Description
<html><p>Whenever an Ajax request is about to be sent, jQuery checks whether there are any other outstanding Ajax requests. If none are in progress, jQuery triggers the <code>ajaxStart</code> event. Any and all handlers that have been registered with the <code>.ajaxStart()</code> method are executed at this time.</p>
<p>To observe this method in action, we can set up a basic Ajax load request:</p>
<pre><div class="trigger">Trigger</div>
<div class="result"></div>
<div class="log"></div></pre>
<p>We can attach our event handler to any element:</p>
<pre>$('.log').ajaxStart(function() {
$(this).text('Triggered ajaxStart handler.');
});</pre>
<p>Now, we can make an Ajax request using any jQuery method:</p>
<pre>$('.trigger').click(function() {
$('.result').load('ajax/test.html');
});</pre>
<p>When the user clicks the button and the Ajax request is sent, the log message is displayed.</p>
<p><strong>Note:</strong> Because <code>.ajaxStart()</code> is implemented as a method of jQuery object instances, we can use the <code>this</code> keyword as we do here to refer to the selected elements within the callback function.</p>
</html>
!Examples
* {{multiLine{Show a loading message whenever an Ajax request starts (and none is already active).
{{{
$("#loading").ajaxStart(function(){
$(this).show();
});
}}}
}}}
|!Name|!Type|!Optional|!Description|h
|handler()|Function|no|The function to be invoked.|
|Arguments|c
!Description
<html>
<p>Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the <code>ajaxStop</code> event. Any and all handlers that have been registered with the <code>.ajaxStop()</code> method are executed at this time.</p>
<p>To observe this method in action, we can set up a basic Ajax load request:</p>
<pre><div class="trigger">Trigger</div>
<div class="result"></div>
<div class="log"></div></pre>
<p>We can attach our event handler to any element:</p>
<pre>$('.log').ajaxStop(function() {
$(this).text('Triggered ajaxStop handler.');
});</pre>
<p>Now, we can make an Ajax request using any jQuery method:</p>
<pre>$('.trigger').click(function() {
$('.result').load('ajax/test.html');
});</pre>
<p>When the user clicks the button and the Ajax request completes, the log message is displayed.</p>
<p>Because <code>.ajaxStop()</code> is implemented as a method of jQuery object instances, we can use the <code>this</code> keyword as we do here to refer to the selected elements within the callback function.</p>
</html>
!Examples
* {{multiLine{Hide a loading message after all the Ajax requests have stopped.
{{{
$("#loading").ajaxStop(function(){
$(this).hide();
});
}}}
}}}
|!Name|!Type|!Optional|!Description|h
|handler(event, XMLHttpRequest, ajaxOptions)|Function|no|The function to be invoked.|
|Arguments|c
!Description
<html>
<p>Whenever an Ajax request completes successfully, jQuery triggers the <code>ajaxSuccess</code> event. Any and all handlers that have been registered with the <code>.ajaxSuccess()</code> method are executed at this time.</p>
<p>To observe this method in action, we can set up a basic Ajax load request:</p>
<pre><div class="trigger">Trigger</div>
<div class="result"></div>
<div class="log"></div></pre>
<p>We can attach our event handler to any element:</p>
<pre>$('.log').ajaxSuccess(function() {
$(this).text('Triggered ajaxSuccess handler.');
});</pre>
<p>Now, we can make an Ajax request using any jQuery method:</p>
<pre>$('.trigger').click(function() {
$('.result').load('ajax/test.html');
});</pre>
<p>When the user clicks the button and the Ajax request completes successfully, the log message is displayed.</p>
<p><strong>Note:</strong> Because <code>.ajaxSuccess()</code> is implemented as a method of jQuery object instances, we can use the <code>this</code> keyword as we do here to refer to the selected elements within the callback function.</p>
<p>All <code>ajaxSuccess</code> handlers are invoked, regardless of what Ajax request was completed. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an <code>ajaxSuccess</code> handler is executed, it is passed the event object, the <code>XMLHttpRequest</code> object, and the settings object that was used in the creation of the request. For example, we can restrict our callback to only handling events dealing with a particular URL:</p>
<pre>$('.log').ajaxSuccess(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html') {
$(this).text('Triggered ajaxSuccess handler.');
}
});</pre>
</html>
!Examples
* {{multiLine{Show a message when an Ajax request completes successfully.
{{{
$("#msg").ajaxSuccess(function(evt, request, settings){
$(this).append("<li>Successful Request!</li>");
});
}}}
}}}
Selects all elements.
!Description
<html><p>Caution: The all, or universal, selector is extremely slow, except when used by itself.</p> </html>
!Examples
* {{multiLine{Finds every element (including head, body, etc) in the document.
{{{
var elementCount = $("*").css("border","3px solid red").length;
$("body").prepend("<h3>" + elementCount + " elements found</h3>");
}}}
}}}
* {{multiLine{A common way to select all elements is to find within document.body so elements like head, script, etc are left out.
{{{
var elementCount = $("#test").find("*").css("border","3px solid red").length;
$("body").prepend("<h3>" + elementCount + " elements found</h3>");
}}}
}}}
Add the previous set of elements on the stack to the current set.
!Description
<html><p>As described in the discussion for <code>.end()</code> above, jQuery objects maintain an internal stack that keeps track of changes to the matched set of elements. When one of the DOM traversal methods is called, the new set of elements is pushed onto the stack. If the previous set of elements is desired as well, <code>.andSelf()</code> can help.</p>
<p>Consider a page with a simple list on it:</p>
<pre>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
</pre>
<p>If we begin at the third item, we can find the elements which come after it:</p>
<pre>$('li.third-item').nextAll().andSelf()
.css('background-color', 'red');
</pre>
<p>The result of this call is a red background behind items 3, 4 and 5. First, the initial selector locates item 3, initializing the stack with the set containing just this item. The call to <code>.nextAll()</code> then pushes the set of items 4 and 5 onto the stack. Finally, the <code>.andSelf()</code> invocation merges these two sets together, creating a jQuery object that points to all three items.</p></html>
!Examples
* {{multiLine{Find all divs, and all the paragraphs inside of them, and give them both classnames. Notice the div doesn't have the yellow background color since it didn't use andSelf.
{{{
$("div").find("p").andSelf().addClass("border");
$("div").find("p").addClass("background");
}}}
}}}
Perform a custom animation of a set of CSS properties.
|!Name|!Type|!Optional|!Description|h
|properties|Options|no|A map of CSS properties that the animation will move toward.|
|duration|String,Number|yes|A string or number determining how long the animation will run.|
|easing|String|yes|A string indicating which easing function to use for the transition.|
|callback|Callback|yes|A function to call once the animation is complete.|
|properties|Options|no|A map of CSS properties that the animation will move toward.|
|options|Options|no|A map of additional options to pass to the method. Supported keys:
duration: A string or number determining how long the animation will run.
easing: A string indicating which easing function to use for the transition.
complete: A function to call once the animation is complete.
step: A function to be called after each step of the animation.
queue: A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately.
specialEasing: A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions (added 1.4).
|
|Arguments|c
!Description
<html>
<p>The <code>.animate()</code> method allows us to create animation effects on any numeric CSS property. The only required parameter is a map of CSS properties. This map is similar to the one that can be sent to the <code>.css()</code> method, except that the range of properties is more restrictive.</p>
<p>All animated properties should be numeric (except as noted below); properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, <code>width</code>, <code>height</code>, or <code>left</code> can be animated but <code>background-color</code> cannot be.) Property values are treated as a number of pixels unless otherwise specified. The units <code>em</code> and <code>%</code> can be specified where applicable.</p>
<p>In addition to numeric values, each property can take the strings <code>'show'</code>, <code>'hide'</code>, and <code>'toggle'</code>. These shortcuts allow for custom hiding and showing animations that take into account the display type of the element.</p>
<p>Animated properties can also be relative. If a value is supplied with a leading <code>+=</code> or <code>-=</code> sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.</p>
<h4 id="duration">Duration</h4>
<p>Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings <code>'fast'</code> and <code>'slow'</code> can be supplied to indicate durations of <code>200</code> and <code>600</code> milliseconds, respectively.</p>
<h4 id="callback">Callback Function</h4>
<p>If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but <code>this</code> is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.</p>
<p>We can animate any element, such as a simple image:</p>
<pre><div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123"
style="position: relative; left: 10px;" /></pre>
<p>We can animate the opacity, left offset, and height of the image simultaneously:</p>
<pre>$('#clickme').click(function() {
$('#book').animate({
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 5000, function() {
// Animation complete.
});
});
</pre>
<p class="image">
<img src="/images/animate-1.jpg" alt=""/>
</p>
<p>Note that we have specified <code>toggle</code> as the target value of the <code>height</code> property. Since the image was visible before, the animation shrinks the height to 0 to hide it. A second click then reverses this transition:
</p>
<p class="image">
<img src="/images/animate-2.jpg" alt=""/>
</p>
<p>The <code>opacity</code> of the image is already at its target value, so this property is not animated by the second click. Since we specified the target value for <code>left</code> as a relative value, the image moves even farther to the right during this second animation.</p>
<p>The <code>position</code> attribute of the element must not be <code>static</code> if we wish to animate the <code>left</code> property as we do in the example.</p>
<blockquote><p>The <a href="http://jqueryui.com">jQuery UI</a> project extends the <code>.animate()</code> method by allowing some non-numeric styles such as colors to be animated. The project also includes mechanisms for specifying animations through CSS classes rather than individual attributes.</p></blockquote>
<h4 id="easing">Easing</h4>
<p>The remaining parameter of <code>.animate()</code> is a string naming an easing function to use. An easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called <code>swing</code>, and one that progresses at a constant pace, called <code>linear</code>. More easing functions are available with the use of plug-ins, most notably the <a href="http://jqueryui.com/">jQuery UI suite</a>.</p>
<h4 id="per-property-easing">Per-property Easing</h4>
<p>As of jQuery version 1.4, we can set per-property easing functions within a single <code>.animate()</code> call. In the first version of <code>.animate()</code>, each property can take an array as its value: The first member of the array is the CSS property and the second member is an easing function. If a per-property easing function is not defined for a particular property, it uses the value of the <code>.animate()</code> method's optional easing argument. If the easing argument is not defined, the default <code>swing</code> function is used.</p>
<p>We can, for example, simultaneously animate the width and height with the <code>swing</code> easing function and the opacity with the <code>linear</code> easing function:</p>
<pre>$('#clickme').click(function() {
$('#book').animate({
width: ['toggle', 'swing'],
height: ['toggle', 'swing'],
opacity: 'toggle'
}, 5000, 'linear', function() {
$(this).after('<div>Animation complete.</div>');
});
});</pre>
<p>In the second version of <code>.animate()</code>, the options map can include the <code>specialEasing</code> property, which is itself a map of CSS properties and their corresponding easing functions. We can simultaneously animate the width using the <code>linear</code> easing function and the height using the <code>easeOutBounce</code> easing function.</p>
<pre>$('#clickme').click(function() {
$('#book').animate({
width: 'toggle',
height: 'toggle'
}, {
duration: 5000,
specialEasing: {
width: 'linear',
height: 'easeOutBounce'
},
complete: function() {
$(this).after('<div>Animation complete.</div>');
}
});
});</pre>
<p>As previously noted, a plug-in is required for the <code>easeOutBounce</code> function.</p>
</html>
!Examples
* {{multiLine{Click the button to animate the div with a number of different 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 );
});
}}}
}}}
* {{multiLine{Shows a div animate with a relative move. Click several times on the buttons to see the relative animations queued up.
{{{
$("#right").click(function(){
$(".block").animate({"left": "+=50px"}, "slow");
});
$("#left").click(function(){
$(".block").animate({"left": "-=50px"}, "slow");
});
}}}
}}}
* {{multiLine{Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.
{{{
$("p").animate({
"height": "toggle", "opacity": "toggle"
}, "slow");
}}}
}}}
* {{multiLine{Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds.
{{{
$("p").animate({
"left": "50", "opacity": 1
}, 500);
}}}
}}}
* {{multiLine{An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. Note, this code will do nothing unless the paragraph element is hidden.
{{{
$("p").animate({
"opacity": "show"
}, "slow", "easein");
}}}
}}}
* {{multiLine{The first button shows how an unqueued animation works. It expands the div out to 90% width while the font-size is increasing. Once the font-size change is complete, the border animation will begin.
The second button starts a traditional chained animation, where each animation will start once the previous animation on the element has completed.
{{{
$("#go1").click(function(){
$("#block1").animate( { width:"90%" }, { queue:false, duration:3000 } )
.animate( { fontSize:"24px" }, 1500 )
.animate( { borderRightWidth:"15px" }, 1500);
});
$("#go2").click(function(){
$("#block2").animate( { width:"90%"}, 1000 )
.animate( { fontSize:"24px" } , 1000 )
.animate( { borderLeftWidth:"15px" }, 1000);
});
$("#go3").click(function(){
$("#go1").add("#go2").click();
});
$("#go4").click(function(){
$("div").css({width:"", fontSize:"", borderWidth:""});
});
}}}
}}}
* {{multiLine{Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.
{{{
$("p").animate({
"height": "toggle", "opacity": "toggle"
}, { duration: "slow" });
}}}
}}}
* {{multiLine{Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. It also will do it outside the queue, meaning it will automatically start without waiting for its turn.
{{{
$("p").animate({
left: "50px", opacity: 1
}, { duration: 500, queue: false });
}}}
}}}
* {{multiLine{An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function.
{{{
$("p").animate({
"opacity": "show"
}, { "duration": "slow", "easing": "easein" });
}}}
}}}
* {{multiLine{An example of using a callback function. The first argument is an array of CSS properties, the second specifies that the animation should take 1000 milliseconds to complete, the third states the easing type, and the fourth argument is an anonymous callback function.
{{{
$("p").animate({
height:200, width:400, opacity: .5
}, 1000, "linear", function(){alert("all done");} );
}}}
}}}
Select all elements that are in the progress of an animation at the time the selector is run.
!Description
N/A
!Examples
* {{multiLine{Change the color of any div that is animated.
{{{
$("#run").click(function(){
$("div:animated").toggleClass("colored");
});
function animateIt() {
$("#mover").slideToggle("slow", animateIt);
}
animateIt();
}}}
}}}
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|content|String, Element, jQuery|no|An element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.|
|function(index, html)|Function|no|A function that returns an HTML string to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments.|
|Arguments|c
!Description
<html><p>The <code>.append()</code> method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the <em>first</em> child, use <a href="http://api.jquery.com/prepend/"><code>.prepend()</code></a>). </p>
<p>The <code>.append()</code> and <code><a href="/appendTo">.appendTo()</a></code> methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With<code> .append()</code>, the selector expression preceding the method is the container into which the content is inserted. With <code>.appendTo()</code>, on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.</p>
<p>Consider the following HTML:</p>
<pre><h2>Greetings</h2>
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
</pre>
<p>We can create content and insert it into several elements at once:</p>
<pre>$('.inner').append('<p>Test</p>');
</pre>
<p>Each inner <code><div></code> element gets this new content:</p>
<pre><h2>Greetings</h2>
<div class="container">
<div class="inner">
Hello
<p>Test</p>
</div>
<div class="inner">
Goodbye
<p>Test</p>
</div>
</div>
</pre>
<p>We can also select an element on the page and insert it into another:</p>
<pre>$('.container').append($('h2'));
</pre>
<p>If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):</p>
<pre><div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
<h2>Greetings</h2>
</div>
</pre>
<p>If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.</p></html>
!Examples
* {{multiLine{Appends some HTML to all paragraphs.
{{{
$("p").append("<strong>Hello</strong>");
}}}
}}}
* {{multiLine{Appends an Element to all paragraphs.
{{{
$("p").append(document.createTextNode("Hello"));
}}}
}}}
* {{multiLine{Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
{{{
$("p").append( $("strong") );
}}}
}}}
Insert every element in the set of matched elements to the end of the target.
|!Name|!Type|!Optional|!Description|h
|target|Selector, Element, jQuery|no|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.|
|Arguments|c
!Description
<html><p>The <code><a href="/append">.append()</a></code> and <code>.appendTo()</code> methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With<code> .append()</code>, the selector expression preceding the method is the container into which the content is inserted. With <code>.appendTo()</code>, on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.</p>
<p>Consider the following HTML:</p>
<pre><h2>Greetings</h2>
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
</pre>
<p>We can create content and insert it into several elements at once:</p>
<pre>$('<p>Test</p>').appendTo('.inner');
</pre>
<p>Each inner <code><div></code> element gets this new content:</p>
<pre><h2>Greetings</h2>
<div class="container">
<div class="inner">
Hello
<p>Test</p>
</div>
<div class="inner">
Goodbye
<p>Test</p>
</div>
</div>
</pre>
<p>We can also select an element on the page and insert it into another:</p>
<pre>$('h2').appendTo($('.container'));
</pre>
<p>If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):</p>
<pre><div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
<h2>Greetings</h2>
</div>
</pre>
<p>If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.</p></html>
!Examples
* {{multiLine{Appends all spans to the element with the ID "foo"
{{{
$("span").appendTo("#foo"); // check append() examples
}}}
}}}
Set one or more attributes for the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|attributeName|String|no|The name of the attribute to set.|
|value|Object|no|A value to set for the attribute.|
|map|Map|no|A map of attribute-value pairs to set.|
|attributeName|String|no|The name of the attribute to set.|
|function(index, attr)|Function|no|A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.|
|Arguments|c
!Description
<html><p>The <code>.attr()</code> method is a convenient and powerful way to set the value of attributes—especially when setting multiple attributes or using values returned by a function. Let's consider the following image:</p>
<pre><img id="greatphoto" src="brush-seller.jpg" alt="brush seller" /></pre>
<h4>Setting a simple attribute</h4>
<p>We can change the <code>alt</code> attribute by simply passing the name of the attribute and its new value to the <code>.attr()</code> method:</p>
<pre>$('#greatphoto').attr('alt', 'Beijing Brush Seller');</pre>
<p>We can <em>add</em> an attribute the same way:</p>
<pre>$('#greatphoto')
.attr('title', 'Photo by Kelly Clark');</pre>
<h4>Setting several attributes at once</h4>
<p>To change the <code>alt</code> attribute and add the <code>title</code> attribute at the same time, we can pass both sets of names and values into the method at once using a map (JavaScript object literal). Each key-value pair in the map adds or modifies an attribute:</p>
<pre>$('#greatphoto').attr({
alt: 'Beijing Brush Seller',
title: 'photo by Kelly Clark'
});</pre>
<p>When setting multiple attributes, the quotes around attribute names are optional.</p>
<p><strong>WARNING</strong> When setting the 'class' attribute, you must always use quotes!</p>
<h4>Computed attribute values</h4>
<p>By using a function to set attributes, we can compute the value based on other properties of the element. For example, we could concatenate a new value with an existing value:</p>
<pre>$('#greatphoto').attr('title', function() {
return this.alt + ' - photo by Kelly Clark'
});</pre>
<p>This use of a function to compute attribute values can be particularly useful when we modify the attributes of multiple elements at once.</p></html>
!Examples
* {{multiLine{Set some attributes for all <img>s in the page.
{{{
$("img").attr({
src: "/images/hat.gif",
title: "jQuery",
alt: "jQuery Logo"
});
$("div").text($("img").attr("alt"));
}}}
}}}
* {{multiLine{Disables buttons greater than the 1st button.
{{{
$("button:gt(1)").attr("disabled","disabled");
}}}
}}}
* {{multiLine{Sets id for divs based on the position in the page.
{{{
$("div").attr("id", function (arr) {
return "div-id" + arr;
})
.each(function () {
$("span", this).html("(ID = '<b>" + this.id + "</b>')");
});
}}}
}}}
* {{multiLine{Sets src attribute from title attribute on the image.
{{{
$("img").attr("src", function() {
return "/images/" + this.title;
});
}}}
}}}
Selects elements that have the specified attribute with a value containing the a given substring.
|!Name|!Type|!Optional|!Description|h
|attribute|String|no|An attribute name.|
|value|String|no|An attribute value. Quotes are optional.|
|Arguments|c
!Description
<html><p>This is the most generous of the jQuery attribute selectors that match against a value. It will select an element if the selector's string appears anywhere within the element's attribute value. Compare this selector with the Attribute Contains Word selector (e.g. [attr~=word]), which is more appropriate in many cases.</p></html>
!Examples
* {{multiLine{Finds all inputs with a name attribute that contains 'man' and sets the value with some text.
{{{
$("input[name*='man']").val("has man in it!");
}}}
}}}
Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).
|!Name|!Type|!Optional|!Description|h
|attribute|String|no|An attribute name.|
|value|String|no|An attribute value. Quotes are optional.|
|Arguments|c
!Description
<html><p>This selector was introduced into the CSS specification to handle language attributes.</p></html>
!Examples
* {{multiLine{Finds all links with an hreflang attribute that is english.
{{{
$('a[hreflang|=en]').css('border','3px dotted green');
}}}
}}}
Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.
|!Name|!Type|!Optional|!Description|h
|attribute|String|no|An attribute name.|
|value|String|no|An attribute value. Quotes are optional.|
|Arguments|c
!Description
<html><p>This selector matches the test string against each word in the attribute value, where a "word" is defined as a string delimited by whitespace. The selector matches if the test string is exactly equal to any of the words.</p> </html>
!Examples
* {{multiLine{Finds all inputs with a name attribute that contains the word 'man' and sets the value with some text.
{{{
$("input[name~=man]").val("mr. man is in it!");
}}}
}}}
Selects elements that have the specified attribute with a value ending exactly with a given string.
|!Name|!Type|!Optional|!Description|h
|attribute|String|no|An attribute name.|
|value|String|no|An attribute value. Quotes are optional.|
|Arguments|c
!Description
N/A
!Examples
* {{multiLine{Finds all inputs with an attribute name that ends with 'letter' and puts text in them.
{{{
$("input[name$='letter']").val("a letter");
}}}
}}}
Selects elements that have the specified attribute with a value exactly equal to a certain value.
|!Name|!Type|!Optional|!Description|h
|attribute|String|no|An attribute name.|
|value|String|no|An attribute value. Quotes are optional.|
|Arguments|c
!Description
N/A
!Examples
* {{multiLine{Finds all inputs with name 'newsletter' and changes the text of the span next to it.
{{{
$("input[name='newsletter']").next().text(" is newsletter");
}}}
}}}
Selects elements that have the specified attribute, with any value.
|!Name|!Type|!Optional|!Description|h
|attribute|String|no|An attribute name.|
|Arguments|c
!Description
N/A
!Examples
* {{multiLine{Bind a single click that adds the div id to its text.
{{{
$("div[id]").one("click", function(){
var idString = $(this).text() + " = " + $(this).attr("id");
$(this).text(idString);
});
}}}
}}}
Matches elements that match all of the specified attribute filters.
|!Name|!Type|!Optional|!Description|h
|attributeFilter1|Selector|no|An attribute filter.|
|attributeFilter2|Selector|no|Another attribute filter, reducing the selection even more|
|attributeFilterN|Selector|yes|As many more attribute filters as necessary|
|Arguments|c
!Description
N/A
!Examples
* {{multiLine{Finds all inputs that have an id attribute and whose name attribute ends with man and sets the value.
{{{
$("input[id][name$='man']").val("only this one");
}}}
}}}
Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.
|!Name|!Type|!Optional|!Description|h
|attribute|String|no|An attribute name.|
|value|String|no|An attribute value. Quotes are optional.|
|Arguments|c
!Description
<html><p>This selector is equivalent to <code>:not([attr=value])</code>.</p> </html>
!Examples
* {{multiLine{Finds all inputs that don't have the name 'newsletter' and appends text to the span next to it.
{{{
$("input[name!=newsletter]").next().append("<b>; not newsletter</b>");
}}}
}}}
Selects elements that have the specified attribute with a value beginning exactly with a given string.
|!Name|!Type|!Optional|!Description|h
|attribute|String|no|An attribute name.|
|value|String|no|An attribute value. Quotes are optional.|
|Arguments|c
!Description
<html><p>This selector can be useful for identifying elements in pages produced by server-side frameworks that produce HTML with systematic element IDs. However it will be slower than using a class selector so leverage classes, if you can, to group like elements.</p></html>
!Examples
* {{multiLine{Finds all inputs with an attribute name that starts with 'news' and puts text in them.
{{{
$("input[name^='news']").val("news here!");
}}}
}}}
Insert content, specified by the parameter, before each element in the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|content|String, Element, jQuery|no|An element, HTML string, or jQuery object to insert before each element in the set of matched elements.|
|function|Function|no|A function that returns an HTML string to insert before each element in the set of matched elements.|
|Arguments|c
!Description
<html><p>The <code>.before()</code> and <code><a href="/insertBefore">.insertBefore()</a></code> methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With<code> .before()</code>, the selector expression preceding the method is the container before which the content is inserted. With <code>.insertBefore()</code>, on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted before the target container.</p>
<p>Consider the following HTML:</p>
<pre><div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>We can create content and insert it before several elements at once:</p>
<pre>$('.inner').before('<p>Test</p>');</pre>
<p>Each inner <code><div></code> element gets this new content:</p>
<pre><div class="container">
<h2>Greetings</h2>
<p>Test</p>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">Goodbye</div>
</div></pre>
<p>We can also select an element on the page and insert it before another:</p>
<pre>$('.container').before($('h2'));</pre>
<p>If an element selected this way is inserted elsewhere, it will be moved before the target (not cloned):</p>
<pre><h2>Greetings</h2>
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.</p>
<p>In jQuery 1.4, <code>.before()</code> and <code>.after()</code> will also work on disconnected DOM nodes:</p>
<pre>$("<div/>").before("<p></p>");</pre>
<p>The result is a jQuery set that contains a paragraph and a div (in that order).</p></html>
!Examples
* {{multiLine{Inserts some HTML before all paragraphs.
{{{
$("p").before("<b>Hello</b>");
}}}
}}}
* {{multiLine{Inserts a DOM element before all paragraphs.
{{{
$("p").before( document.createTextNode("Hello") );
}}}
}}}
* {{multiLine{Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs.
{{{
$("p").before( $("b") );
}}}
}}}
Attach a handler to an event for the elements.
|!Name|!Type|!Optional|!Description|h
|eventType|String|no|A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.|
|eventData|Object|yes|A map of data that will be passed to the event handler.|
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|events|Object|no|A map of one or more JavaScript event types and functions to execute for them.|
|Arguments|c
!Description
<html><p>The <code>.bind()</code> method is the primary means of attaching behavior to a document. All JavaScript event types, such as <code>focus</code>, <code>mouseover</code>, and <code>resize</code>, are allowed for <code>eventType.</code></p>
<p>The jQuery library provides shortcut methods for binding the standard event types, such as <code>.click()</code> for <code>.bind('click')</code>. A description of each can be found in the discussion of its shortcut method: <a href="/blur">blur</a>, <a href="/focus">focus</a>, <a href="/focusin">focusin</a>, <a href="/focusout">focusout</a>, <a href="/load">load</a>, <a href="/resize">resize</a>, <a href="/scroll">scroll</a>, <a href="/unload">unload</a>, <a href="/click">click</a>, <a href="/dblclick">dblclick</a>, <a href="/mousedown">mousedown</a>, <a href="/mouseup">mouseup</a>, <a href="/mousemove">mousemove</a>, <a href="/mouseover">mouseover</a>, <a href="/mouseout">mouseout</a>, <a href="/mouseenter">mouseenter</a>, <a href="/mouseleave">mouseleave</a>, <a href="/change">change</a>, <a href="/select">select</a>, <a href="/submit">submit</a>, <a href="/keydown">keydown</a>, <a href="/keypress">keypress</a>, <a href="/keyup">keyup</a>, <a href="/error">error</a></p>
<p>Any string is legal for <code>eventType</code>; if the string is not the name of a native JavaScript event, then the handler is bound to a custom event. These events are never called by the browser, but may be triggered manually from other JavaScript code using <code>.trigger()</code> or <code>.triggerHandler()</code>.</p>
<p>If the <code>eventType</code> string contains a period (<code>.</code>) character, then the event is namespaced. The period character separates the event from its namespace. For example, in the call <code>.bind('click.name', handler)</code>, the string <code>click</code> is the event type, and the string <code>name</code> is the namespace. Namespacing allows us to unbind or trigger some events of a type without affecting others. See the discussion of <code>.unbind()</code> for more information.</p>
<p>When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.</p>
<p>A basic usage of <code>.bind()</code> is:</p>
<pre>
$('#foo').bind('click', function() {
alert('User clicked on "foo."');
});
</pre>
<p>This code will cause the element with an ID of <code>foo</code> to respond to the <code>click</code> event. When a user clicks inside this element thereafter, the alert will be shown.</p>
<h4 id="multiple-events">Multiple Events</h4>
<p>Multiple event types can be bound at once by including each one separated by a space:</p>
<pre>
$('#foo').bind('mouseenter mouseleave', function() {
$(this).toggleClass('entered');
});
</pre>
<p>The effect of this on <code><div id="foo"></code> (when it does not initially have the "entered" class) is to add the "entered" class when the mouse enters the <code><div></code> and remove the class when the mouse leaves. </p>
<p>As of jQuery 1.4 we can bind multiple event handlers simultaneously by passing a map of event type/handler pairs:</p>
<pre>
$('#foo').bind({
click: function() {
// do something on click
},
mouseenter: function() {
// do something on mouseenter
}
});
</pre>
<h4 id="event-handlers">Event Handlers</h4>
<p>The <code>handler</code> parameter takes a callback function, as shown above. Within the handler, the keyword <code>this</code> refers to the DOM element to which the handler is bound. To make use of the element in jQuery, it can be passed to the normal <code>$()</code> function. For example:</p>
<pre>$('#foo').bind('click', function() {
alert($(this).text());
});
</pre>
<p>After this code is executed, when the user clicks inside the element with an ID of <code>foo</code>, its text contents will be shown as an alert.
</p>
<p>As of jQuery 1.4.2 duplicate event handlers can be bound to an element instead of being discarded. For example:</p>
<pre>function test(){ alert("Hello"); }
$("button").click( test );
$("button").click( test );</pre>
<p>The above will generate two alerts when the button is clicked.</p>
<h4 id="event-object"><a href="/category/events/event-object/">The Event object</a></h4>
<p>The <code>handler</code> callback function can also take parameters. When the function is called, the JavaScript event object will be passed to the first parameter.</p>
<p>The event object is often unnecessary and the parameter omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered. However, at times it becomes necessary to gather more information about the user's environment at the time the event was initiated. <a href="/category/events/event-object/">View the full Event Object</a>.</p>
<p>Returning <code>false</code> from a handler is equivalent to calling both <code>.preventDefault()</code> and <code>.stopPropagation()</code> on the event object.</p>
<p>Using the event object in a handler looks like this:</p>
<pre>$(document).ready(function() {
$('#foo').bind('click', function(event) {
alert('The mouse cursor is at ('
+ event.pageX + ', ' + event.pageY + ')');
});
});
</pre>
<p>Note the parameter added to the anonymous function. This code will cause a click on the element with ID <code>foo</code> to report the page coordinates of the mouse cursor at the time of the click.</p>
<h4 id="passing-event-data">Passing Event Data</h4>
<p>The optional <code>eventData</code> parameter is not commonly used. When provided, this argument allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures. For example, suppose we have two event handlers that both refer to the same external variable:</p>
<pre>var message = 'Spoon!';
$('#foo').bind('click', function() {
alert(message);
});
message = 'Not in the face!';
$('#bar').bind('click', function() {
alert(message);
});
</pre>
<p>Because the handlers are closures that both have <code>message</code> in their environment, both will display the message <span class="output">Not in the face!</span> when triggered. The variable's value has changed. To sidestep this, we can pass the message in using <code>eventData</code>:
</p>
<pre>var message = 'Spoon!';
$('#foo').bind('click', {msg: message}, function(event) {
alert(event.data.msg);
});
message = 'Not in the face!';
$('#bar').bind('click', {msg: message}, function(event) {
alert(event.data.msg);
});
</pre>
<p>This time the variable is not referred to directly within the handlers; instead, the variable is passed in <em>by value</em> through <code>eventData</code>, which fixes the value at the time the event is bound. The first handler will now display <span class="output">Spoon!</span> while the second will alert <span class="output">Not in the face!</span>
</p>
<blockquote>
<p>Note that objects are passed to functions <em>by reference</em>, which further complicates this scenario.</p>
</blockquote>
<p>If <code>eventData</code> is present, it is the second argument to the <code>.bind()</code> method; if no additional data needs to be sent to the handler, then the callback is passed as the second and final argument.</p>
<blockquote><p>See the <code>.trigger()</code> method reference for a way to pass data to a handler at the time the event happens rather than when the handler is bound.</p></blockquote>
<p>As of jQuery 1.4 we can no longer attach data (and thus, events) to object, embed, or applet elements because critical errors occur when attaching data to Java applets.</p>
</html>
!Examples
* {{multiLine{Handle click and double-click for the paragraph. Note: the coordinates are window relative, so in this case relative to the demo iframe.
{{{
$("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");
});
}}}
}}}
* {{multiLine{To display each paragraph's text in an alert box whenever it is clicked:
{{{
$("p").bind("click", function(){
alert( $(this).text() );
});
}}}
}}}
* {{multiLine{You can pass some extra data before the event handler:
{{{
function handler(event) {
alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)
}}}
}}}
* {{multiLine{Cancel a default action and prevent it from bubbling up by returning false:
{{{
false$("form").bind("submit", function() { return false; })
}}}
}}}
* {{multiLine{Cancel only the default action by using the .preventDefault() method.
{{{
$("form").bind("submit", function(event) {
event.preventDefault();
});
}}}
}}}
* {{multiLine{Stop an event from bubbling without preventing the default action by using the .stopPropagation() method.
{{{
$("form").bind("submit", function(event) {
event.stopPropagation();
});
}}}
}}}
* {{multiLine{Bind custom events.
{{{
$("p").bind("myCustomEvent", function(e, myName, myValue){
$(this).text(myName + ", hi there!");
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent", [ "John" ]);
});
}}}
}}}
* {{multiLine{Bind multiple events simultaneously.
{{{
$("div.test").bind({
click: function(){
$(this).addClass("active");
},
mouseenter: function(){
$(this).addClass("inside");
},
mouseleave: function(){
$(this).removeClass("inside");
}
});
}}}
}}}
Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('blur', handler)</code> in the first variation, and <code>.trigger('blur')</code> in the second.</p>
<p>The <code>blur</code> event is sent to an element when it loses focus. Originally, this event was only applicable to form elements, such as <code><input></code>. In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page.</p>
<p>For example, consider the HTML:</p>
<pre><form>
<input id="target" type="text" value="Field 1" />
<input type="text" value="Field 2" />
</form>
<div id="other">
Trigger the handler
</div>
The event handler can be bound to the first input field:
$('#target').blur(function() {
alert('Handler for .blur() called.');
});</pre>
<p>Now if the first field has the focus and we click elsewhere, or tab away from it, the alert is displayed:</p>
<p><span class="output">Handler for .blur() called.</span></p>
<p>We can trigger the event when another element is clicked:</p>
<pre>$('#other').click(function() {
$('#target').blur();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also alert the message.</p>
<p>The <code>blur</code> event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the <code>blur</code> event will not work consistently across browsers.</p>
</html>
!Examples
* {{multiLine{To trigger the blur event on all paragraphs:
{{{
$("p").blur();
}}}
}}}
Selects all button elements and elements of type button.
!Description
N/A
!Examples
* {{multiLine{Finds all button inputs.
{{{
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
}}}
}}}
Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('change', handler)</code> in the first variation, and <code>.trigger('change')</code> in the second.</p>
<p>The <code>change</code> event is sent to an element when its value changes. This event is limited to <code><input></code> elements, <code><textarea></code> boxes and <code><select></code> elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.</p>
<p>For example, consider the HTML:</p>
<pre><form>
<input class="target" type="text" value="Field 1" />
<select class="target">
<option value="option1" selected="selected">Option 1</option>
<option value="option2">Option 2</option>
</select>
</form>
<div id="other">
Trigger the handler
</div></pre>
<p>The event handler can be bound to the text input and the select box:</p>
<pre>$('.target').change(function() {
alert('Handler for .change() called.');
});</pre>
<p>Now when the second option is selected from the dropdown, the alert is displayed. It is also displayed if we change the text in the field and then click away. If the field loses focus without the contents having changed, though, the event is not triggered. We can trigger the event manually when another element is clicked:</p>
<pre>$('#other').click(function() {
$('.target').change();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also alert the message. The message will be displayed twice, because the handler has been bound to the <code>change</code> event on both of the form elements.</p>
<p>As of jQuery 1.4 the <code>change</code> event now bubbles, and works identically to all other browsers, in Internet Explorer.</p>
</html>
!Examples
* {{multiLine{Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.
{{{
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
}}}
}}}
* {{multiLine{To add a validity test to all text input elements:
{{{
$("input[type='text']").change( function() {
// check input ($(this).val()) for validity here
});
}}}
}}}
Selects all elements of type checkbox.
!Description
<html><p><code>$(':checkbox')</code> is equivalent to <code>$('[type=checkbox]')</code>. As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare <code>$(':checkbox')</code> is equivalent to <code>$('*:checkbox')</code>, so <code>$('input:checkbox')</code> should be used instead. </p>
</html>
!Examples
* {{multiLine{Finds all checkbox inputs.
{{{
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
}}}
}}}
Matches all elements that are checked.
!Description
<html><p>The <code>:checked</code> selector works for checkboxes and radio buttons. For select elements, use the <code>:selected</code> selector.</p></html>
!Examples
* {{multiLine{Finds all input elements that are checked.
{{{
function countChecked() {
var n = $("input:checked").length;
$("div").text(n + (n <= 1 ? " is" : " are") + " checked!");
}
countChecked();
$(":checkbox").click(countChecked);
}}}
}}}
Selects all direct child elements specified by "child" of elements specified by "parent".
|!Name|!Type|!Optional|!Description|h
|parent|Selector|no|Any valid selector.|
|child|Selector|no|A selector to filter the child elements.|
|Arguments|c
!Description
<html><p>As a CSS selector, the child combinator is supported by all modern web browsers including Safari, Firefox, Opera, Chrome, and Internet Explorer 7 and above, but notably not by Internet Explorer versions 6 and below. However, in jQuery, this selector (along with all others) works across all supported browsers, including IE6.</p>
<p>The child combinator (E <strong>></strong> F) can be thought of as a more specific form of the descendant combinator (E F) in that it selects only first-level descendants.</p></html>
!Examples
* {{multiLine{Places a border around all list items that are children of <ul class="topnav"> .
{{{
$("ul.topnav > li").css("border", "3px double red");
}}}
}}}
Get the children of each element in the set of matched elements, optionally filtered by a selector.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|yes|A string containing a selector expression to match elements against.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.children()</code> method allows us to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The <code>.find()</code> and <code>.children()</code> methods are similar, except that the latter only travels a single level down the DOM tree.</p>
<p>The method optionally accepts a selector expression of the same type that we can pass to the <code>$()</code> function. If the selector is supplied, the elements will be filtered by testing whether they match it.</p>
<p>Consider a page with a basic nested list on it:</p>
<pre>
<ul class="level-1">
<li class="item-i">I</li>
<li class="item-ii">II
<ul class="level-2">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>
</pre>
<p>If we begin at the level-2 list, we can find its children:</p>
<pre>$('ul.level-2').children().css('background-color', 'red');</pre>
<p>The result of this call is a red background behind items A, B, and C. Since we do not supply a selector expression, all of the children are part of the returned jQuery object. If we had supplied one, only the matching items among these three would be included.</p></html>
!Examples
* {{multiLine{Find all children of the clicked element.
{{{
$("#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;
});
}}}
}}}
* {{multiLine{Find all children of each div.
{{{
$("div").children().css("border-bottom", "3px double red");
}}}
}}}
* {{multiLine{Find all children with a class "selected" of each div.
{{{
$("div").children(".selected").css("color", "blue");
}}}
}}}
Selects all elements with the given class.
|!Name|!Type|!Optional|!Description|h
|class|String|no|A class to search for. An element can have multiple classes; only one of them must match.|
|Arguments|c
!Description
<html><p>For class selectors, jQuery uses JavaScript's native <code>getElementsByClassName()</code> function if the browser supports it.</p>
</html>
!Examples
* {{multiLine{Finds the element with the class "myClass".
{{{
$(".myClass").css("border","3px solid red");
}}}
}}}
* {{multiLine{Finds the element with both "myclass" and "otherclass" classes.
{{{
$(".myclass.otherclass").css("border","13px solid red");
}}}
}}}
Remove from the queue all items that have not yet been run.
|!Name|!Type|!Optional|!Description|h
|queueName|String|yes|A string containing the name of the queue. Defaults to fx, the standard effects queue.|
|Arguments|c
!Description
<html><p>When the <code>.clearQueue()</code> method is called, all functions on the queue that have not been executed are removed from the queue. When used without an argument, <code>.clearQueue()</code> removes the remaining functions from <code>fx</code>, the standard effects queue. In this way it is similar to <code>.stop(true)</code>. However, while the <code>.stop()</code> method is meant to be used only with animations, <code>.clearQueue()</code> can also be used to remove any function that has been added to a generic jQuery queue with the <code>.queue()</code> method. </p></html>
!Examples
* {{multiLine{Empty the 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();
});
}}}
}}}
Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('click', handler)</code> in the first variation, and <code>.trigger('click')</code> in the second.</p>
<p>The <code>click</code> event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event.</p>
<pre>For example, consider the HTML:
<div id="target">
Click here
</div>
<div id="other">
Trigger the handler
</div></pre>
<p class="image"><img src="/images/0042_05_03.png" alt=""/></p>
<p>The event handler can be bound to any <code><div></code>:</p>
<pre>$('#target').click(function() {
alert('Handler for .click() called.');
});</pre>
<p>Now if we click on this element, the alert is displayed:</p>
<p><span class="output">Handler for .click() called.</span></p>
<p>We can also trigger the event when a different element is clicked:</p>
<pre>$('#other').click(function() {
$('#target').click();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also alert the message.</p>
<p>The <code>click</code> event is only triggered after this exact series of events:</p>
<ul>
<li>The mouse button is depressed while the pointer is inside the element.</li>
<li>The mouse button is released while the pointer is inside the element.</li>
</ul>
<p>This is usually the desired sequence before taking an action. If this is not required, the <code>mousedown</code> or <code>mouseup</code> event may be more suitable.</p>
</html>
!Examples
* {{multiLine{To hide paragraphs on a page when they are clicked:
{{{
$("p").click(function () {
$(this).slideUp();
});
$("p").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});
}}}
}}}
* {{multiLine{To trigger the click event on all of the paragraphs on the page:
{{{
$("p").click();
}}}
}}}
Create a copy of the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|withDataAndEvents|Boolean|yes|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.|
|Arguments|c
!Description
<html><p>The <code>.clone()</code> method, when used in conjunction with one of the insertion methods, is a convenient way to duplicate elements on a page. Consider the following HTML:</p>
<pre><div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div></pre>
<p>As shown in the discussion for <code><a href="/append">.append()</a></code>, normally when we insert an element somewhere in the DOM, it is moved from its old location. So, given the code:</p>
<pre>$('.hello').appendTo('.goodbye');</pre>
<p>The resulting DOM structure would be:</p>
<pre><div class="container">
<div class="goodbye">
Goodbye
<div class="hello">Hello</div>
</div>
</div></pre>
<p>To prevent this and instead create a copy of the element, we could write the following:</p>
<pre>$('.hello').clone().appendTo('.goodbye');</pre>
<p>This would produce:</p>
<pre><div class="container">
<div class="hello">Hello</div>
<div class="goodbye">
Goodbye
<div class="hello">Hello</div>
</div>
</div></pre>
<blockquote><p>Note that when using the <code>.clone()</code> method, we can modify the cloned elements or their contents before (re-)inserting them into the document.</p></blockquote>
<p>Normally, any event handlers bound to the original element are <em>not</em> copied to the clone. The optional <code>withDataAndEvents </code>parameter allows us to change this behavior, and to instead make copies of all of the event handlers as well, bound to the new copy of the element. As of jQuery 1.4, all element data (attached by the <code>.data()</code> method) is also copied to the new copy. </p></html>
!Examples
* {{multiLine{Clones all b elements (and selects the clones) and prepends them to all paragraphs.
{{{
$("b").clone().prependTo("p");
}}}
}}}
Gets an array of all the elements and selectors matched against the current element up through the DOM tree.
|!Name|!Type|!Optional|!Description|h
|selectors|Array|no|An array or string containing a selector expression to match elements against (can also be a jQuery object).|
|context|Element|yes|A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.|
|Arguments|c
!Description
<html><p>This method is primarily meant to be used internally or by plugin authors.</p></html>
!Examples
* {{multiLine{Show how event delegation can be done with closest.
{{{
var close = $("li:first").closest(["ul", "body"]);
$.each(close, function(i){
$("li").eq(i).html( this.selector + ": " + this.elem.nodeName );
});
}}}
}}}
Select all elements that contain the specified text.
!Description
<html><p>The matching text can appear directly within the selected element, in any of that element's descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of <code>:contains()</code> can be written as bare words or surrounded by quotation marks. The text must have matching case to be selected.</p></html>
!Examples
* {{multiLine{Finds all divs containing "John" and underlines them.
{{{
$("div:contains('John')").css("text-decoration", "underline");
}}}
}}}
Get the children of each element in the set of matched elements, including text nodes.
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.contents()</code> method allows us to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The <code>.contents()</code> and <code>.children()</code> methods are similar, except that the former includes text nodes as well as HTML elements in the resulting jQuery object.</p>
<p>The <code>.contents()</code> method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.</p>
<p>Consider a simple <code><div></code> with a number of text nodes, each of which is separated by two line break elements (<code><br /></code>):</p>
<pre><div class="container">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
<br /><br />
Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.
<br /> <br />
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur.
</div>
</pre>
<p>We can employ the <code>.contents()</code> method to help convert this blob of text into three well-formed paragraphs:</p>
<pre>
$('.container').contents().filter(function() {
return this.nodeType == 3;
})
.wrap('<p></p>')
.end()
.filter('br')
.remove();
</pre>
<p>This code first retrieves the contents of <code><div class="container"></code> and then filters it for text nodes, which are wrapped in paragraph tags. This is accomplished by testing the <a href="https://developer.mozilla.org/en/nodeType"><code>.nodeType</code> property</a> of the element. This DOM property holds a numeric code indicating the node's type; text nodes use the code 3. The contents are again filtered, this time for <code><br /></code> elements, and these elements are removed.</p>
</html>
!Examples
* {{multiLine{Find all the text nodes inside a paragraph and wrap them with a bold tag.
{{{
$("p").contents().filter(function(){ return this.nodeType != 1; }).wrap("<b/>");
}}}
}}}
* {{multiLine{Change the background colour of links inside of an iframe.
{{{
$("#frameDemo").contents().find("a").css("background-color","#BADA55");
}}}
}}}
The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document.
!Description
<html><p>The <code>.live()</code> method for binding event handlers uses this property to determine the root element to use for its event delegation needs. Plug-ins which perform similar tasks may also find the property useful.</p><p>
The value of this property is typically equal to document, as this is the default context for jQuery objects if none is supplied. The context may differ if, for example, the object was created by searching within an <code><iframe></code> or XML document.</p></html>
!Examples
* {{multiLine{Determine the exact context used.
{{{
$("ul")
.append("<li>" + $("ul").context + "</li>")
.append("<li>" + $("ul", document.body).context.nodeName + "</li>");
}}}
}}}
Set one or more CSS properties for the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|propertyName|String|no|A CSS property name.|
|value|String, Number|no|A value to set for the property.|
|propertyName|String|no|A CSS property name.|
|function(index, value)|Function|no|A function returning the value to set. Receives the index position of the element in the set and the old value as arguments.|
|map|Map|no|A map of property-value pairs to set.|
|Arguments|c
!Description
<html><p>As with the <code>.attr()</code> method, the <code>.css()</code> method makes setting properties of elements quick and easy. This method can take either a property name and value as separate parameters, or a single map of key-value pairs (JavaScript object notation).</p>
<p>Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both <code>.css({'background-color': '#ffe', 'border-left': '5px solid #ccc'})</code> and <code>.css({backgroundColor: '#ffe', borderLeft: '5px solid #ccc'})</code>. Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name.</p>
<p>As with <code><a href="/attr">.attr()</a></code>, <code>.css()</code> allows us to pass a function as the property value:</p>
<pre>$('div.example').css('width', function(index) {
return index * 50;
});</pre>
<p>This example sets the widths of the matched elements to incrementally larger values.</p></html>
!Examples
* {{multiLine{To change the color of any paragraph to red on mouseover event.
{{{
$("p").mouseover(function () {
$(this).css("color","red");
});
}}}
}}}
* {{multiLine{To highlight a clicked word in the paragraph.
{{{
var words = $("p:first").text().split(" ");
var text = words.join("</span> <span>");
$("p:first").html("<span>" + text + "</span>");
$("span").click(function () {
$(this).css("background-color","yellow");
});
}}}
}}}
* {{multiLine{To set the color of all paragraphs to red and background to blue:
{{{
$("p").hover(function () {
$(this).css({'background-color' : 'yellow', 'font-weight' : 'bolder'});
}, function () {
var cssObj = {
'background-color' : '#ddd',
'font-weight' : '',
'color' : 'rgb(0,40,244)'
}
$(this).css(cssObj);
});
}}}
}}}
* {{multiLine{Increase the size of a div when you click it:
{{{
$("div").click(function() {
$(this).css({
width: function(index, value) {
return parseFloat(value) * 1.2;
},
height: function(index, value) {
return parseFloat(value) * 1.2;
}
});
});
}}}
}}}
Returns value at named data store for the element, as set by data(name, value).
|!Name|!Type|!Optional|!Description|h
|key|String|no|Name of the data stored.|
|Arguments|c
!Description
<html>
<p>The <code>.data()</code> method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can retrieve several distinct values for a single element one at a time, or as a set:</p>
<pre>
alert($('body').data('foo'));
alert($('body').data());
</pre>
<p>The above lines alert the data values that were set on the <code>body</code> element. If nothing was set on that element, an empty string is returned:</p>
<p>Calling <code>.data()</code> with no parameters retrieves all of the values as a JavaScript object. This object can be safely cached in a variable as long as a new object is not set with <code>.data(obj)</code>.</p>
</html>
!Examples
* {{multiLine{Get the data named "blah" stored at for an element.
{{{
$("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);
});
}}}
}}}
Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('dblclick', handler)</code> in the first variation, and <code>.trigger('dblclick')</code> in the second.
The <code>dblclick</code> event is sent to an element when the element is double-clicked. Any HTML element can receive this event.
For example, consider the HTML:</p>
<pre><div id="target">
Double-click here
</div>
<div id="other">
Trigger the handler
</div></pre>
<p class="image"><img src="/images/0042_05_04.png" alt=""/>
</p>
<p>The event handler can be bound to any <code><div></code>:</p>
<pre>$('#target').dblclick(function() {
alert('Handler for .dblclick() called.');
});</pre>
<p>Now if we double-click on this element, the alert is displayed:</p>
<p><span class="output">Handler for .dblclick() called.</span></p>
<p>We can also trigger the event when a different element is clicked:</p>
<pre>$('#other').click(function() {
$('#target').dblclick();
});</pre>
<p>After this code executes, (single) clicks on <span class="output">Trigger the handler</span> will also alert the message.</p>
<p>The <code>dblclick</code> event is only triggered after this exact series of events:</p>
<ul>
<li>The mouse button is depressed while the pointer is inside the element.</li>
<li>The mouse button is released while the pointer is inside the element.</li>
<li>The mouse button is depressed again while the pointer is inside the element, within a time window that is system-dependent.</li>
<li>The mouse button is released while the pointer is inside the element.</li>
</ul>
<p>It is inadvisable to bind handlers to both the <code>click</code> and <code>dblclick</code> events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two <code>click</code> events and others only one. If an interface that reacts differently to single- and double-clicks cannot be avoided, then the <code>dblclick</code> event should be simulated within the <code>click</code> handler. We can achieve this by saving a timestamp in the handler, and then comparing the current time to the saved timestamp on subsequent clicks. If the difference is small enough, we can treat the click as a double-click.
</p>
</html>
!Examples
* {{multiLine{To bind a "Hello World!" alert box the dblclick event on every paragraph on the page:
{{{
$("p").dblclick( function () { alert("Hello World!"); });
}}}
}}}
* {{multiLine{Double click to toggle background color.
{{{
var divdbl = $("div:first");
divdbl.dblclick(function () {
divdbl.toggleClass('dbl');
});
}}}
}}}
Set a timer to delay execution of subsequent items in the queue.
|!Name|!Type|!Optional|!Description|h
|duration|Integer|no|An integer indicating the number of milliseconds to delay execution of the next item in the queue.|
|queueName|String|yes|A string containing the name of the queue. Defaults to fx, the standard effects queue.|
|Arguments|c
!Description
<html><p>Added to jQuery in version 1.4, the <code>.delay()</code> method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. </p>
<p>Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings <code>'fast'</code> and <code>'slow'</code> can be supplied to indicate durations of 200 and 600 milliseconds, respectively.</p>
<p>Using the standard effects queue, we can, for example, set an 800-millisecond delay between the <code>.slideUp()</code> and <code>.fadeIn()</code> of <code><div id="foo"></code>:</p>
<pre>$('#foo').slideUp(300).delay(800).fadeIn(400);</pre>
<p>When this statement is executed, the element slides up for 300 milliseconds and then pauses for 800 milliseconds before fading in for 400 milliseconds.</p>
<p><strong>jQuery.delay() is best for delaying between queued jQuery effects and such, and is not a replacement for JavaScript's native <a href="https://developer.mozilla.org/en/DOM/window.setTimeout">setTimeout</a> function, which may be more appropriate for certain use cases.</strong></p>
</html>
!Examples
* {{multiLine{Animate the hiding and showing of two divs, delaying the first before showing it.
{{{
$("button").click(function() {
$("div.first").slideUp(300).delay(800).fadeIn(400);
$("div.second").slideUp(300).fadeIn(400);
});
}}}
}}}
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.
|!Name|!Type|!Optional|!Description|h
|selector|String|no|A selector to filter the elements that trigger the event.|
|eventType|String|no|A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.|
|handler|Function|no|A function to execute at the time the event is triggered.|
|selector|String|no|A selector to filter the elements that trigger the event.|
|eventType|String|no|A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.|
|eventData|Object|no|A map of data that will be passed to the event handler.|
|handler|Function|no|A function to execute at the time the event is triggered.|
|Arguments|c
!Description
<html>
<p>Delegate is an alternative to using the <a href="/live">.live()</a> method, allowing for each binding of event delegation to specific DOM elements. For example the following delegate code:</p>
<pre>$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});</pre>
<p>Is equivalent to the following code written using <code>.live()</code>:</p>
<pre>$("table").each(function(){
$("td", this).live("hover", function(){
$(this).toggleClass("hover");
});
});</pre>
<p>See also the <a href="/undelegate">.undelegate()</a> method for a way of removing event handlers added in <a href="/delegate">.delegate()</a>.</p>
</html>
!Examples
* {{multiLine{Click a paragraph to add another. Note that .delegate() binds the click event to all paragraphs - even new ones.
{{{
$("body").delegate("p", "click", function(){
$(this).after("<p>Another paragraph!</p>");
});
}}}
}}}
* {{multiLine{To display each paragraph's text in an alert box whenever it is clicked:
{{{
$("body").delegate("p", "click", function(){
alert( $(this).text() );
});
}}}
}}}
* {{multiLine{To cancel a default action and prevent it from bubbling up, return false:
{{{
$("body").delegate("a", "click", function() { return false; })
}}}
}}}
* {{multiLine{To cancel only the default action by using the preventDefault method.
{{{
$("body").delegate("a", "click", function(event){
event.preventDefault();
});
}}}
}}}
* {{multiLine{Can bind custom events too.
{{{
$("body").delegate("p", "myCustomEvent", function(e, myName, myValue){
$(this).text("Hi there!");
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent");
});
}}}
}}}
Execute the next function on the queue for the matched elements.
|!Name|!Type|!Optional|!Description|h
|queueName|String|yes|A string containing the name of the queue. Defaults to fx, the standard effects queue.|
|Arguments|c
!Description
<html><p>When <code>.dequeue()</code> is called, the next function on the queue is removed from the queue, and then executed. This function should in turn (directly or indirectly) cause <code>.dequeue()</code> to be called, so that the sequence can continue.</p></html>
!Examples
* {{multiLine{Use dequeue to end a custom queue function which allows the queue to keep going.
{{{
$("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);
});
}}}
}}}
Selects all elements that are descendants of a given ancestor.
|!Name|!Type|!Optional|!Description|h
|ancestor|Selector|no|Any valid selector.|
|descendant|Selector|no|A selector to filter the descendant elements.|
|Arguments|c
!Description
<html><p>A descendant of an element could be a child, grandchild, great-grandchild, and so on, of that element.</p></html>
!Examples
* {{multiLine{Finds all input descendants of forms.
{{{
$("form input").css("border", "2px dotted blue");
}}}
}}}
Remove the set of matched elements from the DOM.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|yes|A selector expression that filters the set of matched elements to be removed.|
|Arguments|c
!Description
<html><p>The <code>.detach()</code> method is the same as <code><a href="/remove">.remove()</a></code>, except that <code>.detach()</code> keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.</p></html>
!Examples
* {{multiLine{Detach all paragraphs from the DOM
{{{
$("p").click(function(){
$(this).toggleClass("off");
});
var p;
$("button").click(function(){
if ( p ) {
p.appendTo("body");
p = null;
} else {
p = $("p").detach();
}
});
}}}
}}}
Remove an event handler previously attached using .live() from the elements.
|!Name|!Type|!Optional|!Description|h
|eventType|String|no|A string containing a JavaScript event type, such as click or keydown.|
|handler|String|yes|The function that is to be no longer executed.|
|Arguments|c
!Description
<html>
<p>Any handler that has been attached with <code>.live()</code> can be removed with <code>.die()</code>. This method is analogous to <code>.unbind()</code>, which is used to remove handlers attached with <code>.bind()</code>.
See the discussions of <code>.live()</code> and <code>.unbind()</code> for further details.</p>
</html>
!Examples
* {{multiLine{Can bind and unbind events to the colored button.
{{{
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...");
});
}}}
}}}
* {{multiLine{To unbind all live events from all paragraphs, write:
{{{
$("p").die()
}}}
}}}
* {{multiLine{To unbind all live click events from all paragraphs, write:
{{{
$("p").die( "click" )
}}}
}}}
* {{multiLine{To unbind just one previously bound handler, pass the function in as the second argument:
{{{
var foo = function () {
// code to handle some kind of event
};
$("p").live("click", foo); // ... now foo will be called when paragraphs are clicked ...
$("p").die("click", foo); // ... foo will no longer be called.
}}}
}}}
Selects all elements that are disabled.
!Description
<html><p>As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare <code>$(':disabled')</code> is equivalent to <code>$('*:disabled')</code>, so <code>$('input:disabled')</code> should be used instead. </p></html>
!Examples
* {{multiLine{Finds all input elements that are disabled.
{{{
$("input:disabled").val("this is it");
}}}
}}}
Iterate over a jQuery object, executing a function for each matched element.
|!Name|!Type|!Optional|!Description|h
|function(index, Element)|Function|no|A function to execute for each matched element.|
|Arguments|c
!Description
<html>
<p>The <code>.each()</code> method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword <code>this</code> refers to the element.</p>
<p>Suppose we had a simple unordered list on the page:</p>
<pre><ul>
<li>foo</li>
<li>bar</li>
</ul>
</pre>
<p>We can select the list items and iterate across them:</p>
<pre>$('li').each(function(index) {
alert(index + ': ' + $(this).text());
});
</pre>
<p>A message is thus alerted for each item in the list:</p>
<p><span class="output">0: foo</span><br/>
<span class="output">1: bar</span></p>
<p>We can stop the loop from within the callback function by returning <code>false</code>.</p>
</html>
!Examples
* {{multiLine{Iterates over three divs and sets their color property.
{{{
$(document.body).click(function () {
$("div").each(function (i) {
if (this.style.color != "blue") {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
});
}}}
}}}
* {{multiLine{If you want to have the jQuery object instead of the regular DOM element, use the $(this) function, for example:
{{{
$("span").click(function () {
$("li").each(function(){
$(this).toggleClass("example");
});
});
}}}
}}}
* {{multiLine{You can use 'return' to break out of each() loops early.
{{{
$("button").click(function () {
$("div").each(function (index, domEle) {
// domEle == this
$(domEle).css("backgroundColor", "yellow");
if ($(this).is("#stop")) {
$("span").text("Stopped at div index #" + index);
return false;
}
});
});
}}}
}}}
Selects all elements with the given tag name.
|!Name|!Type|!Optional|!Description|h
|element|String|no|An element to search for. Refers to the tagName of DOM nodes.|
|Arguments|c
!Description
<html><p>JavaScript's <code>getElementsByTagName()</code> function is called to return the appropriate elements when this expression is used.</p> </html>
!Examples
* {{multiLine{Finds every DIV element.
{{{
$("div").css("border","9px solid red");
}}}
}}}
Remove all child nodes of the set of matched elements from the DOM.
!Description
<html><p>This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element. Consider the following HTML:</p>
<pre><div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div></pre>
<p>We can target any element for removal:</p>
<pre>$('.hello').empty();</pre>
<p>This will result in a DOM structure with the <code>Hello</code> text deleted:</p>
<pre><div class="container">
<div class="hello"></div>
<div class="goodbye">Goodbye</div>
</div></pre>
<p>If we had any number of nested elements inside <code><div class="hello"></code>, they would be removed, too. </p>
<p>To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.</p>
</html>
!Examples
* {{multiLine{Removes all child nodes (including text nodes) from all paragraphs
{{{
$("button").click(function () {
$("p").empty();
});
}}}
}}}
Selects all elements that are enabled.
!Description
<html><p>As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare <code>$(':enabled')</code> is equivalent to <code>$('*:enabled')</code>, so <code>$('input:enabled')</code> should be used instead. </p></html>
!Examples
* {{multiLine{Finds all input elements that are enabled.
{{{
$("input:enabled").val("this is it");
}}}
}}}
End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
!Description
<html><p>Most of the methods in this chapter operate on a jQuery object and produce a new one, matching a different set of DOM elements. When this happens, it is as if the new set of elements is pushed onto a stack that is maintained inside the object. Each successive filtering method pushes a new element set onto the stack. If we need an older element set, we can use <code>end()</code> to pop the sets back off of the stack.</p>
<p>Suppose we have a couple short lists on a page:</p>
<pre>
<ul class="first">
<li class="foo">list item 1</li>
<li>list item 2</li>
<li class="bar">list item 3</li>
</ul>
<ul class="second">
<li class="foo">list item 1</li>
<li>list item 2</li>
<li class="bar">list item 3</li>
</ul>
</pre>
<p>The <code>end()</code> method is useful primarily when exploiting jQuery's chaining properties. When not using chaining, we can usually just call up a previous object by variable name, so we don't need to manipulate the stack. With <code>end()</code>, though, we can string all the method calls together:</p>
<pre>
$('ul.first').find('.foo').css('background-color', 'red')
<code>.end()</code>.find('.bar').css('background-color', 'green');
</pre>
<p>This chain searches for items with the class <code>foo</code> within the first list only and turns their backgrounds red. Then <code>end()</code> returns the object to its state before the call to <code>find()</code>, so the second <code>find()</code> looks for '.bar' inside <code><ul class="first"></code>, not just inside that list's <code><li class="foo"></code>, and turns the matching elements' backgrounds green. The net result is that items 1 and 3 of the first list have a colored background, and none of the items from the second list do.</p>
<p>A long jQuery chain can be visualized as a structured code block, with filtering methods providing the openings of nested blocks and <code>end()</code> methods closing them:</p>
<pre>
$('ul.first').find('.foo')
.css('background-color', 'red')
.end().find('.bar')
.css('background-color', 'green')
.end();
</pre>
<p>The last <code>end()</code> is unnecessary, as we are discarding the jQuery object immediately thereafter. However, when the code is written in this form, the <code>end()</code> provides visual symmetry and closure—making the program, at least to the eyes of some developers, more readable.</p></html>
!Examples
* {{multiLine{Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.
{{{
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");
}}}
}}}
* {{multiLine{Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.
{{{
$("p").find("span").end().css("border", "2px red solid");
}}}
}}}
Reduce the set of matched elements to the one at the specified index.
|!Name|!Type|!Optional|!Description|h
|index|Integer|no|An integer indicating the 0-based position of the element. |
|-index|Integer|no|An integer indicating the position of the element, counting backwards from the last element in the set. |
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.eq()</code> method constructs a new jQuery object from one of the matching elements. The supplied index identifies the position of this element in the set.</p>
<p>Consider a page with a simple list on it:</p>
<pre>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
</pre>
<p>We can apply this method to the set of list items:</p>
<pre>
$('li').eq(2).css('background-color', 'red');
</pre>
<p>The result of this call is a red background for item 3. Note that the supplied index is zero-based, and refers to the position of the element within the jQuery object, not within the DOM tree.</p>
<p>If a negative number is provided, this indicates a position starting from the end of the set, rather than the beginning. For example:</p>
<pre>
$('li').eq(-2).css('background-color', 'red');
</pre>
<p>This time list item 4 is turned red, since it is two from the end of the set.</p>
</html>
!Examples
* {{multiLine{Turn the div with index 2 blue by adding an appropriate class.
{{{
$("div").eq(2).addClass("blue");
}}}
}}}
Bind an event handler to the "error" JavaScript event.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute when the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('error', handler)</code>.</p>
<p>The <code>error</code> event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly.</p>
<p>For example, consider a page with a simple image:</p>
<pre><img src="missing.png" alt="Book" id="book" /></pre>
<p>The event handler can be bound to the image:</p>
<pre>$('#book').error(function() {
alert('Handler for .error() called.')
});
</pre>
<p>If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:</p>
<p><span class="output">Handler for .error() called.</span></p>
<blockquote><p>This event may not be correctly fired when the page is served locally. Since <code>error</code> relies on normal HTTP status codes, it will generally not be triggered if the URL uses the <code>file:</code> protocol.</p>
</blockquote>
<p>Note: jQuery's error event should not be attached to the window object. The browser fires the window's error event when a script error occurs. However, the window error event receives different arguments and has different return value requirements than conventional event handlers.
</p>
</html>
!Examples
* {{multiLine{To hide JavaScript errors from the user, you can try:
{{{
$(window).error(function(){
return true;
});
}}}
}}}
* {{multiLine{To hide the "broken image" icons for your IE users, you can try:
{{{
$("img").error(function(){
$(this).hide();
});
}}}
}}}
Selects even elements, zero-indexed. See also odd.
!Description
<html><p>In particular, note that the <em>0-based indexing</em> means that, counter-intuitively, <code>:even</code> selects the first element, third element, and so on within the matched set.</p></html>
!Examples
* {{multiLine{Finds even table rows, matching the first, third and so on (index 0, 2, 4 etc.).
{{{
$("tr:even").css("background-color", "#bbbbff");
}}}
}}}
The current DOM element within the event bubbling phase.
!Description
<html><p>This property will always be equal to the <code>this</code> of the function.</p> </html>
!Examples
* {{multiLine{Alert that currentTarget matches the `this` keyword.
{{{
$("p").click(function(event) {
alert( event.currentTarget === this ); // true
});
}}}
}}}
Contains the optional data passed to jQuery.fn.bind when the current executing handler was bound.
!Description
<html> </html>
!Examples
* {{multiLine{The description of the example.
{{{
$("a").each(function(i) {
$(this).bind('click', {index:i}, function(e){
alert('my index is ' + e.data.index);
});
});
}}}
}}}
Returns whether event.preventDefault() was ever called on this event object.
!Description
<html> </html>
!Examples
* {{multiLine{Checks whether event.preventDefault() was called.
{{{
$("a").click(function(event){
alert( event.isDefaultPrevented() ); // false
event.preventDefault();
alert( event.isDefaultPrevented() ); // true
});
}}}
}}}
Returns whether event.stopImmediatePropagation() was ever called on this event object.
!Description
<html> <p>This property was introduced in <a href="http://www.w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/events.html#Events-Event-isImmediatePropagationStopped">DOM level 3</a>.</p> </html>
!Examples
* {{multiLine{Checks whether event.stopImmediatePropagation() was called.
{{{
$("p").click(function(event){
alert( event.isImmediatePropagationStopped() );
event.stopImmediatePropagation();
alert( event.isImmediatePropagationStopped() );
});
}}}
}}}
Returns whether event.stopPropagation() was ever called on this event object.
!Description
<html> </html>
!Examples
* {{multiLine{Checks whether event.stopPropagation() was called
{{{
$("p").click(function(event){
alert( event.isPropagationStopped() );
event.stopPropagation();
alert( event.isPropagationStopped() );
});
}}}
}}}
The mouse position relative to the left edge of the document.
!Description
<html> </html>
!Examples
* {{multiLine{Show the mouse position relative to the left and top edges of the document (within the iframe).
{{{
$(document).bind('mousemove',function(e){
$("#log").text("e.pageX: " + e.pageX + ", e.pageY: " + e.pageY);
});
}}}
}}}
The mouse position relative to the top edge of the document.
!Description
<html> </html>
!Examples
* {{multiLine{Show the mouse position relative to the left and top edges of the document (within this iframe).
{{{
$(document).bind('mousemove',function(e){
$("#log").text("e.pageX: " + e.pageX + ", e.pageY: " + e.pageY);
});
}}}
}}}
If this method is called, the default action of the event will not be triggered.
!Description
<html> <p>For example, clicked anchors will not take the browser to a new URL. We can use <code>event.isDefaultPrevented()</code> to determine if this method has been called by an event handler that was triggered by this event.</p> </html>
!Examples
* {{multiLine{Cancel the default action (navigation) of the click.
{{{
$("a").click(function(event) {
event.preventDefault();
$('<div/>')
.append('default ' + event.type + ' prevented')
.appendTo('#log');
});
}}}
}}}
The other DOM element involved in the event, if any.
!Description
<html><p>For <code>mouseout</code>, indicates the element being entered; for <code>mousein</code>, indicates the element being exited. </p> </html>
!Examples
* {{multiLine{On mouseout of anchors, alert the element type being entered.
{{{
$("a").mouseout(function(event) {
alert(event.relatedTarget.nodeName); // "DIV"
});
}}}
}}}
This attribute contains the last value returned by an event handler that was triggered by this event, unless the value was undefined.
!Description
<html> It can be useful for getting previous return values of custom events. </html>
!Examples
* {{multiLine{Alert previous handler's return value
{{{
$("p").click(function(event) {
return "hey"
});
$("p").click(function(event) {
alert( event.result );
});
}}}
}}}
Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree
!Description
<html><p>In addition to keeping any additional handlers on an element from being executed, this method also stops the bubbling by implicitly calling <code>event.stopPropagation()</code>. To simply prevent the event from bubbling to ancestor elements but allow other event handlers to execute on the same element, we can use <code><a href="http://api.jquery.com/event.stopPropagation">event.stopPropagation()</a></code> instead.</p>
<p>Use <code><a href="http://api.jquery.com/event.isImmediatePropagationStopped">event.isImmediatePropagationStopped()</a></code> to know whether this method was ever called (on that event object).</p> </html>
!Examples
* {{multiLine{Prevents other event handlers from being called.
{{{
$("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");
});
}}}
}}}
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
!Description
<html> <p>We can use <code><a href="/event.isPropagationStopped">event.isPropagationStopped()</a></code> to determine if this method was ever called (on that event object). </p>
<p>This method works for custom events triggered with <a href="/trigger">trigger()</a>, as well.</p>
<p>Note that this will not prevent other handlers <em>on the same element</em> from running. </p> </html>
!Examples
* {{multiLine{Kill the bubbling on the click event.
{{{
$("p").click(function(event){
event.stopPropagation();
// do something
});
}}}
}}}
The DOM element that initiated the event.
!Description
<html> <p>This can be the element that registered for the event or a child of it. It is often useful to compare <code>event.target</code> to <code>this</code> in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.</p></html>
!Examples
* {{multiLine{Display the tag's name on click
{{{
$("body").click(function(event) {
$("#log").html("clicked: " + event.target.nodeName);
});
}}}
}}}
* {{multiLine{Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children.
{{{
function handler(event) {
var $target = $(event.target);
if( $target.is("li") ) {
$target.children().toggle();
}
}
$("ul").click(handler).find("ul").hide();
}}}
}}}
This attribute returns the number of milliseconds since January 1, 1970, when the event is triggered.
!Description
<html>It can be useful for profiling the performance of certain jQuery functions. </html>
!Examples
* {{multiLine{Display the time since the click handler last executed.
{{{
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;
});
}}}
}}}
Describes the nature of the event.
!Description
<html> </html>
!Examples
* {{multiLine{On all anchor clicks, alert the event type.
{{{
$("a").click(function(event) {
alert(event.type); // "click"
});
}}}
}}}
For key or button events, this attribute indicates the specific button or key that was pressed.
!Description
<html> <p><code>event.which</code> normalizes <code>event.keyCode</code> and <code>event.charCode</code>. It is recommended to watch <code>event.which</code> for keyboard key input. For more detail, read about <a href="https://developer.mozilla.org/en/DOM/event.charCode#Notes">event.charCode on the MDC</a>. </p> </html>
!Examples
* {{multiLine{Log what key was depressed.
{{{
$('#whichkey').bind('keydown',function(e){
$('#log').html(e.type + ': ' + e.which );
});
}}}
}}}
Display the matched elements by fading them to opaque.
|!Name|!Type|!Optional|!Description|h
|duration|String,Number|yes|A string or number determining how long the animation will run.|
|callback|Callback|yes|A function to call once the animation is complete.|
|Arguments|c
!Description
<html>
<p>The <code>.fadeIn()</code> method animates the opacity of the matched elements.</p>
<p>Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings <code>'fast'</code> and <code>'slow'</code> can be supplied to indicate durations of <code>200</code> and <code>600</code> milliseconds, respectively. If any other string is supplied, or if the <code>duration</code> parameter is omitted, the default duration of <code>400</code> milliseconds is used.</p>
<p>If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but <code>this</code> is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.</p>
<p>We can animate any element, such as a simple image:</p>
<pre><div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
With the element initially hidden, we can show it slowly:
$('#clickme').click(function() {
$('#book').fadeIn('slow', function() {
// Animation complete
});
});</pre>
<p class="image four-across">
<img src="/images/0042_06_33.png" alt=""/>
<img src="/images/0042_06_34.png" alt=""/>
<img src="/images/0042_06_35.png" alt=""/>
<img src="/images/0042_06_36.png" alt=""/>
</p>
</html>
!Examples
* {{multiLine{Animates hidden divs to fade in one by one, completing each animation within 600 milliseconds.
{{{
$(document.body).click(function () {
$("div:hidden:first").fadeIn("slow");
});
}}}
}}}
* {{multiLine{Fades a red block in over the text. Once the animation is done, it quickly fades in more text on top.
{{{
$("a").click(function () {
$("div").fadeIn(3000, function () {
$("span").fadeIn(100);
});
return false;
});
}}}
}}}
Hide the matched elements by fading them to transparent.
|!Name|!Type|!Optional|!Description|h
|duration|String,Number|yes|A string or number determining how long the animation will run.|
|callback|Callback|yes|A function to call once the animation is complete.|
|Arguments|c
!Description
<html>
<p>The <code>.fadeOut()</code> method animates the opacity of the matched elements. Once the opacity reaches 0, the <code>display</code> style property is set to <code>none</code>, so the element no longer affects the layout of the page.</p>
<p>Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings <code>'fast'</code> and <code>'slow'</code> can be supplied to indicate durations of <code>200</code> and <code>600</code> milliseconds, respectively. If any other string is supplied, or if the <code>duration</code> parameter is omitted, the default duration of <code>400</code> milliseconds is used.</p>
<p>If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but <code>this</code> is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.</p>
<p>We can animate any element, such as a simple image:</p>
<pre><div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" /></pre>
<p>With the element initially shown, we can hide it slowly:</p>
<pre>$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});</pre>
<p class="image four-across">
<img src="/images/0042_06_37.png" alt=""/>
<img src="/images/0042_06_38.png" alt=""/>
<img src="/images/0042_06_39.png" alt=""/>
<img src="/images/0042_06_40.png" alt=""/>
</p>
</html>
!Examples
* {{multiLine{Animates all paragraphs to fade out, completing the animation within 600 milliseconds.
{{{
$("p").click(function () {
$("p").fadeOut("slow");
});
}}}
}}}
* {{multiLine{Fades out spans in one section that you click on.
{{{
$("span").click(function () {
$(this).fadeOut(1000, function () {
$("div").text("'" + $(this).text() + "' has faded!");
$(this).remove();
});
});
$("span").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});
}}}
}}}
Adjust the opacity of the matched elements.
|!Name|!Type|!Optional|!Description|h
|duration|String,Number|no|A string or number determining how long the animation will run.|
|opacity|Number|no|A number between 0 and 1 denoting the target opacity.|
|callback|Callback|yes|A function to call once the animation is complete.|
|Arguments|c
!Description
<html>
<p>The <code>.fadeTo()</code> method animates the opacity of the matched elements.</p>
<p>Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings <code>'fast'</code> and <code>'slow'</code> can be supplied to indicate durations of <code>200</code> and <code>600</code> milliseconds, respectively. If any other string is supplied, the default duration of <code>400</code> milliseconds is used. Unlike the other effect methods, <code>.fadeTo()</code> requires that <code>duration</code> be explicitly specified.</p>
<p>If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but <code>this</code> is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.</p>
<p>We can animate any element, such as a simple image:</p>
<pre><div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
With the element initially shown, we can dim it slowly:
$('#clickme').click(function() {
$('#book').fadeTo('slow', 0.5, function() {
// Animation complete.
});
});
</pre>
<p class="image four-across">
<img src="/images/0042_06_41.png" alt=""/>
<img src="/images/0042_06_42.png" alt=""/>
<img src="/images/0042_06_43.png" alt=""/>
<img src="/images/0042_06_44.png" alt=""/>
</p>
<p>With <code>duration</code> set to <code>0</code>, this method just changes the <code>opacity</code> CSS property, so <code>.fadeTo(0, opacity)</code> is the same as <code>.css('opacity', opacity)</code>.</p>
</html>
!Examples
* {{multiLine{Animates first paragraph to fade to an opacity of 0.33 (33%, about one third visible), completing the animation within 600 milliseconds.
{{{
$("p:first").click(function () {
$(this).fadeTo("slow", 0.33);
});
}}}
}}}
* {{multiLine{Fade div to a random opacity on each click, completing the animation within 200 milliseconds.
{{{
$("div").click(function () {
$(this).fadeTo("fast", Math.random());
});
}}}
}}}
* {{multiLine{Find the right answer! The fade will take 250 milliseconds and change various styles when it completes.
{{{
var getPos = function (n) {
return (Math.floor(n) * 90) + "px";
};
$("p").each(function (n) {
var r = Math.floor(Math.random() * 3);
var tmp = $(this).text();
$(this).text($("p:eq(" + r + ")").text());
$("p:eq(" + r + ")").text(tmp);
$(this).css("left", getPos(n));
});
$("div").each(function (n) {
$(this).css("left", getPos(n));
})
.css("cursor", "pointer")
.click(function () {
$(this).fadeTo(250, 0.25, function () {
$(this).css("cursor", "")
.prev().css({"font-weight": "bolder",
"font-style": "italic"});
});
});
}}}
}}}
Selects all elements of type file.
!Description
<html><p>As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare <code>$(':file')</code> is equivalent to <code>$('*:file')</code>, so <code>$('input:file')</code> should be used instead. </p></html>
!Examples
* {{multiLine{Finds all file inputs.
{{{
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
}}}
}}}
Reduce the set of matched elements to those that match the selector or pass the function's test.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|no|A string containing a selector expression to match elements against.|
|function(index)|Function|no|A function used as a test for each element in the set. this is the current DOM element.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.filter()</code> method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; all elements matching the selector will be included in the result.</p>
<p>Consider a page with a simple list on it:</p>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
<p>We can apply this method to the set of list items:</p>
<pre>
$('li').filter(':even').css('background-color', 'red');
</pre>
<p>The result of this call is a red background for items 1, 3, and 5, as they match the selector (recall that <code>:even</code> and <code>:odd</code> use 0-based indexing).</p>
<h4 id="using-filter-function">Using a Filter Function</h4>
<p>The second form of this method allows us to filter elements against a function rather than a selector. For each element, if the function returns <code>true</code>, the element will be included in the filtered set; otherwise, it will be excluded. Suppose we have a somewhat more involved HTML snippet:</p>
<pre>
<ul>
<li><strong>list</strong> item 1 -
one strong tag</li>
<li><strong>list</strong> item <strong>2</strong> -
two <span>strong tags</span></li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
</pre>
<p>We can select the list items, then filter them based on their contents:</p>
<pre>
$('li').filter(function(index) {
return $('strong', this).length == 1;
}).css('background-color', 'red');
</pre>
<p>This code will alter the first list item only, as it contains exactly one <code><strong></code> tag. Within the filter function, <code>this</code> refers to each DOM element in turn. The parameter passed to the function tells us the index of that DOM element within the set matched by the jQuery object.</p>
<p>We can also take advantage of the <code>index</code> passed through the function, which indicates the 0-based position of the element within the unfiltered set of matched elements:</p>
<pre>
$('li').filter(function(index) {
return index % 3 == 2;
}).css('background-color', 'red');
</pre>
<p>This alteration to the code will cause the third and sixth list items to be highlighted, as it uses the modulus operator (<code>%</code>) to select every item with an <code>index</code> value that, when divided by 3, has a remainder of <code>2</code>.</p>
</html>
!Examples
* {{multiLine{Change the color of all divs then put a border around only some of them.
{{{
$("div").css("background", "#c8ebcc")
.filter(".middle")
.css("border-color", "red");
}}}
}}}
* {{multiLine{Selects all paragraphs and removes those without a class "selected".
{{{
$("p").filter(".selected")
}}}
}}}
* {{multiLine{Selects all paragraphs and removes those that aren't of class "selected" or the first one.
{{{
$("p").filter(".selected, :first")
}}}
}}}
* {{multiLine{Change the color of all divs then put a border to specific ones.
{{{
$("div").css("background", "#b4b0da")
.filter(function (index) {
return index == 1 || $(this).attr("id") == "fourth";
})
.css("border", "3px double red");
}}}
}}}
* {{multiLine{Remove all elements that have a descendant ol element
{{{
$("div").filter(function(index) {
return $("ol", this).length == 0;
});
}}}
}}}
Get the descendants of each element in the current set of matched elements, filtered by a selector.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|no|A string containing a selector expression to match elements against.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.find()</code> method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The <code>.find()</code> and <code>.children()</code> methods are similar, except that the latter only travels a single level down the DOM tree.</p>
<p>The method accepts a selector expression of the same type that we can pass to the <code>$()</code> function. The elements will be filtered by testing whether they match this selector.</p>
<p>Consider a page with a basic nested list on it:</p>
<pre>
<ul class="level-1">
<li class="item-i">I</li>
<li class="item-ii">II
<ul class="level-2">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>
</pre>
<p>If we begin at item II, we can find list items within it:</p>
<pre>$('li.item-ii').find('li').css('background-color', 'red');</pre>
<p>The result of this call is a red background on items A, B, 1, 2, 3, and C. Even though item II matches the selector expression, it is not included in the results; only descendants are considered candidates for the match.</p>
<blockquote><p>Unlike in the rest of the tree traversal methods, the selector expression is required in a call to <code>.find()</code>. If we need to retrieve all of the descendant elements, we can pass in the universal selector <code>'*'</code> to accomplish this.</p></blockquote>
<p><a href="http://api.jquery.com/jquery/#selector-context">Selector context</a> is implemented with the <code>.find()</code> <code>method;</code> therefore, <code>$('li.item-ii').find('li')</code> is equivalent to <code>$('li', 'li.item-ii')</code>.</p>
</html>
!Examples
* {{multiLine{Starts with all paragraphs and searches for descendant span elements, same as $("p span")
{{{
$("p").find("span").css('color','red');
}}}
}}}
* {{multiLine{Add spans around each word then add a hover and italicize words with the letter t.
{{{
var newText = $("p").text().split(" ").join("</span> <span>");
newText = "<span>" + newText + "</span>";
$("p").html(newText)
.find('span')
.hover(function() {
$(this).addClass("hilite");
},
function() { $(this).removeClass("hilite");
})
.end()
.find(":contains('t')")
.css({"font-style":"italic", "font-weight":"bolder"});
}}}
}}}
Reduce the set of matched elements to the first in the set.
!Description
<html>[<p>Given a jQuery object that represents a set of DOM elements, the <code>.first()</code> method constructs a new jQuery object from the first matching element.</p>
<p>Consider a page with a simple list on it:</p>
<pre>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
</pre>
<p>We can apply this method to the set of list items:</p>
<pre>$('li').first().css('background-color', 'red');</pre>
<p>The result of this call is a red background for the first item.</p></html>
!Examples
* {{multiLine{Highlight the first span in a paragraph.
{{{
$("p span").first().addClass('highlight');
}}}
}}}
Selects all elements that are the first child of their parent.
!Description
<html><p>While <a href="/first-selector">:first</a> matches only a single element, the <code>:first-child</code> selector can match more than one: one for each parent. This is equivalent to <code>:nth-child(1)</code>.</p></html>
!Examples
* {{multiLine{Finds the first span in each matched div to underline and add a hover state.
{{{
$("div span:first-child")
.css("text-decoration", "underline")
.hover(function () {
$(this).addClass("sogreen");
}, function () {
$(this).removeClass("sogreen");
});
}}}
}}}
Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<ul>
<li>This method is a shortcut for <code>.bind('focus', handler)</code> in the first variation, and <code>.trigger('focus')</code> in the second.</li>
<li>The <code>focus</code> event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<code><input></code>, <code><select></code>, etc.) and links (<code><a href></code>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's <code>tabindex</code> property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.</li>
<li>Elements with focus are usually highlighted in some way by the browser, for example with a dotted line surrounding the element. The focus is used to determine which element is the first to receive keyboard-related events.</li>
</ul>
<p>For example, consider the HTML:</p>
<pre><form>
<input id="target" type="text" value="Field 1" />
<input type="text" value="Field 2" />
</form>
<div id="other">
Trigger the handler
</div>
</pre>
<p>The event handler can be bound to the first input field:</p>
<pre>$('#target').focus(function() {
alert('Handler for .focus() called.');
});</pre>
<p>Now if we click on the first field, or tab to it from another field, the alert is displayed:</p>
<p><span class="output">Handler for .focus() called.</span></p>
<p>We can trigger the event when another element is clicked:</p>
<pre>$('#other').click(function() {
$('#target').focus();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also alert the message.</p>
<p>The <code>focus</code> event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the <code>focus</code> event will not work consistently across browsers.</p>
<blockquote><p>Triggering the focus on hidden elements causes an error in Internet Explorer. Take care to only call <code>.focus()</code> without parameters on elements that are visible.</p></blockquote>
</html>
!Examples
* {{multiLine{Fire focus.
{{{
$("input").focus(function () {
$(this).next("span").css('display','inline').fadeOut(1000);
});
}}}
}}}
* {{multiLine{To stop people from writing in text input boxes, try:
{{{
$("input[type=text]").focus(function(){
$(this).blur();
});
}}}
}}}
* {{multiLine{To focus on a login input box with id 'login' on page startup, try:
{{{
$(document).ready(function(){
$("#login").focus();
});
}}}
}}}
Bind an event handler to the "focusin" JavaScript event.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html><p>This method is a shortcut for <code>.bind('focusin', handler)</code>.</p>
<p>The <code>focusin</code> event is sent to an element when it, or any element inside of it, gains focus. This is distinct from the <a href="/focus">focus</a> event in that it supports detecting the focus event on parent elements.</p>
<p>This event will likely be used together with the <a href="/focusout">focusout</a> event.</p></html>
!Examples
* {{multiLine{Watch for a focus to occur within the paragraphs on the page.
{{{
$("p").focusin(function() {
$(this).find("span").css('display','inline').fadeOut(1000);
});
}}}
}}}
Bind an event handler to the "focusout" JavaScript event.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html><p>This method is a shortcut for <code>.bind('focusout', handler)</code>.</p>
<p>The <code>focusout</code> event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the <a href="/blur">blur</a> event in that it supports detecting the loss of focus from parent elements (in other words, it supports events bubbling).</p>
<p>This event will likely be used together with the <a href="/focusin">focusin</a> event.</p></html>
!Examples
* {{multiLine{Watch for a loss of focus to occur within the paragraphs on the page.
{{{
$("p").focusout(function() {
$(this).find("span").css('display','inline').fadeOut(1000);
});
}}}
}}}
Retrieve the DOM elements matched by the jQuery object.
|!Name|!Type|!Optional|!Description|h
|index|Number|yes|A zero-based integer indicating which element to retrieve.|
|Arguments|c
!Description
<html><p>The <code>.get()</code> method grants us access to the DOM nodes underlying each jQuery object. Suppose we had a simple unordered list on the page:</p>
<pre>
<ul>
<li id="foo">foo</li>
<li id="bar">bar</li>
</ul>
</pre>
<p>Without a parameter, <code>.get()</code> returns all of the elements:</p>
<pre>alert($('li').get());</pre>
<p>All of the matched DOM nodes are returned by this call, contained in a standard array:</p>
<p><span class="result">[<li id="foo">, <li id="bar">]</span></p>
<p>With an index specified, .get() will retrieve a single element:</p>
<pre>($('li').get(0));</pre>
<p>Since the index is zero-based, the first list item is returned:</p>
<p><span class="output"><li id="foo"></span></p>
<p>Each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get at the list item instead:</p>
<pre>alert($('li')[0]);</pre>
<p>However, this syntax lacks some of the additional capabilities of .get(), such as specifying a negative index:</p>
<pre>alert($('li').get(-1));</pre>
<p>A negative index is counted from the end of the matched set, so this example will return the last item in the list:</p>
<p><span class="output"><li id="bar"></span></p></html>
!Examples
* {{multiLine{Selects all divs in the document and returns the DOM Elements as an Array, then uses the built-in reverse-method to reverse that 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").get().reverse() );
}}}
}}}
* {{multiLine{Gives the tag name of the element clicked on.
{{{
$("*", document.body).click(function (e) {
e.stopPropagation();
var domEl = $(this).get(0);
$("span:first").text("Clicked on - " + domEl.tagName);
});
}}}
}}}
Select all elements at an index greater than index within the matched set.
!Description
<html><p><strong>index-related selectors</strong></p>
<p>The index-related selector expressions (including this "greater than" selector) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set. For example, if elements are first selected with a class selector (<code>.myclass</code>) and four elements are returned, these elements are given indices 0 through 3 for the purposes of these selectors.</p>
<p>Note that since JavaScript arrays use <em>0-based indexing</em>, these selectors reflect that fact. This is why <code>$('.myclass:gt(1)')</code> selects elements after the second element in the document with the class <code>myclass</code>, rather than after the first. In contrast, <code>:nth-child(n)</code> uses <em>1-based indexing</em> to conform to the CSS specification.</p>
</html>
!Examples
* {{multiLine{Finds TD #5 and higher. Reminder: the indexing starts at 0.
{{{
$("td:gt(4)").css("text-decoration", "line-through");
}}}
}}}
Selects elements which contain at least one element that matches the specified selector.
!Description
<html><p>The expression <code>$('div:has(p)')</code> matches a <code><div></code> if a <code><p></code> exists anywhere among its descendants, not just as a direct child.</p> </html>
!Examples
* {{multiLine{Adds the class "test" to all divs that have a paragraph inside of them.
{{{
$("div:has(p)").addClass("test");
}}}
}}}
Determine whether any of the matched elements are assigned the given class.
|!Name|!Type|!Optional|!Description|h
|className|String|no|The class name to search for.|
|Arguments|c
!Description
<html><p>Elements may have more than one class assigned to them. In HTML, this is represented by separating the class names with a space:</p>
<pre><div id="mydiv" class="foo bar"></div></pre>
<p>The <code>.hasClass()</code> method will return <code>true</code> if the class is assigned to an element, even if other classes also are. For example, given the HTML above, the following will return <code>true</code>:</p>
<pre>$('#mydiv').hasClass('foo')</pre>
<p>as would:</p>
<pre>$('#mydiv').hasClass('bar')</pre></html>
!Examples
* {{multiLine{Looks for the class 'selected' on the matched elements.
{{{
$("div#result1").append($("p:first").hasClass("selected").toString());
$("div#result2").append($("p:last").hasClass("selected").toString());
$("div#result3").append($("p").hasClass("selected").toString());
}}}
}}}
Selects all elements that are headers, like h1, h2, h3 and so on.
!Description
N/A
!Examples
* {{multiLine{Adds a background and text color to all the headers on the page.
{{{
$(":header").css({ background:'#CCC', color:'blue' });
}}}
}}}
Set the CSS height of every matched element.
|!Name|!Type|!Optional|!Description|h
|value|String, Number|no|An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string).|
|function(index, height)|Function|no|A function returning the height to set. Receives the index position of the element in the set and the old height as arguments.|
|Arguments|c
!Description
<html><p>When calling <code>.height(value)</code>, the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit. If a string is provided, however, any valid CSS measurement may be used for the height (such as <code>100px</code>, <code>50%</code>, or <code>auto</code>). Note that in modern browsers, the CSS height property does not include padding, border, or margin.</p>
<p>If no explicit unit was specified (like 'em' or '%') then "px" is concatenated to the value.</p></html>
!Examples
* {{multiLine{To set the height of each div on click to 30px plus a color change.
{{{
$("div").one('click', function () {
$(this).height(30)
.css({cursor:"auto", backgroundColor:"green"});
});
}}}
}}}
Selects all elements that are hidden.
!Description
<html>
<p>Elements can be considered hidden for several reasons:</p>
<ul>
<li>They have a display value of none.</li>
<li>They are form elements with type="hidden".</li>
<li>Their width and height are explicitly set to 0.</li>
<li>An ancestor element is hidden, so the element is not shown on the page.</li>
</ul>
<p>How <code>:hidden</code> is determined was changed in jQuery 1.3.2. An element is assumed to be hidden if it or any of its parents consumes no space in the document. CSS visibility isn't taken into account (therefore <code>$(elem).css('visibility','hidden').is(':hidden') == false</code>). The <a href="http://docs.jquery.com/Release:jQuery_1.3.2#:visible.2F:hidden_Overhauled">release notes</a> outline the changes in more detail.</p></html>
!Examples
* {{multiLine{Shows all hidden divs and counts hidden inputs.
{{{
// 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 the matched elements.
|!Name|!Type|!Optional|!Description|h
|duration|String,Number|no|A string or number determining how long the animation will run.|
|callback|Callback|yes|A function to call once the animation is complete.|
|Arguments|c
!Description
<html>
<p>With no parameters, the <code>.hide()</code> method is the simplest way to hide an element:</p>
<pre>$('.target').hide();
</pre>
<p>The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling <code>.css('display', 'none')</code>, except that the value of the <code>display</code> property is saved in jQuery's data cache so that <code>display</code> can later be restored to its initial value. If an element has a <code>display</code> value of <code>inline</code>, then is hidden and shown, it will once again be displayed <code>inline</code>.</p>
<p>When a duration is provided, <code>.hide()</code> becomes an animation method. The <code>.hide()</code> method animates the width, height, and opacity of the matched elements simultaneously. When these properties reach 0, the <code>display</code> style property is set to <code>none</code> to ensure that the element no longer affects the layout of the page.</p>
<p>Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings <code>'fast'</code> and <code>'slow'</code> can be supplied to indicate durations of <code>200</code> and <code>600</code> milliseconds, respectively.</p>
<p>If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but <code>this</code> is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.</p>
<p>We can animate any element, such as a simple image:</p>
<pre><div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
With the element initially shown, we can hide it slowly:
$('#clickme').click(function() {
$('#book').hide('slow', function() {
$.print('Animation complete.');
});
});</pre>
<p class="image four-across">
<img src="/images/0042_06_05.png" alt=""/>
<img src="/images/0042_06_06.png" alt=""/>
<img src="/images/0042_06_07.png" alt=""/>
<img src="/images/0042_06_08.png" alt=""/>
</p>
</html>
!Examples
* {{multiLine{Hides all paragraphs then the link on click.
{{{
$("p").hide();
$("a").click(function () {
$(this).hide();
return true;
});
}}}
}}}
* {{multiLine{Animates all shown paragraphs to hide slowly, completing the animation within 600 milliseconds.
{{{
$("button").click(function () {
$("p").hide("slow");
});
}}}
}}}
* {{multiLine{Animates all spans (words in this case) to hide fastly, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one.
{{{
$("#hidr").click(function () {
$("span:last-child").hide("fast", function () {
// use callee so don't have to name the function
$(this).prev().hide("fast", arguments.callee);
});
});
$("#showr").click(function () {
$("span").show(2000);
});
}}}
}}}
* {{multiLine{Hides the divs when clicked over 2 seconds, then removes the div element when its hidden. Try clicking on more than one box at a time.
{{{
for (var i = 0; i < 5; i++) {
$("<div>").appendTo(document.body);
}
$("div").click(function () {
$(this).hide(2000, function () {
$(this).remove();
});
});
}}}
}}}
Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.
|!Name|!Type|!Optional|!Description|h
|handlerInOut(eventObject)|Function|no|A function to execute when the mouse pointer enters or leaves the element.|
|Arguments|c
!Description
<html>
<p>The <code>.hover()</code> method, when passed a single function, will execute that handler for both <code>mouseenter</code> and <code>mouseleave</code> events. This allows the user to use jQuery's various toggle methods within the handler.</p>
<p>Calling <code>$(selector).hover(handlerInOut)</code> is shorthand for:</p>
<pre>$(selector).bind("mouseenter mouseleave",handlerInOut);</pre>
<p>See the discussions for <code><a href="/mouseenter">.mouseenter()</a></code> and <code><a href="/mouseleave">.mouseleave()</a></code> for more details.</p>
</html>
!Examples
* {{multiLine{Slide the next sibling LI up or down on hover, and toggle a class.
{{{
$("li")
.filter(":odd")
.hide()
.end()
.filter(":even")
.hover(
function () {
$(this).toggleClass("active")
.next().stop(true, true).slideToggle();
}
);
}}}
}}}
Set the HTML contents of each element in the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|htmlString|String|no|A string of HTML to set as the content of each matched element.|
|function(index, html)|Function|no|A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments.|
|Arguments|c
!Description
<html>
<p>The <code>.html()</code> method is not available in XML documents. </p>
<p>When we use <code>.html()</code> to set elements' contents, any contents that were in those elements is completely replaced by the new contents. Consider the following HTML:</p>
<pre><div class="demo-container">
<div class="demo-box">Demonstration Box</div>
</div></pre>
<p>We can set the HTML contents of <code><div class="demo-container"></code> like so:</p>
<pre>$('div.demo-container')
.html('<p>All new content. <em>You bet!</em></p>');</pre>
<p>That line of code will replace everything inside <code><div class="demo-container"></code>:</p>
<pre><div class="demo-container">
<p>All new content. <em>You bet!</em></p>
</div></pre>
<p>As of jQuery 1.4, the <code>.html()</code> method allows us to set the HTML content by passing in a function.</p>
<pre>$('div.demo-container').html(function() {
var emph = '<em>' + $('p').length + ' paragraphs!</em>';
return '<p>All new content for ' + emph + '</p>';
});</pre>
<p>Given a document with six paragraphs, this example will set the HTML of <code><div class="demo-container"></code> to <code><p>All new content for <em>6 paragraphs!</em></p></code>.</p>
</html>
!Examples
* {{multiLine{Add some html to each div.
{{{
$("div").html("<span class='red'>Hello <b>Again</b></span>");
}}}
}}}
* {{multiLine{Add some html to each div then immediately do further manipulations to the inserted html.
{{{
$("div").html("<b>Wow!</b> Such excitement...");
$("div b").append(document.createTextNode("!!!"))
.css("color", "red");
}}}
}}}
Selects a single element with the given id attribute.
|!Name|!Type|!Optional|!Description|h
|id|String|no|An ID to search for, specified via the id attribute of an element.|
|Arguments|c
!Description
<html>
<p>For id selectors, jQuery uses the JavaScript function <code>document.getElementById()</code>, which is extremely efficient. When another selector is attached to the id selector, such as <code>h2#pageTitle</code>, jQuery performs an additional check before identifying the element as a match.</p>
<blockquote><p>As always, remember that as a developer, your time is typically the most valuable resource. Do not focus on optimization of selector speed unless it is clear that performance needs to be improved.</p></blockquote>
<p>Each <code>id</code> value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.</p>
<p>If the id contains characters like periods or colons you have to <a href="http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_select_an_element_by_an_ID_that_has_characters_used_in_CSS_notation.3F">escape those characters with backslashes</a>.</p>
</html>
!Examples
* {{multiLine{Finds the element with the id "myDiv".
{{{
$("#myDiv").css("border","3px solid red");
}}}
}}}
* {{multiLine{Finds the element with the id "myID.entry[1]". See how certain characters must be escaped with backslashes.
{{{
$("#myID\\.entry\\[1\\]").css("border","3px solid red");
}}}
}}}
Selects all elements of type image.
!Description
N/A
!Examples
* {{multiLine{Finds all image inputs.
{{{
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
}}}
}}}
Search for a given element from among the matched elements.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|no|A selector representing a jQuery collection in which to look for an element.|
|element|Element, jQuery|no|The DOM element or first element within the jQuery object to look for.|
|Arguments|c
!Description
<html><h4>Return Values</h4>
<p>If no argument is passed to the <code>.index()</code> method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.</p>
<p>If <code>.index()</code> is called on a collection of elements and a DOM element or jQuery object is passed in, <code>.index()</code> returns an integer indicating the position of the passed element relative to the original collection.</p>
<p>If a selector string is passed as an argument, <code>.index()</code> returns an integer indicating the position of the original element relative to the elements matched by the selector. If the element is not found, <code>.index()</code> will return -1.</p>
<h4>Detail</h4>
<p>The complementary operation to <code>.get()</code>, which accepts an index and returns a DOM node, <code>.index()</code> can take a DOM node and returns an index. Suppose we have a simple unordered list on the page:</p>
<pre>
<ul>
<li id="foo">foo</li>
<li id="bar">bar</li>
<li id="baz">baz</li>
</ul>
</pre>
<p>If we retrieve one of the three list items (for example, through a DOM function or as the context to an event handler), <code>.index()</code> can search for this list item within the set of matched elements:</p>
<pre>
var listItem = document.getElementById('bar');
alert('Index: ' + $('li').index(listItem));
We get back the zero-based position of the list item:
</pre>
<p><span class="output">Index: 1</span></p>
<p>Similarly, if we retrieve a jQuery object consisting of one of the three list items, <code>.index()</code> will search for that list item:</p>
<pre>
var listItem = $('#bar');
alert('Index: ' + $('li').index(listItem));
</pre>
<p>We get back the zero-based position of the list item:</p>
<p><span class="output">Index: 1</span></p>
<p>Note that if the jQuery collection used as the <code>.index()</code> method's argument contains more than one element, the first element within the matched set of elements will be used.</p>
<pre>
var listItems = $('li:gt(0)');
alert('Index: ' + $('li').index(listItems));
</pre>
<p>We get back the zero-based position of the first list item within the matched set:</p>
<p><span class="output">Index: 1</span></p>
<p>If we use a string as the <code>.index()</code> method's argument, it is interpreted as a jQuery selector string. The first element among the object's matched elements which also matches this selector is located.</p>
<pre>
var listItem = $('#bar');
alert('Index: ' + listItem.index('li'));
</pre>
<p>We get back the zero-based position of the list item:</p>
<p><span class="output">Index: 1</span></p>
<p>If we omit the argument, <code>.index()</code> will return the position of the first element within the set of matched elements in relation to its siblings:</p>
<pre>alert('Index: ' + $('#bar').index();</pre>
<p>Again, we get back the zero-based position of the list item:</p>
<p><span class="output">Index: 1</span></p>
</html>
!Examples
* {{multiLine{On click, returns the index (based zero) of that div in the page.
{{{
$("div").click(function () {
// this is the dom element clicked
var index = $("div").index(this);
$("span").text("That was div index #" + index);
});
}}}
}}}
* {{multiLine{Returns the index for the element with ID bar.
{{{
var listItem = $('#bar');
$('div').html( 'Index: ' + $('li').index(listItem) );
}}}
}}}
* {{multiLine{Returns the index for the first item in the jQuery collection.
{{{
var listItems = $('li:gt(0)');
$('div').html( 'Index: ' + $('li').index(listItems) );
}}}
}}}
* {{multiLine{Returns the index for the element with ID bar in relation to all <li> elements.
{{{
$('div').html('Index: ' + $('#bar').index('li') );
}}}
}}}
* {{multiLine{Returns the index for the element with ID bar in relation to its siblings.
{{{
var barIndex = $('#bar').index();
$('div').html( 'Index: ' + barIndex );
}}}
}}}
* {{multiLine{Returns -1, as there is no element with ID foobar.
{{{
var foobar = $("li").index( $('#foobar') );
$('div').html('Index: ' + foobar);
}}}
}}}
Get the current computed height for the first element in the set of matched elements, including padding but not border.
!Description
<html><p>This method returns the height of the element, including top and bottom padding, in pixels.</p>
<p>This method is not applicable to <code>window</code> and <code>document</code> objects; for these, use <code><a href="/height">.height()</a></code> instead.</p>
<p class="image"><img src="/images/0042_04_02.png"/></p></html>
!Examples
* {{multiLine{Get the innerHeight of a paragraph.
{{{
var p = $("p:first");
$("p:last").text( "innerHeight:" + p.innerHeight() );
}}}
}}}
Get the current computed width for the first element in the set of matched elements, including padding but not border.
!Description
<html><p>This method returns the width of the element, including left and right padding, in pixels.</p>
<p>This method is not applicable to <code>window</code> and <code>document</code> objects; for these, use <code><a href="/width">.width()</a></code> instead.</p>
<p class="image"><img src="/images/0042_04_05.png"/></p></html>
!Examples
* {{multiLine{Get the innerWidth of a paragraph.
{{{
var p = $("p:first");
$("p:last").text( "innerWidth:" + p.innerWidth() );
}}}
}}}
Selects all input, textarea, select and button elements.
!Description
<html><p>The <code>:input</code> selector basically selects all form controls.</p></html>
!Examples
* {{multiLine{Finds all input 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; });
}}}
}}}
Insert every element in the set of matched elements after the target.
|!Name|!Type|!Optional|!Description|h
|target|Selector, Element, jQuery|no|A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter.|
|Arguments|c
!Description
<html><p>The <code><a href="/after">.after()</a></code> and <code>.insertAfter()</code> methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With<code> .after()</code>, the selector expression preceding the method is the container after which the content is inserted. With <code>.insertAfter()</code>, on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.</p>
<p>Consider the following HTML:</p>
<pre><div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>We can create content and insert it after several elements at once:</p>
<pre>$('<p>Test</p>').insertAfter('.inner');</pre>
<p>Each inner <code><div></code> element gets this new content:</p>
<pre><div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">Goodbye</div>
<p>Test</p>
</div></pre>
<p>We can also select an element on the page and insert it after another:</p>
<pre>$('h2').insertAfter($('.container'));</pre>
<p>If an element selected this way is inserted elsewhere, it will be moved after the target (not cloned):</p>
<pre><div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<h2>Greetings</h2></pre>
<p>If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.</p></html>
!Examples
* {{multiLine{Inserts all paragraphs after an element with id of "foo". Same as $("#foo").after("p")
{{{
$("p").insertAfter("#foo"); // check after() examples
}}}
}}}
Insert every element in the set of matched elements before the target.
|!Name|!Type|!Optional|!Description|h
|target|Selector, Element, jQuery|no|A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter.|
|Arguments|c
!Description
<html><p>The <code><a href="/before">.before()</a></code> and <code>.insertBefore()</code> methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With<code> .before()</code>, the selector expression preceding the method is the container before which the content is inserted. With <code>.insertBefore()</code>, on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted before the target container.</p>
<p>Consider the following HTML:</p>
<pre><div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>We can create content and insert it before several elements at once:</p>
<pre>$('<p>Test</p>').insertBefore('.inner');</pre>
<p>Each inner <code><div></code> element gets this new content:</p>
<pre><div class="container">
<h2>Greetings</h2>
<p>Test</p>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">Goodbye</div>
</div></pre>
<p>We can also select an element on the page and insert it before another:</p>
<pre>$('h2').insertBefore($('.container'));</pre>
<p>If an element selected this way is inserted elsewhere, it will be moved before the target (not cloned):</p>
<pre><h2>Greetings</h2>
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.</p></html>
!Examples
* {{multiLine{Inserts all paragraphs before an element with id of "foo". Same as $("#foo").before("p")
{{{
$("p").insertBefore("#foo"); // check before() examples
}}}
}}}
Check the current matched set of elements against a selector and return true if at least one of these elements matches the selector.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|no|A string containing a selector expression to match elements against.|
|Arguments|c
!Description
<html><p>Unlike the other filtering and traversal methods, <code>.is()</code> does not create a new jQuery object. Instead, it allows us to test the contents of a jQuery object without modification. This is often useful inside callbacks, such as event handlers.</p>
<p>Suppose we have a list, with two of its items containing a child element:</p>
<pre>
<ul>
<li>list <strong>item 1</strong></li>
<li><span>list item 2</span></li>
<li>list item 3</li>
</ul>
</pre>
<p>We can attach a click handler to the <ul> element, and then limit the code to be triggered only when a list item itself, not one of its children, is clicked:</p>
<pre>$('ul').click(function(event) {
if ($(event.target).is('li') ) {
$(event.target).css('background-color', 'red');
}
});</pre>
<p>Now, when the user clicks on the word list in the first item or anywhere in the third item, the clicked list item will be given a red background. However, when the user clicks on item 1 in the first item or anywhere in the second item, nothing will occur, because in those cases the target of the event would be <code><strong></code> or <code><span></code>, respectively.
</p></html>
!Examples
* {{multiLine{Shows a few ways is() can be used inside an event handler.
{{{
$("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"});
});
}}}
}}}
* {{multiLine{Returns true, because the parent of the input is a form element
{{{
var isFormParent = $("input[type='checkbox']").parent().is("form")
$("div").text("isFormParent = " + isFormParent);
}}}
}}}
* {{multiLine{Returns false, because the parent of the input is a p element
{{{
var isFormParent = $("input[type='checkbox']").parent().is("form")
$("div").text("isFormParent = " + isFormParent);
}}}
}}}
Binds a function to be executed when the DOM has finished loading.
|!Name|!Type|!Optional|!Description|h
|callback|Function|no|The function to execute when the DOM is ready.|
|Arguments|c
!Description
<html>
<p>This function behaves just like <code>$(document).ready()</code>, in that it should be used to wrap other <code>$()</code> operations on your page that depend on the DOM being ready. While this function is, technically, chainable, there really isn't much use for chaining against it.</p>
</html>
!Examples
* {{multiLine{Executes the function when the DOM is ready to be used.
{{{
$(function(){
// Document is ready
});
}}}
}}}
* {{multiLine{Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.
{{{
jQuery(function($) {
// Your code using failsafe $ alias here...
});
}}}
}}}
Perform an asynchronous HTTP (Ajax) request.
|!Name|!Type|!Optional|!Description|h
|settings|Map|no|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().|
|Arguments|c
!Description
<html><p>The <code>$.ajax()</code> function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like <code><a href="/jQuery.get">$.get()</a></code> and <code><a href="/load">.load()</a></code> are available and are easier to use. If less common options are required, though, <code>$.ajax()</code> can be used more flexibly.</p>
<p>At its simplest, the <code>$.ajax()</code> function can be called with no arguments:</p>
<pre>$.ajax();</pre>
<p><strong>Note:</strong> Default settings can be set globally by using the <code><a href="/jQuery.ajaxSetup">$.ajaxSetup()</a></code> function.</p>
<p>This example, using no options, loads the contents of the current page, but does nothing with the result. To use the result, we can implement one of the callback functions.</p>
<h4 id="callback-functions">Callback Functions</h4>
<p>The <code>beforeSend</code>, <code>error</code>, <code>dataFilter</code>, <code>success</code> and <code>complete</code> options all take callback functions that are invoked at the appropriate times:</p>
<ol>
<li><code>beforeSend</code> is called before the request is sent, and is passed the <code>XMLHttpRequest</code> object as a parameter.</li>
<li><code>error</code> is called if the request fails. It is passed the <code>XMLHttpRequest</code> object, a string indicating the error type, and an exception object if applicable.</li>
<li><code>dataFilter</code> is called on success. It is passed the returned data and the value of <code>dataType</code>, and must return the (possibly altered) data to pass on to <code>success</code>.</li>
<li><code>success</code> is called if the request succeeds. It is passed the returned data, a string containing the success code, and the <code>XMLHttpRequest</code> object.</li>
<li><code>complete</code> is called when the request finishes, whether in failure or success. It is passed the <code>XMLHttpRequest</code> object, as well as a string containing the success or error code.</li>
</ol>
<p>To make use of the returned HTML, we can implement a <code>success</code> handler:</p>
<pre>$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});</pre>
<p>Such a simple example would generally be better served by using <code><a href="/load">.load()</a></code> or <code><a href="/jQuery.get">$.get()</a></code>.</p>
<h4 id="data-types">Data Types</h4>
<p>The <code>$.ajax()</code> function relies on the server to provide information about the retrieved data. If the server reports the return data as XML, the result can be traversed using normal XML methods or jQuery's selectors. If another type is detected, such as HTML in the example above, the data is treated as text.</p>
<p>Different data handling can be achieved by using the <code>dataType</code> option. Besides plain <code>xml</code>, the <code>dataType</code> can be <code>html</code>, <code>json</code>, <code>jsonp</code>, <code>script</code>, or <code>text</code>.</p>
<p>The <code>text</code> and <code>xml</code> types return the data with no processing. The data is simply passed on to the success handler, either through the <code>responseText</code> or <code>responseXML</code> property of the <code>XMLHttpRequest</code> object, respectively.</p>
<p><strong>Note:</strong> We must ensure that the MIME type reported by the web server matches our choice of <code>dataType</code>. In particular, XML must be declared by the server as <code>text/xml</code> or <code>application/xml</code> for consistent results.</p>
<p>If <code>html</code> is specified, any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string. Similarly, <code>script</code> will execute the JavaScript that is pulled back from the server, then return the script itself as textual data.</p>
<p>The <code>json</code> type parses the fetched data file as a JavaScript object and returns the constructed object as the result data. To do so, it uses <code>JSON.parse()</code> when the browser supports it; otherwise it uses a <code>Function</code> <strong>constructor</strong>. Malformed JSON data will throw a parse error (see <a href="http://json.org/">json.org</a> for more information). JSON data is convenient for communicating structured data in a way that is concise and easy for JavaScript to parse. If the fetched data file exists on a remote server, specify the <code>jsonp</code> type instead.</p>
<p>The <code>jsonp</code> type appends a query string parameter of <code>callback=?</code> to the URL. The server should prepend the JSON data with the callback name to form a valid JSONP response. We can specify a parameter name other than <code>callback</code> with the <code>jsonp</code> option to <code>$.ajax()</code>.</p>
<p><strong>Note:</strong> JSONP is an extension of the JSON format, requiring some server-side code to detect and handle the query string parameter. More information about it can be found in the <a href="http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/">original post detailing its use</a>.</p>
<p>When data is retrieved from remote servers (which is only possible using the <code>script</code> or <code>jsonp</code> data types), the operation is performed using a <code><script></code> tag rather than an <code>XMLHttpRequest</code> object. In this case, no <code>XMLHttpRequest</code> object is returned from <code>$.ajax()</code>, nor is one passed to the handler functions such as <code>beforeSend</code>.</p>
<h4 id="sending-data-to-server">Sending Data to the Server</h4>
<p>By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the <code>type</code> option. This option affects how the contents of the <code>data</code> option are sent to the server.</p>
<p>The <code>data</code> option can contain either a query string of the form <code>key1=value1&key2=value2</code>, or a map of the form <code>{key1: 'value1', key2: 'value2'}</code>. If the latter form is used, the data is converted into a query string before it is sent. This processing can be circumvented by setting <code>processData</code> to <code>false</code>. The processing might be undesirable if we wish to send an XML object to the server; in this case, we would also want to change the <code>contentType</code> option from <code>application/x-www-form-urlencoded</code> to a more appropriate MIME type.</p>
<h4 id="advanced-options">Advanced Options</h4>
<p>The <code>global</code> option prevents handlers registered using <code><a href="/ajaxSend">.ajaxSend()</a></code>, <code><a href="/ajaxError">.ajaxError()</a></code>, and similar methods from firing when this request would trigger them. This can be useful to, for example, suppress a loading indicator that was implemented with <code><a href="/jQuery.ajaxSend">.ajaxSend()</a></code> if the requests are frequent and brief. See the descriptions of these methods below for more details.</p>
<p>If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the <code>username</code> and <code>password</code> options.</p>
<p>Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using <code><a href="/jQuery.ajaxSetup">$.ajaxSetup()</a></code> rather than being overridden for specific requests with the <code>timeout</code> option.</p>
<p>By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set <code>cache</code> to <code>false</code>. To cause the request to report failure if the asset has not been modified since the last request, set <code>ifModified</code> to <code>true</code>.</p>
<p>The <code>scriptCharset</code> allows the character set to be explicitly specified for requests that use a <code><script></code> tag (that is, a type of <code>script</code> or <code>jsonp</code>). This is useful if the script and host page have differing character sets.</p>
<p>The first letter in Ajax stands for "asynchronous," meaning that the operation occurs in parallel and the order of completion is not guaranteed. The <code>async</code> option to <code>$.ajax()</code> defaults to <code>true</code>, indicating that code execution can continue after the request is made. Setting this option to <code>false</code> (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.</p>
<p>The <code>$.ajax()</code> function returns the <code>XMLHttpRequest</code> object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the <code>xhr</code> option. The returned object can generally be discarded, but does provide a lower-level interface for observing and manipulating the request. In particular, calling <code>.abort()</code> on the object will halt the request before it completes.</p></html>
!Examples
* {{multiLine{Load and execute a JavaScript file.
{{{
$.ajax({
type: "GET",
url: "test.js",
dataType: "script"
});
}}}
}}}
* {{multiLine{Save some data to the server and notify the user once it's complete.
{{{
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}}}
}}}
* {{multiLine{Retrieve the latest version of an HTML page.
{{{
$.ajax({
url: "test.html",
cache: false,
success: function(html){
$("#results").append(html);
}
});
}}}
}}}
* {{multiLine{Loads data synchronously. Blocks the browser while the requests is active.
It is better to block user interaction by other means when synchronization is
necessary.
{{{
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
}}}
}}}
* {{multiLine{Sends an xml document as data to the server. By setting the processData
option to false, the automatic conversion of data to strings is prevented.
{{{
var xmlDocument = [create xml document];
$.ajax({
url: "page.php",
processData: false,
data: xmlDocument,
success: handleResponse
});
}}}
}}}
* {{multiLine{Sends an id as data to the server, save some data to the server and notify the user once it's complete.
{{{
bodyContent = $.ajax({
url: "script.php",
global: false,
type: "POST",
data: ({id : this.getAttribute('id')}),
dataType: "html",
success: function(msg){
alert(msg);
}
}
).responseText;
}}}
}}}
Set default values for future Ajax requests.
|!Name|!Type|!Optional|!Description|h
|options|Options|no|A set of key/value pairs that configure the default Ajax request. All options are optional. |
|Arguments|c
!Description
<html><p>For details on the settings available for <code>$.ajaxSetup()</code>, see <code><a href="/jQuery.ajax">$.ajax()</a></code>. </p>
<p>All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of <code>$.ajaxSetup()</code>.</p>
<p>For example, we could set a default for the URL parameter before pinging the server repeatedly:</p>
<pre>$.ajaxSetup({
url: 'ping.php',
});</pre>
<p>Now each time an Ajax request is made, this URL will be used automatically:</p>
<pre>
$.ajax({
data: {'name': 'Tim'},
});</pre>
<blockquote><p>Note: Global callback functions should be set with their respective global Ajax event handler methods-<code><a href="/ajaxStart">.ajaxStart()</a></code>, <code><a href="/ajaxStop">.ajaxStop()</a></code>, <code><a href="/ajaxComplete">.ajaxComplete()</a></code>, <code><a href="/ajaxError">.ajaxError()</a></code>, <code><a href="/ajaxSuccess">.ajaxSuccess()</a></code>, <code><a href="/ajaxSend">.ajaxSend()</a></code>-rather than within the <code>settings</code> object for <code>$.ajaxSetup()</code>.</p></blockquote></html>
!Examples
* {{multiLine{Sets the defaults for Ajax requests to the url "/xmlhttp/", disables global handlers and uses POST instead of GET. The following Ajax requests then sends some data without having to set anything else.
{{{
$.ajaxSetup({
url: "/xmlhttp/",
global: false,
type: "POST"
});
$.ajax({ data: myData });
}}}
}}}
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.
!Description
N/A
!Examples
* {{multiLine{Returns the box model for the iframe.
{{{
$("p").html("The box model for this iframe is: <span>" +
jQuery.boxModel + "</span>");
}}}
}}}
* {{multiLine{Returns false if the page is in Quirks Mode in Internet Explorer
{{{
$.boxModel
}}}
}}}
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.
!Description
<html>
<p>The <code>$.browser</code> property allows us to detect which web browser is accessing the page, as reported by the browser itself. It contains flags for each of the four most prevalent browser classes (Internet Explorer, Mozilla, Webkit, and Opera) as well as version information.</p>
<p>Available flags are:</p>
<ul>
<li>webkit (as of jQuery 1.4)</li>
<li>safari (deprecated)</li>
<li>opera</li>
<li>msie</li>
<li>mozilla</li>
</ul>
<p>This property is available immediately. It is therefore safe to use it to determine whether or not to call <code>$(document).ready()</code>.
The <code>$.browser</code> property is deprecated in jQuery 1.3, but there are no immediate plans to remove it.</p>
<p>Because <code>$.browser</code> uses <code>navigator.userAgent</code> to determine the platform, it is vulnerable to spoofing by the user or misrepresentation by the browser itself. It is always best to avoid browser-specific code entirely where possible. The <code>$.support</code> property is available for detection of support for particular features rather than relying on <code>$.browser</code>.</p></html>
!Examples
* {{multiLine{Show the browser info.
{{{
jQuery.each(jQuery.browser, function(i, val) {
$("<div>" + i + " : <span>" + val + "</span>")
.appendTo(document.body);
});
}}}
}}}
* {{multiLine{Returns true if the current useragent is some version of Microsoft's Internet Explorer.
{{{
$.browser.msie
}}}
}}}
* {{multiLine{Alerts "this is webkit!" only for webkit browsers
{{{
if ($.browser.webkit) {
alert("this is webkit!");
}
}}}
}}}
* {{multiLine{Alerts "Do stuff for firefox 3" only for firefox 3 browsers.
{{{
jQuery.each(jQuery.browser, function(i, val) {
if(i=="mozilla" && jQuery.browser.version.substr(0,3)=="1.9")
alert("Do stuff for firefox 3")
});
}}}
}}}
* {{multiLine{Set a CSS property to specific browser.
{{{
jQuery.each(jQuery.browser, function(i) {
if($.browser.msie){
$("#div ul li").css("display","inline");
}else{
$("#div ul li").css("display","inline-table");
}
});
}}}
}}}
The version number of the rendering engine for the user's browser.
!Description
<html>
<p>Here are some typical results:</p>
<ul>
<li>Internet Explorer: 6.0, 7.0</li>
<li>Mozilla/Firefox/Flock/Camino: 1.7.12, 1.8.1.3, 1.9</li>
<li>Opera: 9.20</li>
<li>Safari/Webkit: 312.8, 418.9</li>
</ul>
<p>Note that IE8 claims to be 7 in Compatibility View.</p>
</html>
!Examples
* {{multiLine{Returns the browser version.
{{{
$("p").html("The browser version is: <span>" +
jQuery.browser.version + "</span>");
}}}
}}}
* {{multiLine{Alerts the version of IE that is being used
{{{
if ( $.browser.msie ) {
alert( $.browser.version );
}
}}}
}}}
* {{multiLine{Often you only care about the "major number," the whole number. This can be accomplished with JavaScript's built-in parseInt() function:
{{{
if (jQuery.browser.msie) {
alert(parseInt(jQuery.browser.version));
}
}}}
}}}
Check to see if a DOM node is within another DOM node.
|!Name|!Type|!Optional|!Description|h
|container|Element|no|The DOM element that may contain the other element.|
|contained|Element|no|The DOM node that may be contained by the other element.|
|Arguments|c
!Description
N/A
!Examples
* {{multiLine{Check if an element is inside another.
{{{
jQuery.contains(document.documentElement, document.body); // true
jQuery.contains(document.body, document.documentElement); // false
}}}
}}}
Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element.
|!Name|!Type|!Optional|!Description|h
|element|Element|no|The DOM element to query for the data.|
|key|String|no|Name of the data stored.|
|element|Element|no|The DOM element to query for the data.|
|Arguments|c
!Description
<html><p><strong>Note:</strong> This is a low-level method; you should probably use <code><a href="/data">.data()</a></code> instead.</p>
<p>The <code>jQuery.data()</code> method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can retrieve several distinct values for a single element one at a time, or as a set:</p>
<pre>alert(jQuery.data( document.body, 'foo' ));
alert(jQuery.data( document.body ));</pre>
<p>The above lines alert the data values that were set on the <code>body</code> element. If nothing was set on that element, an empty string is returned.</p>
<p>Calling <code>jQuery.data(element)</code> retrieves all of the element's associated values as a JavaScript object. Note that jQuery itself uses this method to store data for internal use, such as event handlers, so do not assume that it contains only data that your own code has stored.</p>
</html>
!Examples
* {{multiLine{Get the data named "blah" stored at for an element.
{{{
$("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);
});
}}}
}}}
Execute the next function on the queue for the matched element.
|!Name|!Type|!Optional|!Description|h
|element|Element|no|A DOM element from which to remove and execute a queued function.|
|queueName|String|yes|A string containing the name of the queue. Defaults to fx, the standard effects queue.|
|Arguments|c
!Description
<html><p><strong>Note:</strong> This is a low-level method, you should probably use <code><a href="/dequeue">.dequeue()</a></code> instead.</p>
<p>When <code>jQuery.dequeue()</code> is called, the next function on the queue is removed from the queue, and then executed. This function should in turn (directly or indirectly) cause <code>jQuery.dequeue()</code> to be called, so that the sequence can continue.</p></html>
!Examples
* {{multiLine{Use dequeue to end a custom queue function which allows the queue to keep going.
{{{
$("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);
});
}}}
}}}
A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
|!Name|!Type|!Optional|!Description|h
|collection|Object|no|The object or array to iterate over.|
|callback(indexInArray, valueOfElement)|Function|no|The function that will be executed on every object.|
|Arguments|c
!Description
<html>
<p>The <code>$.each()</code> function is not the same as <a href="/each/">.each()</a>, which is used to iterate, exclusively, over a jQuery object. The <code>$.each()</code> function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the <code>this</code> keyword.)</p>
<pre>$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
</pre>
<p>This produces two messages:</p>
<p>
<span class="output">0: 52</span><br/>
<span class="output">1: 97</span>
</p>
<p>If a map is used as the collection, the callback is passed a key-value pair each time:</p>
<pre>var map = {
'flammable': 'inflammable',
'duh': 'no duh'
};
$.each(map, function(key, value) {
alert(key + ': ' + value);
});</pre>
<p>Once again, this produces two messages:</p>
<p>
<span class="output">flammable: inflammable</span><br/>
<span class="output">duh: no duh</span>
</p>
<p>We can break the <code>$.each()</code> loop at a particular iteration by making the callback function return <code>false</code>. Returning <em>non-false</em> is the same as a <code>continue</code> statement in a for loop; it will skip immediately to the next iteration.</p></html>
!Examples
* {{multiLine{Iterates through the array displaying each number as both a word and numeral
{{{
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));
});
}}}
}}}
* {{multiLine{Iterates over items in an array, accessing both the current item and its index.
{{{
$.each( ['a','b','c'], function(i, l){
alert( "Index #" + i + ": " + l );
});
}}}
}}}
* {{multiLine{Iterates over the properties in an object, accessing both the current item and its key.
{{{
$.each( { name: "John", lang: "JS" }, function(k, v){
alert( "Key: " + k + ", Value: " + v );
});
}}}
}}}
Takes a string and throws an exception containing it.
|!Name|!Type|!Optional|!Description|h
|message|String|no|The message to send out.|
|Arguments|c
!Description
<html><p>This method exists primarily for plugin developers who wish to override it and provide a better display (or more information) for the error messages.</p></html>
!Examples
* {{multiLine{Override jQuery.error for display in Firebug.
{{{
jQuery.error = console.error;
}}}
}}}
Merge the contents of two or more objects together into the first object.
|!Name|!Type|!Optional|!Description|h
|target|Object|no| 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.|
|object1|Object|yes|An object containing additional properties to merge in.|
|objectN|Object|yes|Additional objects containing properties to merge in.|
|deep|Boolean|yes|If true, the merge becomes recursive (aka. deep copy).|
|target|Object|no|The object to extend. It will receive the new properties.|
|object1|Object|no|An object containing additional properties to merge in.|
|objectN|Object|yes|Additional objects containing properties to merge in.|
|Arguments|c
!Description
<html><p>When we supply two or more objects to <code>$.extend()</code>, properties from all of the objects are added to the target object.</p>
<p>If only one argument is supplied to <code>$.extend()</code>, this means the target argument was omitted. In this case, the jQuery object itself is assumed to be the target. By doing this, we can add new functions to the jQuery namespace. This can be useful for plugin authors wishing to add new methods to JQuery.</p>
<p>Keep in mind that the target object (first argument) will be modified, and will also be returned from <code>$.extend()</code>. If, however, we want to preserve both of the original objects, we can do so by passing an empty object as the target:</p>
<pre>var object = $.extend({}, object1, object2);</pre>
<p>The merge performed by <code>$.extend()</code> is not recursive by default; if a property of the first object is itself an object or array, it will be completely overwritten by a property with the same key in the second object. The values are not merged. This can be seen in the example below by examining the value of banana. However, by passing <code>true</code> for the first function argument, objects will be recursively merged.</p>
<p>Undefined properties are not copied. However, properties inherited from the object's prototype <em>will</em> be copied over.</p>
</html>
!Examples
* {{multiLine{Merge two objects, modifying the first.
{{{
var object1 = {
apple: 0,
banana: {weight: 52, price: 100},
cherry: 97
};
var object2 = {
banana: {price: 200},
durian: 100
};
$.extend(object1, object2);
}}}
}}}
* {{multiLine{Merge two objects recursively, modifying the first.
{{{
var object1 = {
apple: 0,
banana: {weight: 52, price: 100},
cherry: 97
};
var object2 = {
banana: {price: 200},
durian: 100
};
$.extend(true, object1, object2);
}}}
}}}
* {{multiLine{Merge settings and options, modifying settings.
{{{
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);
}}}
}}}
* {{multiLine{Merge defaults and options, without modifying the defaults. This is a common plugin development pattern.
{{{
var empty = {}
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = $.extend(empty, defaults, options);
}}}
}}}
Globally disable all animations.
!Description
<html>
<p>When this property is set to <code>true</code>, all animation methods will immediately set elements to their final state when called, rather than displaying an effect. This may be desirable for a couple reasons:</p>
<ul>
<li>jQuery is being used on a low-resource device.</li>
<li>Users are encountering accessibility problems with the animations (see the article <a href="http://www.jdeegan.phlegethon.org/turn_off_animation.html">Turn Off Animation</a> for more information).</li>
</ul>
<p>Animations can be turned back on by setting the property to <code>false</code>.</p>
</html>
!Examples
* {{multiLine{Toggle animation on and off
{{{
var toggleFx = function() {
$.fx.off = !$.fx.off;
};
toggleFx();
$("button").click(toggleFx)
$("input").click(function(){
$("div").toggle("slow");
});
}}}
}}}
Load data from the server using a HTTP GET request.
|!Name|!Type|!Optional|!Description|h
|url|String|no|A string containing the URL to which the request is sent.|
|data|Map, String|yes|A map or string that is sent to the server with the request.|
|callback(data, textStatus, XMLHttpRequest)|Function|yes|A callback function that is executed if the request succeeds.|
|dataType|String|yes|The type of data expected from the server.|
|Arguments|c
!Description
<html><p>This is a shorthand Ajax function, which is equivalent to:</p>
<pre>$.ajax({
url: <em>url</em>,
data: <em>data</em>,
success: <em>success</em>,
dataType: <em>dataType</em>
});
</pre>
<p>The <code>success</code> callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response. </p>
<p>As of jQuery 1.4, the <code>success</code> callback function is also passed the XMLHttpRequest object.</p>
<p>Most implementations will specify a success handler:</p>
<pre>$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
</pre>
<p>This example fetches the requested HTML snippet and inserts it on the page.</p></html>
!Examples
* {{multiLine{Request the test.php page, but ignore the return results.
{{{
$.get("test.php");
}}}
}}}
* {{multiLine{Request the test.php page and send some additional data along (while still ignoring the return results).
{{{
$.get("test.php", { name: "John", time: "2pm" } );
}}}
}}}
* {{multiLine{pass arrays of data to the server (while still ignoring the return results).
{{{
$.get("test.php", { 'choices[]': ["Jon", "Susan"]} );
}}}
}}}
* {{multiLine{Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
{{{
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
}}}
}}}
* {{multiLine{Alert out the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned).
{{{
$.get("test.cgi", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
}}}
}}}
Load JSON-encoded data from the server using a GET HTTP request.
|!Name|!Type|!Optional|!Description|h
|url|String|no|A string containing the URL to which the request is sent.|
|data|Map|yes|A map or string that is sent to the server with the request.|
|callback(data, textStatus)|Function|yes|A callback function that is executed if the request succeeds.|
|Arguments|c
!Description
<html>
<p>This is a shorthand Ajax function, which is equivalent to:</p>
<pre>$.ajax({
url: <em>url</em>,
dataType: 'json',
data: <em>data</em>,
success: <em>callback</em>
});
</pre>
<p>The callback is passed the returned data, which will be a JavaScript object or array as defined by the JSON structure and parsed using the <code><a href="/jQuery.parseJSON">$.parseJSON()</a></code> method.</p>
<p>Most implementations will specify a success handler:</p>
<pre>$.getJSON('ajax/test.json', function(data) {
$('.result').html('<p>' + data.foo + '</p>'
+ '<p>' + data.baz[1] + '</p>');
});
</pre>
<p>This example, of course, relies on the structure of the JSON file:</p>
<pre>{
"foo": "The quick brown fox jumps over the lazy dog.",
"bar": "ABCDEFG",
"baz": [52, 97]
}
</pre>
<p>Using this structure, the example inserts the first string and second number from the file onto the page.</p>
<blockquote>
<p><strong>Important:</strong> As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see <a href="http://json.org/">http://json.org/</a>.</p>
</blockquote>
<h4 id="jsonp">JSONP</h4>
<p>If the URL includes the string "callback=?" in the URL, the request is treated as JSONP instead. See the discussion of the <code>jsonp</code> data type in <code><a href="/jQuery.ajax">$.ajax()</a></code> for more details.</p></html>
!Examples
* {{multiLine{Loads the four most recent cat pictures from the Flickr JSONP API.
{{{
$.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;
});
});
}}}
}}}
* {{multiLine{Load the JSON data from test.js and access a name from the returned JSON data.
{{{
$.getJSON("test.js", function(json){
alert("JSON Data: " + json.users[3].name);
});
}}}
}}}
* {{multiLine{Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data.
{{{
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json){
alert("JSON Data: " + json.users[3].name);
});
}}}
}}}
* {{multiLine{List the result of a consultation of pages.php in HTML as an array. By Manuel Gonzalez.
{{{
var id=$("#id").attr("value");
$.getJSON("pages.php",{id:id},dates);
function dates(datos) {
$("#list").html("Name:"+datos[1].name+"<br>"+"Last Name:"+datos[1].lastname+"<br>"+"Address:"+datos[1].address);
}
}}}
}}}
Load a JavaScript file from the server using a GET HTTP request, then execute it.
|!Name|!Type|!Optional|!Description|h
|url|String|no|A string containing the URL to which the request is sent.|
|success(data, textStatus)|Function|yes|A callback function that is executed if the request succeeds.|
|Arguments|c
!Description
<html><p>This is a shorthand Ajax function, which is equivalent to:</p>
<pre>$.ajax({
url: <em>url</em>,
dataType: 'script',
success: <em>success</em>
});
</pre>
<p>The callback is passed the returned JavaScript file. This is generally not useful as the script will already have run at this point.</p>
<p>The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts should have some impact on the current page:</p>
<pre>$('.result').html('<p>Lorem ipsum dolor sit amet.</p>');</pre>
<p>The script can then be included and run by referencing the file name:</p>
<pre>$.getScript('ajax/test.js', function() {
alert('Load was performed.');
});</pre></html>
!Examples
* {{multiLine{We load the new official jQuery Color Animation plugin dynamically and bind some color animations to occur once the new functionality is loaded.
{{{
$.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);
});
});
}}}
}}}
* {{multiLine{Load the test.js JavaScript file and execute it.
{{{
$.getScript("test.js");
}}}
}}}
* {{multiLine{Load the test.js JavaScript file and execute it, displaying an alert message when the execution is complete.
{{{
$.getScript("test.js", function(){
alert("Script loaded and executed.");
});
}}}
}}}
Execute some JavaScript code globally.
|!Name|!Type|!Optional|!Description|h
|code|String|no|The JavaScript code to execute.|
|Arguments|c
!Description
<html><p>This method behaves differently from using a normal JavaScript <code>eval()</code> in that it's executed within the global context (which is important for loading external scripts dynamically).</p></html>
!Examples
* {{multiLine{Execute a script in the global context.
{{{
function test(){
jQuery.globalEval("var newVar = true;")
}
test();
// newVar === true
}}}
}}}
Finds the elements of an array which satisfy a filter function. The original array is not affected.
|!Name|!Type|!Optional|!Description|h
|array|Array|no|The array to search through.|
|function(elementOfArray, indexInArray)|Function|no|The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object.|
|invert|Boolean|yes|If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false.|
|Arguments|c
!Description
<html><p>The <code>$.grep()</code> method removes items from an array as necessary so that all remaining items pass a provided test. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.</p>
<p> The filter function will be passed two arguments: the current array item and its index. The filter function must return 'true' to include the item in the result array.</p>
</html>
!Examples
* {{multiLine{Filters the original array of numbers leaving that are not 5 and have an index greater than 4. Then it removes all 9s.
{{{
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(", "));
}}}
}}}
* {{multiLine{Filter an array of numbers to include only numbers bigger then zero.
{{{
$.grep( [0,1,2], function(n,i){
return n > 0;
});
}}}
}}}
* {{multiLine{Filter an array of numbers to include numbers that are not bigger than zero.
{{{
$.grep( [0,1,2], function(n,i){
return n > 0;
},true);
}}}
}}}
Search for a specified value within an array and return its index (or -1 if not found).
|!Name|!Type|!Optional|!Description|h
|value|Any|no|The value to search for.|
|array|Array|no|An array through which to search.|
|Arguments|c
!Description
<html><p>The <code>$.inArray()</code> method is similar to JavaScript's native <code>.indexOf()</code> method in that it returns -1 when it doesn't find a match. If the first element within the array matches <code>value</code>, <code>$.inArray()</code> returns 0.</p>
<p>Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of <code>value</code> within <code>array</code>, we need to check if it's not equal to (or greater than) -1.</p>
</html>
!Examples
* {{multiLine{Report the index of some elements in the array.
{{{
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));
}}}
}}}
Determine whether the argument is an array.
|!Name|!Type|!Optional|!Description|h
|obj|Object|no|Object to test whether or not it is an array.|
|Arguments|c
!Description
<html><p><code>$.isArray()</code> returns a Boolean indicating whether the object is a JavaScript array (not an array-like object, such as a jQuery object).</p></html>
!Examples
* {{multiLine{Finds out if the parameter is an array.
{{{
$("b").append( "" + $.isArray([]) );
}}}
}}}
Check to see if an object is empty (contains no properties).
|!Name|!Type|!Optional|!Description|h
|object|Object|no|The object that will be checked to see if it's empty.|
|Arguments|c
!Description
<html><p>As of jQuery 1.4 this method checks both properties on the object itself and properties inherited from prototypes (in that it doesn't use hasOwnProperty).</p></html>
!Examples
* {{multiLine{Check an object to see if it's empty.
{{{
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false
}}}
}}}
Determine if the argument passed is a Javascript function object.
|!Name|!Type|!Optional|!Description|h
|obj|Object|no|Object to test whether or not it is a function.|
|Arguments|c
!Description
<html><p><strong>Note:</strong> As of jQuery 1.3, functions provided by the browser like <code>alert()</code> and DOM element methods like <code>getAttribute()</code> are not guaranteed to be detected as functions in browsers such as Internet Explorer.</p></html>
!Examples
* {{multiLine{Test a few parameter examples.
{{{
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);
});
}}}
}}}
* {{multiLine{Finds out if the parameter is a funcion.
{{{
$.isFunction(function(){});
}}}
}}}
Check to see if an object is a plain object (created using "{}" or "new Object").
|!Name|!Type|!Optional|!Description|h
|object|Object|no|The object that will be checked to see if it's a plain object.|
|Arguments|c
!Description
N/A
!Examples
* {{multiLine{Check an object to see if it's a plain object.
{{{
jQuery.isPlainObject({}) // true
jQuery.isPlainObject("test") // false
}}}
}}}
Check to see if a DOM node is within an XML document (or is an XML document).
|!Name|!Type|!Optional|!Description|h
|node|Element|no|The DOM node that will be checked to see if it's in an XML document.|
|Arguments|c
!Description
N/A
!Examples
* {{multiLine{Check an object to see if it's in an XML document.
{{{
jQuery.isXMLDoc(document) // false
jQuery.isXMLDoc(document.body) // false
}}}
}}}
Convert an array-like object into a true JavaScript array.
|!Name|!Type|!Optional|!Description|h
|obj|Object|no|Any object to turn into a native Array.|
|Arguments|c
!Description
<html>
<p>Many methods, both in jQuery and in JavaScript in general, return objects that are array-like. For example, the jQuery factory function <code>$()</code> returns a jQuery object that has many of the properties of an array (a length, the <code>[]</code> array access operator, etc.), but is not exactly the same as an array and lacks some of an array's built-in methods (such as <code>.pop()</code> and <code>.reverse()</code>).</p>
<p>Note that after the conversion, any special features the object had (such as the jQuery methods in our example) will no longer be present. The object is now a plain array.</p></html>
!Examples
* {{multiLine{Turn a collection of HTMLElements into an Array of them.
{{{
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);
}}}
}}}
* {{multiLine{Turn a jQuery object into an array
{{{
var obj = $('li');
var arr = $.makeArray(obj);
}}}
}}}
Translate all items in an array or array-like object to another array of items.
|!Name|!Type|!Optional|!Description|h
|array|Array|no|The Array to translate.|
|callback(elementOfArray, indexInArray)|Function|no|The function to process each item against. The first argument to the function is the list item, the second argument is the index in array The function can return any value. this will be the global window object. |
|Arguments|c
!Description
<html><p>The $.map() method applies a function to each item in an array, collecting the results into a new array.</p>
<p>The translation function that is provided to this method is called for each item in the array and is passed two arguments: The item to be translated, and the index within the array.</p>
<p>The function can return:</p>
<ul>
<li>the translated value, which will be mapped to the resulting array</li>
<li><code>null</code>, to remove the item</li>
<li>an array of values, which will be flattened into the full array</li>
</ul>
<p>Map can iterate through Array-like objects, like a jQuery object, that have a length property.</p></html>
!Examples
* {{multiLine{A couple examples of using .map()
{{{
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(", "));
}}}
}}}
* {{multiLine{Maps the original array to a new one and adds 4 to each value.
{{{
$.map( [0,1,2], function(n){
return n + 4;
});
}}}
}}}
* {{multiLine{Maps the original array to a new one and adds 1 to each value if it is bigger then zero, otherwise it's removed.
{{{
$.map( [0,1,2], function(n){
return n > 0 ? n + 1 : null;
});
}}}
}}}
* {{multiLine{Maps the original array to a new one, each element is added with it's original value and the value plus one.
{{{
$.map( [0,1,2], function(n){
return [ n, n + 1 ];
});
}}}
}}}
* {{multiLine{Maps the original array to a new one, each element is squared.
{{{
$.map( [0,1,2,3], function (a) { return a * a; } );
}}}
}}}
* {{multiLine{Remove items by returning null from the function. This removes any numbers less than 50, and the rest are decreased by 45.
{{{
null$.map( [0, 1, 52, 97], function (a) { return (a > 50 ? a - 45 : null); } );
}}}
}}}
* {{multiLine{Augmenting the resulting array by returning an array inside the function.
{{{
var array = [0, 1, 52, 97];
array = $.map(array, function(a, index) {
return [a - 45, index];
});
}}}
}}}
Merge the contents of two arrays together into the first array.
|!Name|!Type|!Optional|!Description|h
|first|Array|no|The first array to merge, the elements of second added.|
|second|Array|no|The second array to merge into the first, unaltered.|
|Arguments|c
!Description
<html><p>The <code>$.merge()</code> operation forms an array that contains all elements from the two arrays. The orders of items in the arrays are preserved, with items from the second array appended. The <code>$.merge()</code> function is destructive. It alters the first parameter to add the items from the second. </p>
<p>If you need the original first array, make a copy of it before calling <code>$.merge()</code>. Fortunately, <code>$.merge()</code> itself can be used for this duplication:</p>
<pre>var newArray = $.merge([], oldArray);</pre>
<p>This shortcut creates a new, empty array and merges the contents of oldArray into it, effectively cloning the array.</p>
<p>The arguments should be true Javascript Array objects; use <code>$.makeArray</code> if they are not.</p></html>
!Examples
* {{multiLine{Merges two arrays, altering the first argument.
{{{
$.merge( [0,1,2], [2,3,4] )
}}}
}}}
* {{multiLine{Merges two arrays, altering the first argument.
{{{
$.merge( [3,2,1], [4,3,2] )
}}}
}}}
* {{multiLine{Merges two arrays, but uses a copy, so the original isn't altered.
{{{
var first = ['a','b','c'];
var second = ['d','e','f'];
$.merge( $.merge([],first), second);
}}}
}}}
Relinquish jQuery's control of the $ variable.
|!Name|!Type|!Optional|!Description|h
|removeAll|Boolean|yes|A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).|
|Arguments|c
!Description
<html><p>Many JavaScript libraries use <code> $</code> as a function or variable name, just as jQuery does. In jQuery's case, <code> $</code> is just an alias for <code>jQuery</code>, so all functionality is available without using <code> $</code>. If we need to use another JavaScript library alongside jQuery, we can return control of <code> $</code> back to the other library with a call to <code>$.noConflict()</code>:</p>
<pre>
<script type="text/javascript" src="other_lib.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$.noConflict();
// Code that uses other library's $ can follow here.
</script>
</pre>
<p>This technique is especially effective in conjunction with the .ready() method's ability to alias the jQuery object, as within callback passed to .ready() we can use $ if we wish without fear of conflicts later:</p>
<pre>
<script type="text/javascript" src="other_lib.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$.noConflict();
jQuery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.
</script>
</pre>
<p>If necessary, we can free up the <code> jQuery</code> name as well by passing <code>true</code> as an argument to the method. This is rarely necessary, and if we must do this (for example, if we need to use multiple versions of the <code>jQuery</code> library on the same page), we need to consider that most plug-ins rely on the presence of the jQuery variable and may not operate correctly in this situation.</p>
</html>
!Examples
* {{multiLine{Maps the original object that was referenced by $ back to $.
{{{
jQuery.noConflict();
// Do something with jQuery
jQuery("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';
}}}
}}}
* {{multiLine{Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery alias inside the functions scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library.
{{{
jQuery.noConflict();
(function($) {
$(function() {
// more code using $ as alias to jQuery
});
})(jQuery);
// other code using $ as an alias to the other library
}}}
}}}
* {{multiLine{You can chain the jQuery.noConflict() with the shorthand ready for a compact code.
{{{
jQuery.noConflict()(function(){
// code using jQuery
});
// other code using $ as an alias to the other library
}}}
}}}
* {{multiLine{Creates a different alias instead of jQuery to use in the rest of the script.
{{{
var j = jQuery.noConflict();
// Do something with jQuery
j("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';
}}}
}}}
* {{multiLine{Completely move jQuery to a new namespace in another object.
{{{
var dom = {};
dom.query = jQuery.noConflict(true);
}}}
}}}
An empty function.
!Description
<html><p>You can use this empty function when you wish to pass around a function that will do nothing.</p>
<p>This is useful for plugin authors who offer optional callbacks; in the case that no callback is given, something like <code>jQuery.noop</code> could execute.</p></html>
!Examples
Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.
|!Name|!Type|!Optional|!Description|h
|obj|Array, Object|no|An array or object to serialize.|
|obj|Array, Object|no|An array or object to serialize.|
|traditional|Boolean|no|A Boolean indicating whether to perform a traditional "shallow" serialization.|
|Arguments|c
!Description
<html>
<p>This function is used internally to convert form element values into a serialized string representation (See <a href="/serialize/">.serialize()</a> for more information).</p>
<p>As of jQuery 1.3, the return value of a function is used instead of the function as a String.</p>
<p>As of jQuery 1.4, the <code>$.param()</code> method serializes deep objects recursively to accommodate modern scripting languages and frameworks such as PHP and Ruby on Rails. You can disable this functionality globally by setting <code>jQuery.ajaxSettings.traditional = true;</code>.</p>
<p>If the object passed is in an Array, it must be an array of objects in the format returned by <a href="/serializeArray/">.serializeArray()</a></p>
<pre>[{name:"first",value:"Rick"},
{name:"last",value:"Astley"},
{name:"job",value:"Rock Star"}]</pre>
<p>Note: Because some frameworks have limited ability to parse serialized arrays, we should exercise caution when passing an <code>obj</code> argument that contains objects or arrays nested within another array.</p>
<p>In jQuery 1.4 HTML5 input elements are serialized, as well.</p>
<p>We can display a query string representation of an object and a URI-decoded version of the same as follows:</p>
<pre>var myObject = {
a: {
one: 1,
two: 2,
three: 3
},
b: [1,2,3]
};
var recursiveEncoded = $.param(myObject);
var recursiveDecoded = decodeURIComponent($.param(myObject));
alert(recursiveEncoded);
alert(recursiveDecoded);
</pre>
<p>The values of <code>recursiveEncoded</code> and <code>recursiveDecoded</code> are alerted as follows:</p>
<p><span class="output">a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3</span><br/>
<span class="output">a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3</span></p>
<p>To emulate the behavior of <code>$.param()</code> prior to jQuery 1.4, we can set the <code>traditional</code> argument to <code>true</code>:</p>
<pre>var myObject = {
a: {
one: 1,
two: 2,
three: 3
},
b: [1,2,3]
};
var shallowEncoded = $.param(myObject, true);
var shallowDecoded = decodeURIComponent(shallowEncoded);
alert(shallowEncoded);
alert(shallowDecoded);
</pre>
<p>The values of <code>shallowEncoded</code> and <code>shallowDecoded</code> are alerted as follows:</p>
<p><span class="output">a=%5Bobject+Object%5D&b=1&b=2&b=3</span><br/>
<span class="output">a=[object+Object]&b=1&b=2&b=3</span></p>
</html>
!Examples
* {{multiLine{Serialize a key/value object.
{{{
var params = { width:1680, height:1050 };
var str = jQuery.param(params);
$("#results").text(str);
}}}
}}}
* {{multiLine{Serialize a few complex objects
{{{
// <=1.3.2:
$.param({ a: [2,3,4] }) // "a=2&a=3&a=4"
// >=1.4:
$.param({ a: [2,3,4] }) // "a[]=2&a[]=3&a[]=4"
// <=1.3.2:
$.param({ a: { b:1,c:2 }, d: [3,4,{ e:5 }] }) // "a=[object+Object]&d=3&d=4&d=[object+Object]"
// >=1.4:
$.param({ a: { b:1,c:2 }, d: [3,4,{ e:5 }] }) // "a[b]=1&a[c]=2&d[]=3&d[]=4&d[2][e]=5"
}}}
}}}
Takes a well-formed JSON string and returns the resulting JavaScript object.
|!Name|!Type|!Optional|!Description|h
|json|String|no|The JSON string to parse.|
|Arguments|c
!Description
<html><p>Passing in a malformed JSON string will result in an exception being thrown. For example, the following are all malformed JSON strings:</p>
<ul>
<li><code>{test: 1}</code> (test does not have double quotes around it).</li>
<li><code>{'test': 1}</code> ('test' is using single quotes instead of double quotes).</li>
</ul>
<p>Additionally if you pass in nothing, an empty string, null, or undefined, 'null' will be returned from parseJSON. Where the browser provides a native implementation of <code>JSON.parse</code>, jQuery uses it to parse the string. For details on the JSON format, see <a href="http://json.org/">http://json.org/</a>.
</p></html>
!Examples
* {{multiLine{Parse a JSON string.
{{{
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
}}}
}}}
Load data from the server using a HTTP POST request.
|!Name|!Type|!Optional|!Description|h
|url|String|no|A string containing the URL to which the request is sent.|
|data|Map, String|yes|A map or string that is sent to the server with the request.|
|success(data, textStatus, XMLHttpRequest)|Function|yes|A callback function that is executed if the request succeeds.|
|dataType|String|yes|The type of data expected from the server.|
|Arguments|c
!Description
<html><p>This is a shorthand Ajax function, which is equivalent to:</p>
<pre>$.ajax({
type: 'POST',
url: <em>url</em>,
data: <em>data</em>,
success: <em>success</em>
dataType: <em>dataType</em>
});
</pre>
<p>The <code>success</code> callback function is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response. It is also passed the text status of the response.</p>
<p>As of jQuery 1.4, the <code>success</code> callback function is also passed the XMLHttpRequest object.</p>
<p>Most implementations will specify a success handler:</p>
<pre>$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
</pre>
<p>This example fetches the requested HTML snippet and inserts it on the page.</p>
<p>Pages fetched with <code>POST</code> are never cached, so the <code>cache</code> and <code>ifModified</code> options in <code><a href="/jQuery.ajaxSetup">jQuery.ajaxSetup()</a></code> have no effect on these requests.</p></html>
!Examples
* {{multiLine{Request the test.php page, but ignore the return results.
{{{
$.post("test.php");
}}}
}}}
* {{multiLine{Request the test.php page and send some additional data along (while still ignoring the return results).
{{{
$.post("test.php", { name: "John", time: "2pm" } );
}}}
}}}
* {{multiLine{pass arrays of data to the server (while still ignoring the return results).
{{{
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
}}}
}}}
* {{multiLine{send form data using ajax requests
{{{
$.post("test.php", $("#testform").serialize());
}}}
}}}
* {{multiLine{Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
{{{
$.post("test.php", function(data){
alert("Data Loaded: " + data);
});
}}}
}}}
* {{multiLine{Alert out the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).
{{{
$.post("test.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
}}}
}}}
* {{multiLine{Gets the test.php page content, store it in a XMLHttpResponse object and applies the process() JavaScript function.
{{{
$.post("test.php", { name: "John", time: "2pm" },
function(data){
process(data);
}, "xml");
}}}
}}}
* {{multiLine{Gets the test.php page contents which has been returned in json format ()
{{{
$.post("test.php", { "func": "getNameAndTime" },
function(data){
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");
}}}
}}}
Takes a function and returns a new one that will always have a particular context.
|!Name|!Type|!Optional|!Description|h
|function|Function|no|The function whose context will be changed.|
|context|Object|no|The object to which the context (`this`) of the function should be set.|
|context|Object|no|The object to which the context of the function should be set.|
|name|String|no|The name of the function whose context will be changed (should be a property of the 'context' object.|
|Arguments|c
!Description
<html><p>This method is most useful for attaching event handlers to an element where the context is pointing back to a different object. Additionally, jQuery makes sure that even if you bind the function returned from jQuery.proxy() it will still unbind the correct function, if passed the original.</p></html>
!Examples
* {{multiLine{Enforce the context of the function.
{{{
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 ) );
}}}
}}}
Add a collection of DOM elements onto the jQuery stack.
|!Name|!Type|!Optional|!Description|h
|elements|Array|no|An array of elements to push onto the stack and make into a new jQuery object.|
|elements|Array|no|An array of elements to push onto the stack and make into a new jQuery object.|
|name|String|no|The name of a jQuery method that generated the array of elements.|
|arguments|Array|no|The arguments that were passed in to the jQuery method (for serialization).|
|Arguments|c
!Description
N/A
!Examples
* {{multiLine{Add some elements onto the jQuery stack, then pop back off again.
{{{
jQuery([])
.pushStack( document.getElementsByTagName("div") )
.remove()
.end();
}}}
}}}
Manipulate the queue of functions to be executed on the matched element.
|!Name|!Type|!Optional|!Description|h
|element|Element|no|A DOM element where the array of queued functions is attached.|
|queueName|String|no|A string containing the name of the queue. Defaults to fx, the standard effects queue.|
|newQueue|Array|no|An array of functions to replace the current queue contents.|
|element|Element|no|A DOM element on which to add a queued function.|
|queueName|String|no|A string containing the name of the queue. Defaults to fx, the standard effects queue.|
|callback()|Function|no|The new function to add to the queue.|
|Arguments|c
!Description
<html><p><strong>Note:</strong> This is a low-level method, you should probably use <code><a href="/queue">.queue()</a></code> instead.</p>
<p>Every element can have one or more queues of functions attached to it by jQuery. In most applications, only one queue (called <code>fx</code>) is used. Queues allow a sequence of actions to be called on an element asynchronously, without halting program execution.</p>
<p>The <code>jQuery.queue()</code> method allows us to directly manipulate this queue of functions. Calling <code>jQuery.queue()</code> with a callback is particularly useful; it allows us to place a new function at the end of the queue.</p>
<p>Note that when adding a function with <code>jQuery.queue()</code>, we should ensure that <code>jQuery.dequeue()</code> is eventually called so that the next function in line executes.</p></html>
!Examples
* {{multiLine{Queue a custom function.
{{{
$(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();
});
}}}
}}}
* {{multiLine{Set a queue array to delete the queue.
{{{
$("#start").click(function () {
$("div").show("slow");
$("div").animate({left:'+=200'},5000);
jQuery.queue( $("div")[0], "fx", function () {
$(this).addClass("newcolor");
jQuery.dequeue( this );
});
$("div").animate({left:'-=200'},1500);
jQuery.queue( $("div")[0], "fx", function () {
$(this).removeClass("newcolor");
jQuery.dequeue( this );
});
$("div").slideUp();
});
$("#stop").click(function () {
jQuery.queue( $("div")[0], "fx", [] );
$("div").stop();
});
}}}
}}}
Remove a previously-stored piece of data.
|!Name|!Type|!Optional|!Description|h
|element|Element|no|A DOM element from which to remove data.|
|name|String|yes|A string naming the piece of data to remove.|
|Arguments|c
!Description
<html><p><strong>Note:</strong> This is a low-level method, you should probably use <code><a href="/removeData">.removeData()</a></code> instead.</p>
<p>The <code>jQuery.removeData()</code> method allows us to remove values that were previously set using <code><a href="/jQuery.data">jQuery.data()</a></code>. When called with the name of a key, <code>jQuery.removeData()</code> deletes that particular value; when called with no arguments, all values are removed.</p></html>
!Examples
* {{multiLine{Set a data store for 2 names then remove one of them.
{{{
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"));
}}}
}}}
A collection of properties that represent the presence of different browser features or bugs.
!Description
<html>
<p>Rather than using <code>$.browser</code> to detect the current user agent and alter the page presentation based on which browser is running, it is a good practice to perform <strong>feature detection</strong>. This means that prior to executing code which relies on a browser feature, we test to ensure that the feature works properly. To make this process simpler, jQuery performs many such tests and makes the results available to us as properties of the <code>jQuery.support</code> object.</p>
<p>The values of all the support properties are determined using feature detection (and do not use any form of browser sniffing). </p>
<blockquote>
<p>Following are a few resources that explain how feature detection works:</p>
<ul>
<li><a href="http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting">http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting</a></li>
<li><a href="http://www.jibbering.com/faq/faq_notes/not_browser_detect.html">http://www.jibbering.com/faq/faq_notes/not_browser_detect.html</a></li>
<li><a href="http://yura.thinkweb2.com/cft/">http://yura.thinkweb2.com/cft/</a></li>
</ul>
</blockquote>
<p>While jQuery includes a number of properties, developers should feel free to add their own as their needs dictate. Many of the <code>jQuery.support</code> properties are rather low-level, so they are most useful for plugin and jQuery core development, rather than general day-to-day development.</p>
<p>The tests included in <code>jQuery.support</code> are as follows:</p>
<ul>
<li><code>boxModel</code>: Is equal to true if the page is rendering according to the <a href="http://www.w3.org/TR/REC-CSS2/box.html">W3C CSS Box Model</a> (is currently false in IE 6 and 7 when they are in Quirks Mode). This property is null until document ready occurs.</li>
<li><code>cssFloat</code>: Is equal to true if the name of the property containing the CSS float value is .cssFloat, as defined in the <a href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSS2Properties-cssFloat">CSS Spec</a>. (It is currently false in IE, it uses styleFloat instead).</li>
<li><code>hrefNormalized</code>: Is equal to true if the <code>.getAttribute()</code> method retrieves the <code>href</code> attribute of elements unchanged, rather than normalizing it to a fully-qualified URL. (It is currently false in IE, the URLs are normalized).
<div><a href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-666EE0F9">DOM l3 spec</a></div></li>
<li><code>htmlSerialize</code>: Is equal to true if the browser is able to serialize/insert <code><link></code> elements using the <code>.innerHTML</code> property of elements. (is currently false in IE). <div><a href="http://www.w3.org/TR/2008/WD-html5-20080610/serializing.html#html-fragment">HTML5 wd</a></div></li>
<li><code>leadingWhitespace</code>: Is equal to true if the browser inserts content with .innerHTML exactly as provided—specifically, if leading whitespace characters are preserved. (It is currently false in IE 6-8). <div><a href="http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0">HTML5 wd</a></div></li>
<li><code>noCloneEvent</code>: Is equal to true if cloned DOM elements are created without event handlers (that is, if the event handlers on the source element are not cloned). (It is currently false in IE). <div><a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Registration-interfaces-h3">DOM l2 spec</a></div></li>
<li><code>objectAll</code>: Is equal to true if the <code>.getElementsByTagName()</code> method returns all descendant elements when called with a wildcard argument ('*'). (It is currently false in IE 7 and IE 8). <div><a href="http://www.w3.org/TR/WD-DOM/level-one-core.html#ID-745549614">DOM l1 spec</a></div></li>
<li><code>opacity</code>: Is equal to true if a browser can properly interpret the opacity style property. (It is currently false in IE, it uses alpha filters instead). <div><a href="http://www.w3.org/TR/css3-color/#transparency">CSS3 spec</a></div></li>
<li><code>scriptEval</code>: Is equal to true if inline scripts are automatically evaluated and executed when inserted to the document using standard DOM manipulation methods, such as <code>appendChild()</code> and <code>createTextNode()</code>. (It is currently false in IE, it uses <code>.text</code> to insert executable scripts). <div><a href="http://www.w3.org/TR/2008/WD-html5-20080610/tabular.html#script">HTML5 WD</a></div></li>
<li><code>style</code>: Is equal to true if inline styles for an element can be accessed through the DOM attribute called style, as required by the DOM Level 2 specification. In this case, <code>.getAttribute('style')</code> can retrieve this value; in Internet Explorer, <code>.cssText</code> is used for this purpose. <div><a href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-ElementCSSInlineStyle">DOM l2 Style spec</a></div></li>
<li><code>tbody</code>: Is equal to true if an empty <code><table></code> element can exist without a <code><tbody></code> element. According to the HTML specification, this sub-element is optional, so the property should be true in a fully-compliant browser. If false, we must account for the possibility of the browser injecting <code><tbody></code> tags implicitly. (It is currently false in IE, which automatically inserts <code>tbody</code> if it is not present in a string assigned to <code>innerHTML</code>). <div><a href="http://dev.w3.org/html5/spec/Overview.html#the-table-element">HTML5 spec</a></div></li>
</ul></html>
!Examples
* {{multiLine{Returns the box model for the iframe.
{{{
$("p").html("This frame uses the W3C box model: <span>" +
jQuery.support.boxModel + "</span>");
}}}
}}}
* {{multiLine{Returns false if the page is in QuirksMode in Internet Explorer
{{{
jQuery.support.boxModel
}}}
}}}
Remove the whitespace from the beginning and end of a string.
|!Name|!Type|!Optional|!Description|h
|str|String|no|The string to trim.|
|Arguments|c
!Description
<html>
<p>The <code>$.trim()</code> function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.</p>
</html>
!Examples
* {{multiLine{Remove the two white spaces at the start and at the end of the string.
{{{
$("button").click(function () {
var str = " lots of spaces before and after ";
alert("'" + str + "'");
str = jQuery.trim(str);
alert("'" + str + "' - no longer");
});
}}}
}}}
* {{multiLine{Remove the two white spaces at the start and at the end of the string.
{{{
$.trim(" hello, how are you? ");
}}}
}}}
Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.
|!Name|!Type|!Optional|!Description|h
|array|Array|no|The Array of DOM elements.|
|Arguments|c
!Description
<html><p>The <code>$.unique()</code> function searches through an array of objects, sorting the array, and removing any duplicate nodes. This function only works on plain JavaScript arrays of DOM elements, and is chiefly used internally by jQuery.</p>
<p>As of jQuery 1.4 the results will always be returned in document order.</p></html>
!Examples
* {{multiLine{Removes any duplicate elements from the array of divs.
{{{
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");
}}}
}}}
/***
|''Name''|jQueryDocsImportMacro|
|''Description''|imports the jQuery API documentation|
|''Author''|FND|
|''Version''|0.2.0|
|''Status''|@@experimental@@|
|''Source''|http://svn.tiddlywiki.org/Trunk/contributors/FND/jQueryDocsImportMacro.js|
|''CodeRepository''|http://svn.tiddlywiki.org/Trunk/contributors/FND/|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
|''CoreVersion''|2.5|
!Usage
{{{
<<jQueryDocsImport>>
}}}
<<jQueryDocsImport>>
!Revision History
!!v0.1 (2010-02-13)
* initial release
!!v0.2 (2010-02-13)
* improved arguments rendering
!Code
***/
//{{{
(function($) {
config.macros.jQueryDocsImport = {
btnLabel: "import jQuery API documentation",
btnTooltip: "imports the raw XML feed provided by api.jquery.com",
uri: "http://api.jquery.com/api/",
handler: function(place, macroName, params, wikifier, paramString, tiddler) {
var uri = this.uri;
createTiddlyButton(place, this.btnLabel, this.btnTooltip, function() {
displayMessage("importing jQuery API documentation");
ajaxReq({
type: "GET",
url: uri,
dataType: "xml",
success: function(data, status, xhr) {
parseDoc(data);
displayMessage("import complete");
},
error: function(xhr, error, exc) {
displayMessage("import failed");
}
});
});
}
};
var parseDoc = function(xml) {
store.suspendNotifications();
$("api > entries > entry", xml).
each(parseEntry);
store.resumeNotifications();
refreshAll();
};
var parseEntry = function(i, node) { // XXX: also does a save, which seems inappropriate
node = $(node);
var title = node.attr("name");
var tags = [
"jQuery API",
"new in v" + node.find("> signature > added").text()
];
$("> category", node).each(function(i, node) {
tags.push($(node).attr("name"));
});
var args = $("> signature > argument", node).map(function(i, node) {
node = $(node);
var name = node.attr("name");
var type = node.attr("type");
var optional = node.attr("optional") ? "yes" : "no";
var desc = node.find("desc").text();
return [[name, type, optional, desc]]; // nested array prevents flattening
});
if(args.length) {
args.splice(0, 0, ["Name", "Type", "Optional", "Description"]);
args = args.map(function(i, item) {
var template = i == 0 ? "|!%0|!%1|!%2|!%3|h" : "|%0|%1|%2|%3|";
return template.format(item);
});
args.push("|Arguments|c");
}
var examples = $("> example", node).map(function(i, node) {
node = $(node);
var desc = node.find("desc").text();
var code = node.find("code").text();
return "* {{multiLine{%0\n{{{\n%1\n}}}\n}}}".format([desc, code]);
});
var summary = node.find("> desc").text();
var desc = serialize(node.find("> longdesc")[0]).
replace(/<(\/?)longdesc>/g, "<$1html>").
replace(/<longdesc\s?\/>/, "N/A"); // XXX: hacky?
var join = Array.prototype.join;
var text = "%0\n%1\n!Description\n%2\n!Examples\n%3".format([
summary, join.apply(args, ["\n"]), desc, join.apply(examples, ["\n"])
]);
store.saveTiddler(title, title, text, "jQuery", new Date(), tags,
config.defaultCustomFields, false, new Date());
};
var serialize = function(xml) {
return window.ActiveXObject ? xml.xml : (new XMLSerializer()).serializeToString(xml);
};
})(jQuery);
//}}}
Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('keydown', handler)</code> in the first variation, and <code>.trigger('keydown')</code> in the second.</p>
<p>The <code>keydown</code> event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.</p>
<p>For example, consider the HTML:</p>
<pre><form>
<input id="target" type="text" value="Hello there" />
</form>
<div id="other">
Trigger the handler
</div></pre>
<p>The event handler can be bound to the input field:</p>
<pre>$('#target').keydown(function() {
alert('Handler for .keydown() called.');
});</pre>
<p>Now when the insertion point is inside the field and a key is pressed, the alert is displayed:</p>
<p><span class="output">Handler for .keydown() called.</span></p>
<p>We can trigger the event manually when another element is clicked:</p>
<pre>$('#other').click(function() {
$('#target').keydown();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also alert the message.</p>
<p>If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the <code>document</code> object. Because of event bubbling, all key presses will make their way up the DOM to the <code>document</code> object unless explicitly stopped.</p>
<p>To determine which key was pressed, we can examine the <a href="http://api.jquery.com/category/events/event-object/">event object</a> that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the <code>.which</code> property so we can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, <code>.keypress()</code> may be a better choice.</p>
</html>
!Examples
* {{multiLine{Show the event object for the keydown handler when a key is pressed in the input.
{{{
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();
});
}}}
}}}
Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('keypress', handler)</code> in the first variation, and <code>.trigger('keypress')</code> in the second.</p>
<p>The <code>keypress</code> event is sent to an element when the browser registers keyboard input. This is similar to the <code>keydown</code> event, except in the case of key repeats. If the user presses and holds a key, a <code>keydown </code>event is triggered once, but separate <code>keypress</code> events are triggered for each inserted character. In addition, modifier keys (such as Shift) cause <code>keydown</code> events but not <code>keypress</code> events.</p>
<p>A <code>keypress</code> event handler can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.</p>
<p>For example, consider the HTML:</p>
<pre><form>
<fieldset>
<input id="target" type="text" value="Hello there" />
</fieldset>
</form>
<div id="other">
Trigger the handler
</div></pre>
<p>The event handler can be bound to the input field:</p>
<pre>$('#target').keypress(function() {
alert('Handler for .keypress() called.');
});</pre>
<p>Now when the insertion point is inside the field and a key is pressed, the alert is displayed:</p>
<p><span class="output">Handler for .keypress() called.</span></p>
<p>The message repeats if the key is held down. We can trigger the event manually when another element is clicked:</p>
<pre>$('#other').click(function() {
$('#target').keypress();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also alert the message.</p>
<p>If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the <code>document</code> object. Because of event bubbling, all key presses will make their way up the DOM to the <code>document</code> object unless explicitly stopped.</p>
<p>To determine which character was entered, we can examine the event object that is passed to the handler function. While browsers use differing attributes to store this information, jQuery normalizes the <code>.which</code> attribute so we can reliably use it to retrieve the character code.</p>
<p>Note that <code>keydown</code> and <code>keyup</code> provide a code indicating which key is pressed, while <code>keypress</code> indicates which character was entered. For example, a lowercase "a" will be reported as 65 by <code>keydown</code> and <code>keyup</code>, but as 97 by <code>keypress</code>. An uppercase "A" is reported as 65 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, <code>.keydown()</code> or <code>.keyup()</code> is a better choice.</p>
</html>
!Examples
* {{multiLine{Show the event object for the keypress handler when a key is pressed in the input.
{{{
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();
});
}}}
}}}
Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('keyup', handler)</code> in the first variation, and <code>.trigger('keyup')</code> in the second.</p>
<p>The <code>keyup</code> event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.</p>
<p>For example, consider the HTML:</p>
<pre><form>
<input id="target" type="text" value="Hello there" />
</form>
<div id="other">
Trigger the handler
</div></pre>
<p>The event handler can be bound to the input field:</p>
<pre>$('#target').keyup(function() {
alert('Handler for .keyup() called.');
});
</pre>
<p>Now when the insertion point is inside the field and a key is pressed and released, the alert is displayed:</p>
<p><span class="output">Handler for .keyup() called.</span></p>
<p>We can trigger the event manually when another element is clicked:</p>
<pre>$('#other').click(function() {
$('#target').keyup();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also alert the message.</p>
<p>If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the <code>document</code> object. Because of event bubbling, all key presses will make their way up the DOM to the <code>document</code> object unless explicitly stopped.</p>
<p>To determine which key was pressed, we can examine the event object that is passed to the handler function. While browsers use differing attributes to store this information, jQuery normalizes the <code>.which</code> attribute so we can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, <code>.keypress()</code> may be a better choice.</p>
</html>
!Examples
* {{multiLine{Show the event object for the keyup handler when a key is released in the input.
{{{
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();
});
}}}
}}}
Reduce the set of matched elements to the final one in the set.
!Description
<html>[<p>Given a jQuery object that represents a set of DOM elements, the <code>.last()</code> method constructs a new jQuery object from the last matching element.</p>
<p>Consider a page with a simple list on it:</p>
<pre>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
</pre>
<p>We can apply this method to the set of list items:</p>
<pre>$('li').last().css('background-color', 'red');</pre>
<p>The result of this call is a red background for the final item.</p></html>
!Examples
* {{multiLine{Highlight the last span in a paragraph.
{{{
$("p span").last().addClass('highlight');
}}}
}}}
Selects all elements that are the last child of their parent.
!Description
<html><p>While <a href="/last-selector">:last</a> matches only a single element, <code>:last-child</code> can match more than one: one for each parent.</p></html>
!Examples
* {{multiLine{Finds the last span in each matched div and adds some css plus a hover state.
{{{
$("div span:last-child")
.css({color:"red", fontSize:"80%"})
.hover(function () {
$(this).addClass("solast");
}, function () {
$(this).removeClass("solast");
});
}}}
}}}
The number of elements in the jQuery object.
!Description
<html><p>The number of elements currently matched. The .<a href="/size">size()</a> method will return the same value.</p></html>
!Examples
* {{multiLine{Count the divs. Click to add more.
{{{
$(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
}}}
}}}
Attach a handler to the event for all elements which match the current selector, now or in the future.
|!Name|!Type|!Optional|!Description|h
|eventType|String|no|A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names, as well.|
|handler|Function|no|A function to execute at the time the event is triggered.|
|eventType|String|no|A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names, as well.|
|eventData|Object|no|A map of data that will be passed to the event handler.|
|handler|Function|no|A function to execute at the time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a variation on the basic <code>.bind()</code> method for attaching event handlers to elements. When <code>.bind()</code> is called, the elements that the jQuery object refers to get the handler attached; elements that get introduced later do not, so they would require another <code>.bind()</code> call. For instance, consider the HTML:</p>
<pre><body>
<div class="clickme">
Click here
</div>
</body>
</pre>
<p>We can bind a simple click handler to this element:</p>
<pre>$('.clickme').bind('click', function() {
// Bound handler called.
});
</pre>
<p>When the element is clicked, the handler is called. However, suppose that after this, another element is added:
</p>
<pre>$('body').append('<div class="clickme">Another target</div>');</pre>
<p>This new element also matches the selector <code>.clickme</code>, but since it was added after the call to <code>.bind()</code>, clicks on it will do nothing.</p>
<p>The <code>.live()</code> method provides an alternative to this behavior. If we bind a click handler to the target element using this method:</p>
<pre>$('.clickme').live('click', function() {
// Live handler called.
});</pre>
<p>And then later add a new element:</p>
<pre>$('body').append('<div class="clickme">Another target</div>');</pre>
<p>Then clicks on the new element will also trigger the handler.</p>
<h4 id="event-delegation">Event Delegation</h4>
<p>The <code>.live()</code> method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to <code>.live()</code> is never bound to an element; instead, <code>.live()</code> binds a special handler to the root of the DOM tree. In our example, when the new element is clicked, the following steps occur:</p>
<ol>
<li>A click event is generated and passed to the <code><div></code> for handling.</li>
<li>No handler is directly bound to the <code><div></code>, so the event bubbles up the DOM tree.</li>
<li>The event bubbles up until it reaches the root of the tree, which is where <code>.live()</code> binds its special handlers by default. <br/><em>* As of jQuery 1.4, event bubbling can optionally stop at a DOM element "context".</em></li>
<li>The special <code>click</code> handler bound by <code>.live()</code> executes.</li>
<li>This handler tests the <code>target</code> of the event object to see whether it should continue. This test is performed by checking if <code>$(event.target).closest('.clickme')</code> is able to locate a matching element.</li>
<li>If a matching element is found, the original handler is called on it.</li>
</ol>
<p>Because the test in step 5 is not performed until the event occurs, elements can be added at any time and still respond to events.</p>
<p>See the discussion for <code><a href="/bind">.bind()</a></code> for more information on event binding.</p>
<h4 id="multiple-events">Multiple Events</h4>
<p>As of jQuery 1.4.1 <code>.live()</code> can accept multiple, space-separated events, similar to the functionality provided in <a href="/bind">.bind()</a>. For example, we can "live bind" the <code>mouseover</code> and <code>mouseout</code> events at the same time like so: </p>
<pre>$('.hoverme').live('mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
// do something on mouseover
} else {
// do something on mouseout
}
});</pre>
<h4 id="event-data">Event Data</h4>
<p>As of jQuery 1.4, the optional <code>eventData</code> parameter allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures. See the <code>.bind()</code> method's "<a href="/bind/#passing-event-data">Passing Event Data</a>" discussion for more information.</p>
<h4 id="event-context">Event Context</h4>
<p>As of jQuery 1.4, live events can be bound to a DOM element "context" rather than to the default document root. To set this context, we use the <a href="http://api.jquery.com/jquery/#selector-context"><code>jQuery()</code> function's second argument</a>, passing in a single DOM element (as opposed to a jQuery collection or a selector).</p>
<pre>$('div.clickme', $('#container')[0]).live('click', function() {
// Live handler called.
});</pre>
<p>The live handler in this example is called only when <code><div class="clickme"></code> is a descendant of an element with an ID of "container."</p>
<h4 id="caveats">Caveats</h4>
<p>The <code>.live()</code> technique is useful, but due to its special approach cannot be simply substituted for <code>.bind()</code> in all cases. Specific differences include:</p>
<ul>
<li>DOM traversal methods are not fully supported for finding elements to send to <code>.live()</code>. Rather, the <code>.live()</code> method should always be called directly after a selector, as in the example above.</li>
<li>To stop further handlers from executing after one bound using <code>.live()</code>, the handler must return <code>false</code>. Calling <code>.stopPropagation()</code> will not accomplish this.</li>
<li>In <b>jQuery 1.3.x</b> only the following JavaScript events (in addition to custom events) could be bound with <code>.live()</code>: <code>click</code>, <code>dblclick</code>, <code>keydown</code>, <code>keypress</code>, <code>keyup</code>, <code>mousedown</code>, <code>mousemove</code>, <code>mouseout</code>, <code>mouseover</code>, and <code>mouseup</code>.</li>
</ul>
<blockquote>
<ul>
<li>As of <b>jQuery 1.4</b> the <code>.live()</code> method supports custom events as well as all JavaScript events. As of <b>jQuery 1.4.1</b> even <code>focus</code> and <code>blur</code> work with live (mapping to the more appropriate, bubbling, events <code>focusin</code> and <code>focusout</code>).</li>
<li>As of <b>jQuery 1.4.1</b> the <code>hover</code> event can be specified (mapping to "<code>mouseenter mouseleave</code>").</li>
</ul>
</blockquote>
</html>
!Examples
* {{multiLine{Click a paragraph to add another. Note that .live() binds the click event to all paragraphs - even new ones.
{{{
$("p").live("click", function(){
$(this).after("<p>Another paragraph!</p>");
});
}}}
}}}
* {{multiLine{To display each paragraph's text in an alert box whenever it is clicked:
{{{
$("p").live("click", function(){
alert( $(this).text() );
});
}}}
}}}
* {{multiLine{To cancel a default action and prevent it from bubbling up, return false:
{{{
$("a").live("click", function() { return false; })
}}}
}}}
* {{multiLine{To cancel only the default action by using the preventDefault method.
{{{
$("a").live("click", function(event){
event.preventDefault();
});
}}}
}}}
* {{multiLine{Can bind custom events too.
{{{
$("p").live("myCustomEvent", function(e, myName, myValue){
$(this).text("Hi there!");
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent");
});
}}}
}}}
Load data from the server and place the returned HTML into the matched element.
|!Name|!Type|!Optional|!Description|h
|url|String|no|A string containing the URL to which the request is sent.|
|data|Map, String|yes|A map or string that is sent to the server with the request.|
|complete(responseText, textStatus, XMLHttpRequest)|Function|yes|A callback function that is executed when the request completes.|
|Arguments|c
!Description
<html>
<p>This method is the simplest way to fetch data from the server. It is roughly equivalent to <code>$.get(url, data, success)</code> except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when <code>textStatus</code> is "success" or "notmodified"), <code>.load()</code> sets the HTML contents of the matched element to the returned data. This means that most uses of the method can be quite simple:</p>
<pre>$('#result').load('ajax/test.html');</pre>
<p>The provided callback, if any, is executed after this post-processing has been performed:</p>
<pre>$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});</pre>
<p>In the two examples above, if the current document does not contain an element with an ID of "result," the <code>.load()</code> method is not executed.</p>
<p>The POST method is used if data is provided as an object; otherwise, GET is assumed.</p>
<blockquote><p>Note: The event handling suite also has a method named <code><a href="/load-event">.load()</a></code>. Which one is fired depends on the set of arguments passed.</p></blockquote>
<h4>Loading Page Fragments</h4>
<p>The <code>.load()</code> method, unlike <code><a href="/jQuery.get">$.get()</a></code>, allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the <code>url</code> parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded. </p>
<p>We could modify the example above to use only part of the document that is fetched:</p>
<pre>$('#result').load('ajax/test.html #container');</pre>
<p>When this method executes, it retrieves the content of <code>ajax/test.html</code>, but then jQuery parses the returned document to find the element with an ID of <code>container</code>. This element, along with its contents, is inserted into the element with an ID of <code>result</code>, and the rest of the retrieved document is discarded.</p>
<p>Note that the document retrieved cannot be a full HTML document; that is, it <em>cannot</em> include (for example) <code><html></code>, <code><title></code>, or <code><head></code> elements. jQuery uses the browser's <code>innerHTML</code> property on a <code><div></code> element to parse the document, and most browsers will not allow non-body elements to be parsed in this way.</p>
</html>
!Examples
* {{multiLine{Load the main page's footer navigation into an ordered list.
{{{
$("#new-nav").load("/ #jq-footerNavigation li");
}}}
}}}
* {{multiLine{Display a notice if the Ajax request encounters an error.
{{{
$("#success").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
}}}
}}}
* {{multiLine{Load the feeds.html file into the div with the ID of feeds.
{{{
$("#feeds").load("feeds.html");
}}}
}}}
* {{multiLine{pass arrays of data to the server.
{{{
$("#objectID").load("test.php", { 'choices[]': ["Jon", "Susan"] } );
}}}
}}}
* {{multiLine{Same as above, but will POST the additional parameters to the server and a callback that is executed when the server is finished responding.
{{{
$("#feeds").load("feeds.php", {limit: 25}, function(){
alert("The last 25 entries in the feed have been loaded");
});
}}}
}}}
Select all elements at an index less than index within the matched set.
|!Name|!Type|!Optional|!Description|h
|index|Number|no|Zero-based index.|
|Arguments|c
!Description
<html><p><strong>index-related selectors</strong></p>
<p>The index-related selectors (including this "less than" selector) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set. For example, if elements are first selected with a class selector (<code>.myclass</code>) and four elements are returned, these elements are given indices 0 through 3 for the purposes of these selectors.</p>
<p>Note that since JavaScript arrays use <em>0-based indexing</em>, these selectors reflect that fact. This is why <code>$('.myclass:lt(1)')</code> selects the first element in the document with the class <code>myclass</code>, rather than selecting no elements. In contrast, <code>:nth-child(n)</code> uses <em>1-based indexing</em> to conform to the CSS specification.</p>
</html>
!Examples
* {{multiLine{Finds TDs less than the one with the 4th index (TD#4).
{{{
$("td:lt(4)").css("color", "red");
}}}
}}}
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
|!Name|!Type|!Optional|!Description|h
|callback(index, domElement)|Function|no|A function object that will be invoked for each element in the current set.|
|Arguments|c
!Description
<html><p>As the return value is a jQuery-wrapped array, it's very common to <code>get()</code> the returned object to work with a basic array.</p><p>The <code>.map()</code> method is particularly useful for getting or setting the value of a collection of elements. Consider a form with a set of checkboxes in it:</p>
<pre>
<form method="post" action="">
<fieldset>
<div>
<label for="two">2</label>
<input type="checkbox" value="2" id="two" name="number[]">
</div>
<div>
<label for="four">4</label>
<input type="checkbox" value="4" id="four" name="number[]">
</div>
<div>
<label for="six">6</label>
<input type="checkbox" value="6" id="six" name="number[]">
</div>
<div>
<label for="eight">8</label>
<input type="checkbox" value="8" id="eight" name="number[]">
</div>
</fieldset>
</form>
</pre>
<p>We can get a comma-separated list of checkbox <code>ID</code>s:</p>
<pre>$(':checkbox').map(function() {
return this.id;
}).get().join(',');</pre>
<p>The result of this call is the string, <code>"two,four,six,eight"</code>.</p>
<p>Within the callback function, <code>this</code> refers to the current DOM element for each iteration.</p>
</html>
!Examples
* {{multiLine{Build a list of all the values within a form.
{{{
$("p").append( $("input").map(function(){
return $(this).val();
}).get().join(", ") );
}}}
}}}
* {{multiLine{A contrived example to show some functionality.
{{{
var mappedItems = $("li").map(function (index) {
var replacement = $("<li>").text($(this).text()).get(0);
if (index == 0) {
// make the first item all caps
$(replacement).text($(replacement).text().toUpperCase());
} else if (index == 1 || index == 3) {
// delete the second and fourth items
replacement = null;
} else if (index == 2) {
// make two of the third item and add some text
replacement = [replacement,$("<li>").get(0)];
$(replacement[0]).append("<b> - A</b>");
$(replacement[1]).append("Extra <b> - B</b>");
}
// replacement will be an dom element, null,
// or an array of dom elements
return replacement;
});
$("#results").append(mappedItems);
}}}
}}}
* {{multiLine{Equalize the heights of the divs.
{{{
$.fn.equalizeHeights = function(){
return this.height( Math.max.apply(this, $(this).map(function(i,e){ return $(e).height() }).get() ) )
}
$('input').click(function(){
$('div').equalizeHeights();
});
}}}
}}}
Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('mousedown', handler)</code> in the first variation, and <code>.trigger('mousedown')</code> in the second.</p>
<p>The <code>mousedown</code> event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed. Any HTML element can receive this event.</p>
<p>For example, consider the HTML:</p>
<pre><div id="target">
Click here
</div>
<div id="other">
Trigger the handler
</div></pre>
<p class="image"><img src="/images/0042_05_01.png" alt=""/></p>
<p>The event handler can be bound to any <code><div></code>:</p>
<pre>$('#target').mousedown(function() {
alert('Handler for .mousedown() called.');
});</pre>
<p>Now if we click on this element, the alert is displayed:</p>
<p><span class="output">Handler for .mousedown() called.</span></p>
<p>We can also trigger the event when a different element is clicked:</p>
<pre>$('#other').click(function() {
$('#target').mousedown();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also alert the message.</p>
<p>The <code>mousedown</code> event is sent when any mouse button is clicked. To act only on specific buttons, we can use the event object's <code>which </code>property. Not all browsers support this property (Internet Explorer uses button instead), but jQuery normalizes the property so that it is safe to use in any browser. The value of <code>which</code> will be 1 for the left button, 2 for the middle button, or 3 for the right button.</p>
<p>This event is primarily useful for ensuring that the primary button was used to begin a drag operation; if ignored, strange results can occur when the user attempts to use a context menu. While the middle and right buttons can be detected with these properties, this is not reliable. In Opera and Safari, for example, right mouse button clicks are not detectable by default.</p>
<p>If the user clicks on an element, drags away from it, and releases the button, this is still counted as a <code>mousedown</code> event. This sequence of actions is treated as a "canceling" of the button press in most user interfaces, so it is usually better to use the <code>click</code> event unless we know that the <code>mousedown</code> event is preferable for a particular situation.</p>
</html>
!Examples
* {{multiLine{Show texts when mouseup and mousedown event triggering.
{{{
$("p").mouseup(function(){
$(this).append('<span style="color:#F00;">Mouse up.</span>');
}).mousedown(function(){
$(this).append('<span style="color:#00F;">Mouse down.</span>');
});
}}}
}}}
Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('mouseenter', handler)</code> in the first variation, and <code>.trigger('mouseenter')</code> in the second.</p>
<p>The <code>mouseenter</code> JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser. This event sent to an element when the mouse pointer enters the element. Any HTML element can receive this event.</p>
<p>For example, consider the HTML:</p>
<pre><div id="outer">
Outer
<div id="inner">
Inner
</div>
</div>
<div id="other">
Trigger the handler
</div>
<div id="log"></div></pre>
<p class="image"><img src="/images/0042_05_08.png" alt=""/>
</p>
<p>The event handler can be bound to any element:</p>
<pre>$('#outer').mouseenter(function() {
$('#log').append('<div>Handler for .mouseenter() called.</div>');
});</pre>
<p>Now when the mouse pointer moves over the <span class="output">Outer</span> <code><div></code>, the message is appended to <code><div id="log"></code>. We can also trigger the event when another element is clicked:</p>
<pre>$('#other').click(function() {
$('#outer').mouseenter();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also append the message.</p>
<p>The <code>mouseenter</code> event differs from <code>mouseover</code> in the way it handles event bubbling. If <code>mouseover</code> were used in this example, then when the mouse pointer moved over the <span class="output">Inner</span> element, the handler would be triggered. This is usually undesirable behavior. The <code>mouseenter</code> event, on the other hand, only triggers its handler when the mouse enters the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse enters the <span class="output">Outer</span> element, but not the <span class="output">Inner</span> element.</p>
</html>
!Examples
* {{multiLine{Show texts when mouseenter and mouseout event triggering.
mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.
{{{
mouseovermouseenter
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");
});
}}}
}}}
Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('mouseleave', handler)</code> in the first variation, and <code>.trigger('mouseleave')</code> in the second.</p>
<p>The <code>mouseleave</code> JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser. This event is sent to an element when the mouse pointer leaves the element. Any HTML element can receive this event.</p>
<p>For example, consider the HTML:</p>
<pre><div id="outer">
Outer
<div id="inner">
Inner
</div>
</div>
<div id="other">
Trigger the handler
</div>
<div id="log"></div></pre>
<p class="image"><img src="/images/0042_05_09.png" alt=""/>
</p>
<p>The event handler can be bound to any element:</p>
<pre>$('#outer').mouseleave(function() {
$('#log').append('<div>Handler for .mouseleave() called.</div>');
});</pre>
<p>Now when the mouse pointer moves out of the <span class="output">Outer</span> <code><div></code>, the message is appended to <code><div id="log"></code>. We can also trigger the event when another element is clicked:</p>
<pre>$('#other').click(function() {
$('#outer').mouseleave();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also append the message.</p>
<p>The <code>mouseleave</code> event differs from <code>mouseout</code> in the way it handles event bubbling. If <code>mouseout</code> were used in this example, then when the mouse pointer moved out of the <span class="output">Inner</span> element, the handler would be triggered. This is usually undesirable behavior. The <code>mouseleave</code> event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse leaves the <span class="output">Outer</span> element, but not the <span class="output">Inner</span> element.</p>
</html>
!Examples
* {{multiLine{Show number of times mouseout and mouseleave events are triggered.
mouseout fires when the pointer moves out of child element as well, while mouseleave fires only when the pointer moves out of the bound element.
{{{
mouseoutmouseleave
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);
});
}}}
}}}
Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('mousemove', handler)</code> in the first variation, and <code>.trigger('mousemove')</code> in the second.</p>
<p>The <code>mousemove</code> event is sent to an element when the mouse pointer moves inside the element. Any HTML element can receive this event.</p>
<p>For example, consider the HTML:</p>
<pre><div id="target">
Move here
</div>
<div id="other">
Trigger the handler
</div>
<div id="log"></div></pre>
<p class="image"><img src="/images/0042_05_10.png" alt=""/>
</p>
<p>The event handler can be bound to the target:</p>
<pre>$('#target').mousemove(function(event) {
var msg = 'Handler for .mousemove() called at ' + event.pageX + ', ' + event.pageY;
$('#log').append('<div> + msg + '</div>');
});</pre>
<p>Now when the mouse pointer moves within the target button, the messages are appended to <div id="log">:</p>
<p>
<span class="output">Handler for .mousemove() called at (399, 48)</span><br/>
<span class="output">Handler for .mousemove() called at (398, 46)</span><br/>
<span class="output">Handler for .mousemove() called at (397, 44)</span><br/>
<span class="output">Handler for .mousemove() called at (396, 42)</span><br/>
</p>
<p>We can also trigger the event when the second button is clicked:</p>
<pre>$('#other').click(function() {
$('#target').mousemove();
});</pre>
<p>After this code executes, clicks on the Trigger button will also append the message:</p>
<p><span class="output">Handler for .mousemove() called at (undefined, undefined)</span></p>
<p>When tracking mouse movement, we usually need to know the actual position of the mouse pointer. The event object that is passed to the handler contains some information about the mouse coordinates. Properties such as <code>.clientX</code>, <code>.offsetX</code>, and <code>.pageX</code> are available, but support for them differs between browsers. Fortunately, jQuery normalizes the <code>.pageX</code> and <code>.pageY</code> attributes so that they can be used in all browsers. These attributes provide the X and Y coordinates of the mouse pointer relative to the top-left corner of the page, as illustrated in the example output above.</p>
<p>We need to remember that the <code>mousemove</code> event is triggered whenever the mouse pointer moves, even for a pixel. This means that hundreds of events can be generated over a very small amount of time. If the handler has to do any significant processing, or if multiple handlers for the event exist, this can be a serious performance drain on the browser. It is important, therefore, to optimize <code>mousemove </code>handlers as much as possible, and to unbind them as soon as they are no longer needed.</p>
<p>A common pattern is to bind the <code>mousemove</code> handler from within a <code>mousedown</code> hander, and to unbind it from a corresponding <code>mouseup</code> handler. If implementing this sequence of events, remember that the <code>mouseup</code> event might be sent to a different HTML element than the <code>mousemove</code> event was. To account for this, the <code>mouseup</code> handler should typically be bound to an element high up in the DOM tree, such as <code><body></code>.</p>
</html>
!Examples
* {{multiLine{Show the mouse coordinates when the mouse is moved over the yellow div. Coordinates are relative to the window, which in this case is the iframe.
{{{
$("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);
});
}}}
}}}
Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('mouseout', handler)</code> in the first variation, and <code>.trigger('mouseout')</code> in the second.</p>
<p>The <code>mouseout</code> event is sent to an element when the mouse pointer leaves the element. Any HTML element can receive this event.</p>
<p>For example, consider the HTML:</p>
<pre><div id="outer">
Outer
<div id="inner">
Inner
</div>
</div>
<div id="other">
Trigger the handler
</div>
<div id="log"></div></pre>
<p class="image"><img src="/images/0042_05_07.png" alt=""/>
</p>
<p>The event handler can be bound to any element:</p>
<pre>$('#outer').mouseout(function() {
$('#log').append('Handler for .mouseout() called.');
});</pre>
<p>Now when the mouse pointer moves out of the <span class="output">Outer</span> <code><div></code>, the message is appended to <code><div id="log"></code>. We can also trigger the event when another element is clicked:</p>
<pre>$('#other').click(function() {
$('#outer').mouseout();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also append the message.</p>
<p>This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves out of the <span class="output">Inner</span> element in this example, a <code>mouseout</code> event will be sent to that, then trickle up to <span class="output">Outer</span>. This can trigger the bound <code>mouseout</code> handler at inopportune times. See the discussion for <code>.<a href="/mouseleave">mouseleave</a>()</code> for a useful alternative.</p>
</html>
!Examples
* {{multiLine{Show the number of times mouseout and mouseleave events are triggered.
mouseout fires when the pointer moves out of the child element as well, while mouseleave fires only when the pointer moves out of the bound element.
{{{
mouseoutmouseleave
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);
});
}}}
}}}
Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('mouseover', handler)</code> in the first variation, and <code>.trigger('mouseover')</code> in the second.</p>
<p>The <code>mouseover</code> event is sent to an element when the mouse pointer enters the element. Any HTML element can receive this event.</p>
<p>For example, consider the HTML:</p>
<pre><div id="outer">
Outer
<div id="inner">
Inner
</div>
</div>
<div id="other">
Trigger the handler
</div>
<div id="log"></div></pre>
<p class="image"><img src="/images/0042_05_06.png" alt=""/>
</p>
<p>The event handler can be bound to any element:</p>
<pre>$('#outer').mouseover(function() {
$('#log').append('<div>Handler for .mouseover() called.</div>');
});</pre>
<p>Now when the mouse pointer moves over the <span class="output">Outer</span> <code><div></code>, the message is appended to <code><div id="log"></code>. We can also trigger the event when another element is clicked:</p>
<pre>$('#other').click(function() {
$('#outer').mouseover();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also append the message.</p>
<p>This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves over the <span class="output">Inner</span> element in this example, a <code>mouseover</code> event will be sent to that, then trickle up to <span class="output">Outer</span>. This can trigger our bound <code>mouseover</code> handler at inopportune times. See the discussion for <code>.mouseenter()</code> for a useful alternative.</p>
</html>
!Examples
* {{multiLine{Show the number of times mouseover and mouseenter events are triggered.
mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.
{{{
mouseovermouseenter
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").bind("mouseenter",function(){
$("p:first",this).text("mouse enter");
$("p:last",this).text(++n);
}).bind("mouseleave",function(){
$("p:first",this).text("mouse leave");
});
}}}
}}}
Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('mouseup', handler)</code> in the first variation, and <code>.trigger('mouseup')</code> in the second.</p>
<p>The <code>mouseup</code> event is sent to an element when the mouse pointer is over the element, and the mouse button is released. Any HTML element can receive this event.</p>
<p>For example, consider the HTML:</p>
<pre><div id="target">
Click here
</div>
<div id="other">
Trigger the handler
</div>
</pre>
<p class="image"><img src="/images/0042_05_02.png" alt=""/></p>
<p>The event handler can be bound to any <code><div></code>:</p>
<pre>$('#target').mouseup(function() {
alert('Handler for .mouseup() called.');
});
</pre>
<p>Now if we click on this element, the alert is displayed:</p>
<p><span class="output">Handler for .mouseup() called.</span></p>
<p>We can also trigger the event when a different element is clicked:</p>
<pre>$('#other').click(function() {
$('#target').mouseup();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also alert the message.</p>
<p>If the user clicks outside an element, drags onto it, and releases the button, this is still counted as a <code>mouseup</code> event. This sequence of actions is not treated as a button press in most user interfaces, so it is usually better to use the <code>click</code> event unless we know that the <code>mouseup</code> event is preferable for a particular situation.</p>
</html>
!Examples
* {{multiLine{Show texts when mouseup and mousedown event triggering.
{{{
$("p").mouseup(function(){
$(this).append('<span style="color:#F00;">Mouse up.</span>');
}).mousedown(function(){
$(this).append('<span style="color:#00F;">Mouse down.</span>');
});
}}}
}}}
Selects the combined results of all the specified selectors.
|!Name|!Type|!Optional|!Description|h
|selector1|Selector|no|Any valid selector.|
|selector2|Selector|no|Another valid selector.|
|selectorN|Selector|yes|As many more valid selectors as you like.|
|Arguments|c
!Description
<html><p>You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order. An alternative to this combinator is the .<a href="/add">add()</a> method.</p></html>
!Examples
* {{multiLine{Finds the elements that match any of these three selectors.
{{{
$("div,span,p.myClass").css("border","3px solid red");
}}}
}}}
* {{multiLine{Show the order in the jQuery object.
{{{
var list = $("div,p,span").map(function () {
return this.tagName;
}).get().join(", ");
$("b").append(document.createTextNode(list));
}}}
}}}
Get the immediately following sibling of each element in the set of matched elements, optionally filtered by a selector.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|yes|A string containing a selector expression to match elements against.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.next()</code> method allows us to search through the immediately following sibling of these elements in the DOM tree and construct a new jQuery object from the matching elements.</p>
<p>The method optionally accepts a selector expression of the same type that we can pass to the <code>$()</code> function. If the the immediately following sibling matches the selector, it remains in the newly constructed jQuery object; otherwise, it is excluded.</p>
<p>Consider a page with a simple list on it:</p>
<pre>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
</pre>
<p>If we begin at the third item, we can find the element which comes just after it:</p>
<pre>$('li.third-item').next().css('background-color', 'red');</pre>
<p>The result of this call is a red background behind item 4. Since we do not supply a selector expression, this following element is unequivocally included as part of the object. If we had supplied one, the element would be tested for a match before it was included.</p></html>
!Examples
* {{multiLine{Find the very next sibling of each disabled button and change its text "this button is disabled".
{{{
$("button[disabled]").next().text("this button is disabled");
}}}
}}}
* {{multiLine{Find the very next sibling of each paragraph. Keep only the ones with a class "selected".
{{{
$("p").next(".selected").css("background", "yellow");
}}}
}}}
Selects all next elements matching "next" that are immediately preceded by a sibling "prev".
|!Name|!Type|!Optional|!Description|h
|prev|Selector|no|Any valid selector.|
|next|Selector|no|A selector to match the element that is next to the first selector.|
|Arguments|c
!Description
<html>
<p>One important point to consider with both the next adjacent sibling selector (<code>prev + next</code>) and the general sibling selector (<code>prev ~ siblings</code>) is that the elements on either side of the combinator must share the same parent.</p></html>
!Examples
* {{multiLine{Finds all inputs that are next to a label.
{{{
$("label + input").css("color", "blue").val("Labeled!")
}}}
}}}
Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.
|!Name|!Type|!Optional|!Description|h
|prev|Selector|no|Any valid selector.|
|siblings|Selector|no|A selector to filter elements that are the following siblings of the first selector.|
|Arguments|c
!Description
<html><p>The notable difference between (<code>prev + next</code>) and (<code>prev ~ siblings</code>) is their respective reach. While the former reaches only to the immediately following sibling element, the latter extends that reach to all following sibling elements.</p></html>
!Examples
* {{multiLine{Finds all divs that are siblings after the element with #prev as its id. Notice the span isn't selected since it is not a div and the "niece" isn't selected since it is a child of a sibling, not an actual sibling.
{{{
$("#prev ~ div").css("border", "3px groove blue");
}}}
}}}
Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.
|!Name|!Type|!Optional|!Description|h
|selector|String|yes|A string containing a selector expression to match elements against.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.nextAll()</code> method allows us to search through the successors of these elements in the DOM tree and construct a new jQuery object from the matching elements.</p>
<p>The method optionally accepts a selector expression of the same type that we can pass to the <code>$()</code> function. If the selector is supplied, the elements will be filtered by testing whether they match it.</p>
<p>Consider a page with a simple list on it:</p>
<pre>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
</pre>
<p>If we begin at the third item, we can find the elements which come after it:</p>
<pre>$('li.third-item').nextAll().css('background-color', 'red');</pre>
<p>The result of this call is a red background behind items 4 and 5. Since we do not supply a selector expression, these following elements are unequivocally included as part of the object. If we had supplied one, the elements would be tested for a match before they were included.</p></html>
!Examples
* {{multiLine{Locate all the divs after the first and give them a class.
{{{
$("div:first").nextAll().addClass("after");
}}}
}}}
* {{multiLine{Locate all the paragraphs after the second child in the body and give them a class.
{{{
$(":nth-child(1)").nextAll("p").addClass("after");
}}}
}}}
Get all following siblings of each element up to but not including the element matched by the selector.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|yes|A string containing a selector expression to indicate where to stop matching following sibling elements.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.nextUntil()</code> method allows us to search through the successors of these elements in the DOM tree, stopping when it reaches an element matched by the method's argument. The new jQuery object that is returned contains all following siblings up to but not including the one matched by the <code>.nextUntil()</code> selector.</p>
<p>If the selector is not matched or is not supplied, all following siblings will be selected; in these cases it selects the same elements as the <code>.nextAll()</code> method does when no filter selector is provided.</p>
<p>Consider a page with a simple definition list as follows:</p>
<pre>
<dl>
<dt>term 1</dt>
<dd>definition 1-a</dd>
<dd>definition 1-b</dd>
<dd>definition 1-c</dd>
<dd>definition 1-d</dd>
<dt id="term-2">term 2</dt>
<dd>definition 2-a</dd>
<dd>definition 2-b</dd>
<dd>definition 2-c</dd>
<dt>term 3</dt>
<dd>definition 3-a</dd>
<dd>definition 3-b</dd>
</dl>
</pre>
<p>If we begin at the second term, we can find the elements which come after it until a following <code><dt></code>.</p>
<pre>$('#term-2').nextUntil('dt').css('background-color', 'red');</pre>
<p>The result of this call is a red background behind definitions <code>2-a</code>, <code>2-b</code>, and <code>2-c</code>. </p>
</html>
!Examples
* {{multiLine{Find the siblings that follow <dt id="term-2"> up to the next <dt> and give them a red background color.
{{{
$("#term-2").nextUntil("dt")
.css("background-color", "red")
}}}
}}}
Remove elements from the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|no|A string containing a selector expression to match elements against.|
|elements|Elements|no|One or more DOM elements to remove from the matched set.|
|function(index)|Function|no|A function used as a test for each element in the set. this is the current DOM element.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.not()</code> method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; the elements that don't match the selector will be included in the result.</p>
<p>Consider a page with a simple list on it:</p>
<pre>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
</pre>
<p>We can apply this method to the set of list items:</p>
<pre>$('li').not(':even').css('background-color', 'red');</pre>
<p>The result of this call is a red background for items 2 and 4, as they do not match the selector (recall that :even and :odd use 0-based indexing).</p>
<h4>Removing Specific Elements</h4>
<p>The second version of the <code>.not()</code> method allows us to remove elements from the matched set, assuming we have found those elements previously by some other means. For example, suppose our list had an id applied to one of its items:</p>
<pre>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li id="notli">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
</pre>
<p>We can fetch the third list item using the native JavaScript <code>getElementById()</code> function, then remove it from a jQuery object:</p>
<pre>
$('li').not(document.getElementById('notli'))
.css('background-color', 'red');
</pre>
<p>This statement changes the color of items 1, 2, 4, and 5. We could have accomplished the same thing with a simpler jQuery expression, but this technique can be useful when, for example, other libraries provide references to plain DOM nodes.</p>
<p>As of jQuery 1.4, the <code>.not()</code> method can take a function as its argument in the same way that <code>.filter()</code> does. Elements for which the function returns <code>true</code> are excluded from the filtered set; all other elements are included.</p></html>
!Examples
* {{multiLine{Adds a border to divs that are not green or blue.
{{{
$("div").not(".green, #blueone")
.css("border-color", "red");
}}}
}}}
* {{multiLine{Removes the element with the ID "selected" from the set of all paragraphs.
{{{
$("p").not( $("#selected")[0] )
}}}
}}}
* {{multiLine{Removes the element with the ID "selected" from the set of all paragraphs.
{{{
$("p").not("#selected")
}}}
}}}
* {{multiLine{Removes all elements that match "div p.selected" from the total set of all paragraphs.
{{{
$("p").not($("div p.selected"))
}}}
}}}
Selects all elements that are the nth-child of their parent.
|!Name|!Type|!Optional|!Description|h
|index|Number/String|no|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) )|
|Arguments|c
!Description
<html><p>Because jQuery's implementation of <code>:nth-child(n)</code> is strictly derived from the CSS specification, the value of <code>n</code> is "1-indexed", meaning that the counting starts at 1. For all other selector expressions, however, jQuery follows JavaScript's "0-indexed" counting. Therefore, given a single <code><ul></code> containing two <code><li></code>s, <code>$('li:nth-child(1)')</code> selects the first <code><li></code> while <code>$('li:eq(1)')</code> selects the second.</p>
<p>The <code>:nth-child(n)</code> pseudo-class is easily confused with <code>:eq(n)</code>, even though the two can result in dramatically different matched elements. With <code>:nth-child(n)</code>, all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With <code>:eq(n)</code> only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the nth one is selected.</p>
<p>Further discussion of this unusual usage can be found in the <a href="http://www.w3.org/TR/css3-selectors/#nth-child-pseudo">W3C CSS specification</a>.</p>
</html>
!Examples
* {{multiLine{Finds the second li in each matched ul and notes it.
{{{
$("ul li:nth-child(2)").append("<span> - 2nd!</span>");
}}}
}}}
* {{multiLine{This is a playground to see how the selector works with different strings. Notice that this is different from the :even and :odd which have no regard for parent and just filter the list of elements to every other one. The :nth-child, however, counts the index of the child to its particular parent. In any case, it's easier to see than explain so...
{{{
$("button").click(function () {
var str = $(this).text();
$("tr").css("background", "white");
$("tr" + str).css("background", "#ff0000");
$("#inner").text(str);
});
}}}
}}}
Selects odd elements, zero-indexed. See also even.
!Description
<html><p>In particular, note that the <em>0-based indexing</em> means that, counter-intuitively, <code>:odd</code> selects the second element, fourth element, and so on within the matched set.</p></html>
!Examples
* {{multiLine{Finds odd table rows, matching the second, fourth and so on (index 1, 3, 5 etc.).
{{{
$("tr:odd").css("background-color", "#bbbbff");
}}}
}}}
Set the current coordinates of every element in the set of matched elements, relative to the document.
|!Name|!Type|!Optional|!Description|h
|coordinates|Object|no|An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements.|
|function(index, coords)|Function|no|A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties.|
|Arguments|c
!Description
<html><p>The <code>.offset()</code> setter method allows us to reposition an element. The element's position is specified <em>relative to the document</em>. If the element's <code>position</code> style property is currently <code>static</code>, it will be set to <code>relative</code> to allow for this repositioning.</p></html>
!Examples
* {{multiLine{Set the offset of the second paragraph:
{{{
$("p:last").offset({ top: 10, left: 30 });
}}}
}}}
Get the closest ancestor element that is positioned.
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.offsetParent()</code> method allows us to search through the ancestors of these elements in the DOM tree and construct a new jQuery object wrapped around the closest positioned ancestor. An element is said to be positioned if it has a CSS position attribute of <code>relative</code>, <code>absolute</code>, or <code>fixed</code>. This information is useful for calculating offsets for performing animations and placing objects on the page.</p>
<p>Consider a page with a basic nested list on it, with a positioned element:</p>
<pre>
<ul class="level-1">
<li class="item-i">I</li>
<li class="item-ii" style="position: relative;">II
<ul class="level-2">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>
</pre>
<p>If we begin at item A, we can find its positioned ancestor:</p>
<pre>$('li.item-a').offsetParent().css('background-color', 'red');</pre>
<p>This will change the color of list item II, which is positioned.</p>
</html>
!Examples
* {{multiLine{Find the offsetParent of item "A."
{{{
$('li.item-a').offsetParent().css('background-color', 'red');
}}}
}}}
Attach a handler to an event for the elements. The handler is executed at most once per element.
|!Name|!Type|!Optional|!Description|h
|eventType|String|no|A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.|
|eventData|Object|yes|A map of data that will be passed to the event handler.|
|handler(eventObject)|Function|no|A function to execute at the time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is identical to <code>.bind()</code>, except that the handler is unbound after its first invocation. For example:</p>
<pre>$('#foo').one('click', function() {
alert('This will be displayed only once.');
});
</pre>
<p>After the code is executed, a click on the element with ID <code>foo</code> will display the alert. Subsequent clicks will do nothing. This code is equivalent to:</p>
<pre>$('#foo').bind('click', function(event) {
alert('This will be displayed only once.');
$(this).unbind(event);
});
</pre>
<p>In other words, explicitly calling <code>.unbind()</code> from within a regularly-bound handler has exactly the same effect.</p>
</html>
!Examples
* {{multiLine{Tie a one-time click to each div.
{{{
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.");
});
}}}
}}}
* {{multiLine{To display the text of all paragraphs in an alert box the first time each of them is clicked:
{{{
$("p").one("click", function(){
alert( $(this).text() );
});
}}}
}}}
Selects all elements that are the only child of their parent.
!Description
<html><p>If the parent has other child elements, nothing is matched.</p></html>
!Examples
* {{multiLine{Finds the button with no siblings in each matched div and modifies look.
{{{
$("div button:only-child").text("Alone").css("border", "2px blue solid");
}}}
}}}
Get the current computed height for the first element in the set of matched elements, including padding and border.
|!Name|!Type|!Optional|!Description|h
|includeMargin|Boolean|yes|A Boolean indicating whether to include the element's margin in the calculation.|
|Arguments|c
!Description
<html><p>If <code>includeMargin</code> is omitted or <code>false</code>, the padding and border are included in the calculation; if <code>true</code>, the margin is also included.</p>
<p>This method is not applicable to <code>window</code> and <code>document</code> objects; for these, use <code><a href="/height">.height()</a></code> instead.</p>
<p class="image"><img src="/images/0042_04_03.png"/></p></html>
!Examples
* {{multiLine{Get the outerHeight of a paragraph.
{{{
var p = $("p:first");
$("p:last").text( "outerHeight:" + p.outerHeight() + " , outerHeight(true):" + p.outerHeight(true) );
}}}
}}}
Get the current computed width for the first element in the set of matched elements, including padding and border.
|!Name|!Type|!Optional|!Description|h
|includeMargin|Boolean|yes|A Boolean indicating whether to include the element's margin in the calculation.|
|Arguments|c
!Description
<html><p>Returns the width of the element, along with left and right padding, border, and optionally margin, in pixels.</p>
<p>If <code>includeMargin</code> is omitted or <code>false</code>, the padding and border are included in the calculation; if <code>true</code>, the margin is also included.</p>
<p>This method is not applicable to <code>window</code> and <code>document</code> objects; for these, use <code><a href="/width">.width()</a></code> instead.</p>
<p class="image"><img src="/images/0042_04_06.png"/></p></html>
!Examples
* {{multiLine{Get the outerWidth of a paragraph.
{{{
var p = $("p:first");
$("p:last").text( "outerWidth:" + p.outerWidth()+ " , outerWidth(true):" + p.outerWidth(true) );
}}}
}}}
Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|yes|A string containing a selector expression to match elements against.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.parent()</code> method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements. The <code>.parents()</code> and <code>.parent()</code> methods are similar, except that the latter only travels a single level up the DOM tree.</p>
<p>The method optionally accepts a selector expression of the same type that we can pass to the <code>$()</code> function. If the selector is supplied, the elements will be filtered by testing whether they match it.</p>
<p>Consider a page with a basic nested list on it:</p>
<pre>
<ul class="level-1">
<li class="item-i">I</li>
<li class="item-ii">II
<ul class="level-2">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>
</pre>
<p>If we begin at item A, we can find its parents:</p>
<pre>$('li.item-a').parent().css('background-color', 'red');</pre>
<p>The result of this call is a red background for the level-2 list. Since we do not supply a selector expression, the parent element is unequivocally included as part of the object. If we had supplied one, the element would be tested for a match before it was included.</p></html>
!Examples
* {{multiLine{Shows the parent of each element as (parent > child). Check the View Source to see the raw html.
{{{
$("*", document.body).each(function () {
var parentTag = $(this).parent().get(0).tagName;
$(this).prepend(document.createTextNode(parentTag + " > "));
});
}}}
}}}
* {{multiLine{Find the parent element of each paragraph with a class "selected".
{{{
$("p").parent(".selected").css("background", "yellow");
}}}
}}}
Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|yes|A string containing a selector expression to match elements against.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.parents()</code> method allows us to search through the ancestors of these elements in the DOM tree and construct a new jQuery object from the matching elements ordered from immediate parent on up. The <code>.parents()</code> and <code>.parent()</code> methods are similar, except that the latter only travels a single level up the DOM tree.</p>
<p>The method optionally accepts a selector expression of the same type that we can pass to the <code>$()</code> function. If the selector is supplied, the elements will be filtered by testing whether they match it.</p>
<p>Consider a page with a basic nested list on it:</p>
<pre>
<ul class="level-1">
<li class="item-i">I</li>
<li class="item-ii">II
<ul class="level-2">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>
</pre>
<p>If we begin at item A, we can find its ancestors:</p>
<pre>$('li.item-a').parents().css('background-color', 'red');</pre>
<p>The result of this call is a red background for the level-2 list, item II, and the level-1 list (and on up the DOM tree all the way to the <code><html></code> element). Since we do not supply a selector expression, all of the ancestors are part of the returned jQuery object. If we had supplied one, only the matching items among these would be included.</p></html>
!Examples
* {{multiLine{Find all parent elements of each b.
{{{
var parentEls = $("b").parents()
.map(function () {
return this.tagName;
})
.get().join(", ");
$("b").append("<strong>" + parentEls + "</strong>");
}}}
}}}
* {{multiLine{Click to find all unique div parent elements of each span.
{{{
function showParents() {
$("div").css("border-color", "white");
var len = $("span.selected")
.parents("div")
.css("border", "2px red solid")
.length;
$("b").text("Unique div parents: " + len);
}
$("span").click(function () {
$(this).toggleClass("selected");
showParents();
});
}}}
}}}
Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|yes|A string containing a selector expression to indicate where to stop matching ancestor elements.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.parentsUntil()</code> method traverses through the ancestors of these elements until it reaches an element matched by the selector passed in the method's argument. The resulting jQuery object contains all of the ancestors up to but not including the one matched by the <code>.parentsUntil()</code> selector. Consider a page with a basic nested list as follows:</p>
<pre><ul class="level-1">
<li class="item-i">I</li>
<li class="item-ii">II
<ul class="level-2">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>
</pre>
<p>If we begin at item A, we can find its ancestors up to but not including <code><ul class="level-1"></code> as follows:</p>
<pre>$('li.item-a').parentsUntil('.level-1')
.css('background-color', 'red');</pre>
<p>The result of this call is a red background for the level-2 list and the item II. </p>
<p>If the .parentsUntil() selector is not matched, or if no selector is supplied, the returned jQuery object contains all of the previous jQuery object's ancestors. For example, let's say we begin at item A again, but this time we use a selector that is not matched by any of its ancestors:</p>
<pre>$('li.item-a').parentsUntil('.not-here')
.css('background-color', 'red');</pre>
<p>The result of this call is a red background-color style applied to the level-2 list, the item II, the level-1 list, the <code><body></code> element, and the <code><html></code> element.</p>
</html>
!Examples
* {{multiLine{Find the ancestors of <li class="item-a"> up to <ul class="level-1"> and give them a red background color.
{{{
$('li.item-a').parentsUntil('.level-1')
.css('background-color', 'red');
}}}
}}}
Selects all elements of type password.
!Description
<html><p><code>$(':password')</code> is equivalent to <code>$('[type=password]')</code>. As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare <code>$(':password')</code> is equivalent to <code>$('*:password')</code>, so <code>$('input:password')</code> should be used instead. </p></html>
!Examples
* {{multiLine{Finds all password inputs.
{{{
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
}}}
}}}
Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
!Description
<html><p>The <code>.position()</code> method allows us to retrieve the current position of an element <em>relative to the offset parent</em>. Contrast this with <code><a href="/offset">.offset()</a></code>, which retrieves the current position <em>relative to the document</em>. When positioning a new element near another one and within the same containing DOM element, <code>.position()</code> is the more useful.</p>
<p>Returns an object containing the properties <code>top</code> and <code>left</code>.</p></html>
!Examples
* {{multiLine{Access the position of the second paragraph:
{{{
var p = $("p:first");
var position = p.position();
$("p:last").text( "left: " + position.left + ", top: " + position.top );
}}}
}}}
Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|content|String, Element, jQuery|no|An element, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.|
|function(index, html)|Function|no|A function that returns an HTML string to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments.|
|Arguments|c
!Description
<html><p>The <code>.prepend()</code> method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the <em>last</em> child, use <a href="http://api.jquery.com/append/"><code>.append()</code></a>). </p>
<p>The <code>.prepend()</code> and <code><a href="/prependTo">.prependTo()</a></code> methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With<code> .prepend()</code>, the selector expression preceding the method is the container into which the content is inserted. With <code>.prependTo()</code>, on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.</p>
<p>Consider the following HTML:</p>
<pre><h2>Greetings</h2>
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>We can create content and insert it into several elements at once:</p>
<pre>$('.inner').prepend('<p>Test</p>');</pre>
<p>Each <code><div class="inner"></code> element gets this new content:</p>
<pre><h2>Greetings</h2>
<div class="container">
<div class="inner">
<p>Test</p>
Hello
</div>
<div class="inner">
<p>Test</p>
Goodbye
</div>
</div></pre>
<p>We can also select an element on the page and insert it into another:</p>
<pre>$('.container').prepend($('h2'));</pre>
<p>If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):</p>
<pre><div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.</p></html>
!Examples
* {{multiLine{Prepends some HTML to all paragraphs.
{{{
$("p").prepend("<b>Hello </b>");
}}}
}}}
* {{multiLine{Prepends a DOM Element to all paragraphs.
{{{
$("p").prepend(document.createTextNode("Hello "));
}}}
}}}
* {{multiLine{Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
{{{
$("p").prepend( $("b") );
}}}
}}}
Insert every element in the set of matched elements to the beginning of the target.
|!Name|!Type|!Optional|!Description|h
|target|Selector, Element, jQuery|no|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.|
|Arguments|c
!Description
<html><p>The <code><a href="/prepend">.prepend()</a></code> and <code>.prependTo()</code> methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With<code> .prepend()</code>, the selector expression preceding the method is the container into which the content is inserted. With <code>.prependTo()</code>, on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.</p>
<p>Consider the following HTML:</p>
<pre><h2>Greetings</h2>
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>We can create content and insert it into several elements at once:</p>
<pre>$('<p>Test</p>').prependTo('.inner');</pre>
<p>Each inner <code><div></code> element gets this new content:</p>
<pre><h2>Greetings</h2>
<div class="container">
<div class="inner">
<p>Test</p>
Hello
</div>
<div class="inner">
<p>Test</p>
Goodbye
</div>
</div></pre>
<p>We can also select an element on the page and insert it into another:</p>
<pre>$('h2').prependTo($('.container'));</pre>
<p>If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):</p>
<pre><div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.</p></html>
!Examples
* {{multiLine{Prepends all spans to the element with the ID "foo"
{{{
$("span").prependTo("#foo"); // check prepend() examples
}}}
}}}
Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|yes|A string containing a selector expression to match elements against.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.prev()</code> method allows us to search through the predecessors of these elements in the DOM tree and construct a new jQuery object from the matching elements.</p>
<p>The method optionally accepts a selector expression of the same type that we can pass to the <code>$()</code> function. If the selector is supplied, the elements will be filtered by testing whether they match it.</p>
<p>Consider a page with a simple list on it:</p>
<pre>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
</pre>
<p>If we begin at the third item, we can find the element which comes just before it:</p>
<pre>$('li.third-item').prev().css('background-color', 'red');</pre>
<p>The result of this call is a red background behind item 2. Since we do not supply a selector expression, this preceding element is unequivocally included as part of the object. If we had supplied one, the element would be tested for a match before it was included.</p></html>
!Examples
* {{multiLine{Find the very previous sibling of each div.
{{{
var $curr = $("#start");
$curr.css("background", "#f99");
$("button").click(function () {
$curr = $curr.prev();
$("div").css("background", "");
$curr.css("background", "#f99");
});
}}}
}}}
* {{multiLine{For each paragraph, find the very previous sibling that has a class "selected".
{{{
$("p").prev(".selected").css("background", "yellow");
}}}
}}}
Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|yes|A string containing a selector expression to match elements against.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.prevAll()</code> method allows us to search through the predecessors of these elements in the DOM tree and construct a new jQuery object from the matching elements.</p>
<p>The method optionally accepts a selector expression of the same type that we can pass to the <code>$()</code> function. If the selector is supplied, the elements will be filtered by testing whether they match it.</p>
<p>Consider a page with a simple list on it:</p>
<pre>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
</pre>
<p>If we begin at the third item, we can find the elements which come before it:</p>
<pre>$('li.third-item').prevAll().css('background-color', 'red');</pre>
<p>The result of this call is a red background behind items 1 and 2. Since we do not supply a selector expression, these preceding elements are unequivocally included as part of the object. If we had supplied one, the elements would be tested for a match before they were included.</p></html>
!Examples
* {{multiLine{Locate all the divs preceding the last div and give them a class.
{{{
$("div:last").prevAll().addClass("before");
}}}
}}}
Get all preceding siblings of each element up to but not including the element matched by the selector.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|yes|A string containing a selector expression to indicate where to stop matching preceding sibling elements.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.prevUntil()</code> method allows us to search through the predecessors of these elements in the DOM tree, stopping when it reaches an element matched by the method's argument. The new jQuery object that is returned contains all previous siblings up to but not including the one matched by the <code>.prevUntil()</code> selector.</p>
<p>If the selector is not matched or is not supplied, all previous siblings will be selected; in these cases it selects the same elements as the <code>.prevAll()</code> method does when no filter selector is provided.</p>
<p>Consider a page with a simple definition list as follows:</p>
<pre>
<dl>
<dt>term 1</dt>
<dd>definition 1-a</dd>
<dd>definition 1-b</dd>
<dd>definition 1-c</dd>
<dd>definition 1-d</dd>
<dt id="term-2">term 2</dt>
<dd>definition 2-a</dd>
<dd>definition 2-b</dd>
<dd>definition 2-c</dd>
<dt>term 3</dt>
<dd>definition 3-a</dd>
<dd>definition 3-b</dd>
</dl>
</pre>
<p>If we begin at the second term, we can find the elements which come after it until a preceding <code><dt></code>.</p>
<pre>$('#term-2').prevUntil('dt').css('background-color', 'red');</pre>
<p>The result of this call is a red background behind definitions <code>1-a</code>, <code>1-b</code>, <code>1-c</code>, and <code>1-d</code>. </p>
</html>
!Examples
* {{multiLine{Find the siblings that precede <dt id="term-2"> up to the preceding <dt> and give them a red background color.
{{{
$("#term-2").prevUntil("dt")
.css("background-color", "red")
}}}
}}}
Manipulate the queue of functions to be executed on the matched elements.
|!Name|!Type|!Optional|!Description|h
|queueName|String|yes|A string containing the name of the queue. Defaults to fx, the standard effects queue.|
|newQueue|Array|no|An array of functions to replace the current queue contents.|
|queueName|String|yes|A string containing the name of the queue. Defaults to fx, the standard effects queue.|
|callback( next )|Function|no|The new function to add to the queue, with a function to call that will dequeue the next item.|
|Arguments|c
!Description
<html><p>Every element can have one to many queues of functions attached to it by jQuery. In most applications, only one queue (called <code>fx</code>) is used. Queues allow a sequence of actions to be called on an element asynchronously, without halting program execution. The typical example of this is calling multiple animation methods on an element. For example:</p>
<pre>$('#foo').slideUp().fadeIn();</pre>
<p>When this statement is executed, the element begins its sliding animation immediately, but the fading transition is placed on the <code>fx</code> queue to be called only once the sliding transition is complete.</p>
<p>The <code>.queue()</code> method allows us to directly manipulate this queue of functions. Calling <code>.queue()</code> with a callback is particularly useful; it allows us to place a new function at the end of the queue.</p>
<p>This feature is similar to providing a callback function with an animation method, but does not require the callback to be given at the time the animation is performed.</p>
<pre>$('#foo').slideUp();
$('#foo').queue(function() {
alert('Animation complete.');
$(this).dequeue();
});</pre>
<p>This is equivalent to:</p>
<pre>$('#foo').slideUp(function() {
alert('Animation complete.');
});</pre>
<p>Note that when adding a function with <code>.queue()</code>, we should ensure that <code>.dequeue()</code> is eventually called so that the next function in line executes.</p>
<p>In jQuery 1.4 the function that's called is passed in another function, as the first argument, that when called automatically dequeues the next item and keeps the queue moving. You would use it like so:</p>
<pre>$("#test").queue(function(next) {
// Do some stuff...
next();
});</pre></html>
!Examples
* {{multiLine{Queue a custom function.
{{{
$(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();
});
}}}
}}}
* {{multiLine{Set a queue array to delete the 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").queue("fx", []);
$("div").stop();
});
}}}
}}}
Selects all elements of type radio.
!Description
<html><p><code>$(':radio')</code> is equivalent to <code>$('[type=radio]')</code>. As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare <code>$(':radio')</code> is equivalent to <code>$('*:radio')</code>, so <code>$('input:radio')</code> should be used instead. </p>
<p>To select a set of associated radio buttons, you might use: <code>$('input[name=gender]:radio')</code></p></html>
!Examples
* {{multiLine{Finds all radio inputs.
{{{
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
}}}
}}}
Specify a function to execute when the DOM is fully loaded.
|!Name|!Type|!Optional|!Description|h
|handler|Function|no|A function to execute after the DOM is ready.|
|Arguments|c
!Description
<html>
<p>While JavaScript provides the <code>load</code> event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to <code>.ready()</code> is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.</p>
<p>In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the <code>load</code> event instead.</p>
<blockquote><p>The <code>.ready()</code> method is generally incompatible with the <code><body onload=""></code> attribute. If <code>load</code> must be used, either do not use <code>.ready()</code> or use jQuery's <code>.load()</code> method to attach <code>load</code> event handlers to the window or to more specific items, like images.
</p></blockquote>
<p>All three of the following syntaxes are equivalent:</p>
<ul>
<li><code>$(document).ready(handler)</code></li>
<li><code>$().ready(handler)</code> (this is not recommended)</li>
<li><code>$(handler)</code></li>
</ul>
<p>There is also <code>$(document).bind("ready", handler)</code>. This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to <code>.bind("ready")</code> the bound handler will not be executed.</p>
<p>The <code>.ready()</code> method can only be called on a jQuery object matching the current document, so the selector can be omitted.</p>
<p>The <code>.ready()</code> method is typically used with an anonymous function:</p>
<pre>$(document).ready(function() {
// Handler for .ready() called.
});</pre>
<p>If <code>.ready()</code> is called after the DOM has been initialized, the new handler passed in will be executed immediately.</p>
<h4>Aliasing the jQuery Namespace</h4>
<p>When using another JavaScript library, we may wish to call <code><a href="/jQuery.noConflict">$.noConflict()</a></code> to avoid namespace difficulties. When this function is called, the <code>$</code> shortcut is no longer available, forcing us to write <code>jQuery</code> each time we would normally write <code>$</code>. However, the handler passed to the <code>.ready()</code> method can take an argument, which is passed the global <code>jQuery</code> object. This means we can rename the object within the context of our <code>.ready()</code> handler without affecting other code:</p>
<pre>jQuery(document).ready(function($) {
// Code using $ as usual goes here.
});</pre>
</html>
!Examples
* {{multiLine{Display a message when the DOM is loaded.
{{{
$(document).ready(function () {
$("p").text("The DOM is now loaded and can be manipulated.");
});
}}}
}}}
Remove the set of matched elements from the DOM.
|!Name|!Type|!Optional|!Description|h
|selector|String|yes|A selector expression that filters the set of matched elements to be removed.|
|Arguments|c
!Description
<html><p>Similar to <code><a href="/empty">.empty()</a></code>, the <code>.remove()</code> method takes elements out of the DOM. We use <code>.remove()</code> when we want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.</p>
<p>Consider the following HTML:</p>
<pre><div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div></pre>
<p>We can target any element for removal:</p>
<pre>$('.hello').remove();</pre>
<p>This will result in a DOM structure with the <code><div></code> element deleted:</p>
<pre><div class="container">
<div class="goodbye">Goodbye</div>
</div></pre>
<p>If we had any number of nested elements inside <code><div class="hello"></code>, they would be removed, too. Other jQuery constructs such as data or event handlers are erased as well.</p>
<p>We can also include a selector as an optional parameter. For example, we could rewrite the previous DOM removal code as follows:</p>
<pre>$('div').remove('.hello');</pre>
<p>This would result in the same DOM structure:</p>
<pre><div class="container">
<div class="goodbye">Goodbye</div>
</div></pre></html>
!Examples
* {{multiLine{Removes all paragraphs from the DOM
{{{
$("button").click(function () {
$("p").remove();
});
}}}
}}}
* {{multiLine{Removes all paragraphs that contain "Hello" from the DOM
{{{
$("button").click(function () {
$("p").remove(":contains('Hello')");
});
}}}
}}}
Remove an attribute from each element in the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|attributeName|String|no|An attribute to remove.|
|Arguments|c
!Description
<html><p>The <code>.removeAttr()</code> method uses the JavaScript <code>removeAttribute()</code> function, but it has the advantage of being able to be called directly on a jQuery object and it accounts for different attribute naming across browsers.</p></html>
!Examples
* {{multiLine{Clicking the button enables the input next to it.
{{{
$("button").click(function () {
$(this).next().removeAttr("disabled")
.focus()
.val("editable now");
});
}}}
}}}
Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|className|String|yes|A class name to be removed from the class attribute of each matched element.|
|function(index, class)|Function|no|A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments.|
|Arguments|c
!Description
<html><p>If a class name is included as a parameter, then only that class will be removed from the set of matched elements. If no class names are specified in the parameter, all classes will be removed.</p>
<p>More than one class may be removed at a time, separated by a space, from the set of matched elements, like so:</p>
<pre>$('p').removeClass('myClass yourClass')
</pre>
<p>This method is often used with <code>.addClass()</code> to switch elements' classes from one to another, like so:</p>
<pre>$('p').removeClass('myClass noClass').addClass('yourClass');
</pre>
<p>Here, the <code>myClass</code> and <code>noClass</code> classes are removed from all paragraphs, while <code>yourClass</code> is added.</p>
<p>To replace all existing classes with another class, we can use <code>.attr('class', 'newClass')</code> instead.</p>
<p>As of jQuery 1.4, the <code>.removeClass()</code> method allows us to indicate the class to be removed by passing in a function.</p>
<pre>$('li:last').removeClass(function() {
return $(this).prev().attr('class');
});</pre>
<p>This example removes the class name of the penultimate <code><li></code> from the last <code><li></code>.</p>
</html>
!Examples
* {{multiLine{Remove the class 'blue' from the matched elements.
{{{
$("p:even").removeClass("blue");
}}}
}}}
* {{multiLine{Remove the class 'blue' and 'under' from the matched elements.
{{{
$("p:odd").removeClass("blue under");
}}}
}}}
* {{multiLine{Remove all the classes from the matched elements.
{{{
$("p:eq(1)").removeClass();
}}}
}}}
Remove a previously-stored piece of data.
|!Name|!Type|!Optional|!Description|h
|name|String|yes|A string naming the piece of data to delete.|
|Arguments|c
!Description
<html><p>The <code>.removeData()</code> method allows us to remove values that were previously set using <code>.data()</code>. When called with the name of a key, <code>.removeData()</code> deletes that particular value; when called with no arguments, all values are removed.</p></html>
!Examples
* {{multiLine{Set a data store for 2 names then remove one of them.
{{{
$("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"));
}}}
}}}
Replace each target element with the set of matched elements.
!Description
<html><p>The <code>.replaceAll()</code> method is corollary to <code><a href="/replaceWith">.replaceWith()</a></code>, but with the source and target reversed. Consider this DOM structure:</p>
<pre><div class="container">
<div class="inner first">Hello</div>
<div class="inner second">And</div>
<div class="inner third">Goodbye</div>
</div></pre>
<p>We can create an element, then replace other elements with it:</p>
<pre>$('<h2>New heading</h2>').replaceAll('.inner');</pre>
<p>This causes all of them to be replaced:</p>
<pre><div class="container">
<h2>New heading</h2>
<h2>New heading</h2>
<h2>New heading</h2>
</div></pre>
<p>Or, we could select an element to use as the replacement:</p>
<pre>$('.first').replaceAll('.third');</pre>
<p>This results in the DOM structure:</p>
<pre><div class="container">
<div class="inner second">And</div>
<div class="inner first">Hello</div>
</div></pre>
<p>From this example, we can see that the selected element replaces the target by being moved from its old location, not by being cloned.</p></html>
!Examples
* {{multiLine{Replace all the paragraphs with bold words.
{{{
$("<b>Paragraph. </b>").replaceAll("p"); // check replaceWith() examples
}}}
}}}
Replace each element in the set of matched elements with the provided new content.
|!Name|!Type|!Optional|!Description|h
|newContent|String, Element, jQuery|no|The content to insert. May be an HTML string, DOM element, or jQuery object.|
|function|Function|no|A function that returns an HTML string to replace the set of matched elements with.|
|Arguments|c
!Description
<html><p>The <code>.replaceWith()</code> method allows us to remove content from the DOM and insert new content in its place with a single call. Consider this DOM structure:</p>
<pre><div class="container">
<div class="inner first">Hello</div>
<div class="inner second">And</div>
<div class="inner third">Goodbye</div>
</div></pre>
<p>We can replace the second inner <code><div></code> with specified HTML:</p>
<pre>$('.second').replaceWith('<h2>New heading</h2>');</pre>
<p>This results in the structure:</p>
<pre><div class="container">
<div class="inner first">Hello</div>
<h2>New heading</h2>
<div class="inner third">Goodbye</div>
</div></pre>
<p>We could equally target all inner <code><div></code> elements at once:</p>
<pre>$('.inner').replaceWith('<h2>New heading</h2>');</pre>
<p>This causes all of them to be replaced:</p>
<pre><div class="container">
<h2>New heading</h2>
<h2>New heading</h2>
<h2>New heading</h2>
</div></pre>
<p>Or, we could select an element to use as the replacement:</p>
<pre>$('.third').replaceWith($('.first'));</pre>
<p>This results in the DOM structure:</p>
<pre><div class="container">
<div class="inner second">And</div>
<div class="inner first">Hello</div>
</div></pre>
<p>From this example, we can see that the selected element replaces the target by being moved from its old location, not by being cloned.</p>
<p>The <code>.replaceWith()</code> method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the <emphasis role="italics">original</emphasis> jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.</p>
<p>In jQuery 1.4 replaceWith, before, and after will also work on disconnected DOM nodes. For example if you were to do:</p>
<pre>$("<div/>").replaceWith("<p/>");</pre>
<p>Then you would end up with a jQuery set that contains only a paragraph.</p></html>
!Examples
* {{multiLine{On click, replace the button with a div containing the same word.
{{{
$("button").click(function () {
$(this).replaceWith("<div>" + $(this).text() + "</div>");
});
}}}
}}}
* {{multiLine{Replace all the paragraphs with bold words.
{{{
$("p").replaceWith("<b>Paragraph. </b>");
}}}
}}}
* {{multiLine{Replace all the paragraphs with empty div elements.
{{{
$("p").replaceWith(document.createElement("div"));
}}}
}}}
* {{multiLine{On click, replace each paragraph with a jQuery div object that is already in the DOM. Notice it doesn't clone the object but rather moves it to replace the paragraph.
{{{
$("p").click(function () {
$(this).replaceWith($("div"));
});
}}}
}}}
Selects all elements of type reset.
!Description
N/A
!Examples
* {{multiLine{Finds all reset inputs.
{{{
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
}}}
}}}
Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('resize', handler)</code> in the first variation, and <code>.trigger('resize')</code> in the second.</p>
<p>The <code>resize</code> event is sent to the <code>window</code> element when the size of the browser window changes:</p>
<pre>$(window).resize(function() {
$('#log').append('<div>Handler for .resize() called.</div>');
});
</pre>
<p>Now whenever the browser window's size is changed, the message is appended to <div id="log"> one or more times, depending on the browser.</p>
<p>Code in a <code>resize</code> handler should never rely on the number of times the handler is called. Depending on implementation, <code>resize</code> events can be sent continuously as the resizing is in progress (the typical behavior in Internet Explorer and WebKit-based browsers such as Safari and Chrome), or only once at the end of the resize operation (the typical behavior in Firefox).</p>
</html>
!Examples
* {{multiLine{To see the window width while (or after) it is resized, try:
{{{
$(window).resize(function() {
$('body').prepend('<div>' + $(window).width() + '</div>');
});
}}}
}}}
Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('scroll', handler)</code> in the first variation, and <code>.trigger('scroll')</code> in the second.</p>
<p>The <code>scroll</code> event is sent to an element when the user scrolls to a different place in the element. It applies to <code>window</code> objects, but also to scrollable frames and elements with the <code>overflow </code>CSS property set to <code>scroll</code> (or <code>auto</code> when the element's explicit height is less than the height of its contents).</p>
<p>For example, consider the HTML:</p>
<pre><div id="target" style="overflow: scroll; width: 200px; height: 100px;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
</div>
<div id="other">
Trigger the handler
</div>
<div id="log"></div></pre>
<p>The style definition is present to make the target element small enough to be scrollable:</p>
<p class="image"><img src="/images/0042_05_11.png" alt=""/>
</p>
<p>The <code>scroll</code> event handler can be bound to this element:</p>
<pre>$('#target').scroll(function() {
$('#log').append('<div>Handler for .scroll() called.</div>');
});</pre>
<p>Now when the user scrolls the text up or down, one or more messages are appended to <code><div id="log"></div></code>:</p>
<p><span class="output">Handler for .scroll() called.</span></p>
<p>We can trigger the event manually when another element is clicked:</p>
<pre>$('#other').click(function() {
$('#target').scroll();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also append the message.</p>
<p>A <code>scroll</code> event is sent whenever the element's scroll position changes, regardless of the cause. A mouse click or drag on the scroll bar, dragging inside the element, pressing the arrow keys, or using the mouse's scroll wheel could cause this event.</p>
</html>
!Examples
* {{multiLine{To do something when your page is scrolled:
{{{
$("p").clone().appendTo(document.body);
$("p").clone().appendTo(document.body);
$("p").clone().appendTo(document.body);
$(window).scroll(function () {
$("span").css("display", "inline").fadeOut("slow");
});
}}}
}}}
Set the current horizontal position of the scroll bar for each of the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|value|Number|no|An integer indicating the new position to set the scroll bar to.|
|Arguments|c
!Description
<html><p>The horizontal scroll position is the same as the number of pixels that are hidden from view above the scrollable area. Setting the <code>scrollLeft</code> positions the horizontal scroll of each matched element.</p></html>
!Examples
* {{multiLine{Set the scrollLeft of a div.
{{{
$("div.demo").scrollLeft(300);
}}}
}}}
Set the current vertical position of the scroll bar for each of the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|value|Number|no|An integer indicating the new position to set the scroll bar to.|
|Arguments|c
!Description
<html><p>The vertical scroll position is the same as the number of pixels that are hidden from view above the scrollable area. Setting the <code>scrollTop</code> positions the vertical scroll of each matched element.</p></html>
!Examples
* {{multiLine{Set the scrollTop of a div.
{{{
$("div.demo").scrollTop(300);
}}}
}}}
Bind an event handler to the "select" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('select', handler)</code> in the first variation, and <code>.trigger('select')</code> in the second.</p>
<p>The <code>select</code> event is sent to an element when the user makes a text selection inside it. This event is limited to <code><input type="text"></code> fields and <code><textarea></code> boxes.</p>
<p>For example, consider the HTML:</p>
<pre><form>
<input id="target" type="text" value="Hello there" />
</form>
<div id="other">
Trigger the handler
</div></pre>
<p>The event handler can be bound to the text input:</p>
<pre>$('#target').select(function() {
alert('Handler for .select() called.');
});</pre>
<p>Now when any portion of the text is selected, the alert is displayed. Merely setting the location of the insertion point will not trigger the event. We can trigger the event manually when another element is clicked:</p>
<pre>$('#other').click(function() {
$('#target').select();
});</pre>
<p>After this code executes, clicks on the Trigger button will also alert the message:</p>
<p><span class="output">Handler for .select() called.</span></p>
<p>In addition, the default <code>select</code> action on the field will be fired, so the entire text field will be selected.</p>
<blockquote><p>The method for retrieving the current selected text differs from one browser to another. A number of jQuery plug-ins offer cross-platform solutions.</p></blockquote>
</html>
!Examples
* {{multiLine{To do something when text in input boxes is selected:
{{{
$(":input").select( function () {
$("div").text("Something was selected").show().fadeOut(1000);
});
}}}
}}}
* {{multiLine{To trigger the select event on all input elements, try:
{{{
$("input").select();
}}}
}}}
Selects all elements that are selected.
!Description
<html><p>The <code>:selected</code> selector works for <code><option></code> elements. It does not work for checkboxes or radio inputs; use <code>:checked</code> for them.</p></html>
!Examples
* {{multiLine{Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.
{{{
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.trigger('change');
}}}
}}}
A selector representing selector originally passed to jQuery().
!Description
<html><p>Should be used in conjunction with context to determine the exact query used.</p>
<p>The <code>.live()</code> method for binding event handlers uses this property to determine how to perform its searches. Plug-ins which perform similar tasks may also find the property useful. This property contains a string representing the matched set of elements, but if DOM traversal methods have been called on the object, the string may not be a valid jQuery selector expression. For this reason, the value of <code>.selector</code> is generally most useful immediately following the original creation of the object. Consequently, the <code>.live()</code> method should only be used in this scenario. </p></html>
!Examples
* {{multiLine{Determine the selector used.
{{{
$("ul")
.append("<li>" + $("ul").selector + "</li>")
.append("<li>" + $("ul li").selector + "</li>")
.append("<li>" + $("div#foo ul:not([class])").selector + "</li>");
}}}
}}}
* {{multiLine{Collecting elements differently
{{{
$('<div>' + $('ul li.foo').selector + '</div>').appendTo('body'); // "ul li.foo"
$('<div>' + $('ul').find('li').filter('.foo').selector + '</div>').appendTo('body'); // "ul li.filter(.foo)"
}}}
}}}
Encode a set of form elements as a string for submission.
!Description
<html><p>The <code>.serialize()</code> method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:</p>
<pre><form>
<div><input type="text" name="a" value="1" id="a" /></div>
<div><input type="text" name="b" value="2" id="b" /></div>
<div><input type="hidden" name="c" value="3" id="c" /></div>
<div>
<textarea name="d" rows="8" cols="40">4</textarea>
</div>
<div><select name="e">
<option value="5" selected="selected">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select></div>
<div>
<input type="checkbox" name="f" value="8" id="f" />
</div>
<div>
<input type="submit" name="g" value="Submit" id="g" />
</div>
</form></pre>
<p>The <code>.serialize()</code> method can act on a jQuery object that has selected individual form elements, such as <code><input></code>, <code><textarea></code>, and <code><select></code>. However, it is typically easier to select the <code><form></code> tag itself for serialization:</p>
<pre>$('form').submit(function() {
alert($(this).serialize());
return false;
});</pre>
<p>This produces a standard-looking query string:</p>
<pre>a=1&b=2&c=3&d=4&e=5</pre>
<p>Note: Only <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2">"successful controls"</a> are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a <code>name</code> attribute. Data from file select elements is not serialized.</p>
</html>
!Examples
* {{multiLine{Serialize a form to a query string, that could be sent to a server in an Ajax request.
{{{
function showValues() {
var str = $("form").serialize();
$("#results").text(str);
}
$(":checkbox, :radio").click(showValues);
$("select").change(showValues);
showValues();
}}}
}}}
Encode a set of form elements as an array of names and values.
!Description
<html><p>The <code>.serializeArray()</code> method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:</p>
<pre><form>
<div><input type="text" name="a" value="1" id="a" /></div>
<div><input type="text" name="b" value="2" id="b" /></div>
<div><input type="hidden" name="c" value="3" id="c" /></div>
<div>
<textarea name="d" rows="8" cols="40">4</textarea>
</div>
<div><select name="e">
<option value="5" selected="selected">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select></div>
<div>
<input type="checkbox" name="f" value="8" id="f" />
</div>
<div>
<input type="submit" name="g" value="Submit" id="g" />
</div>
</form></pre>
<p>The <code>.serializeArray()</code> method can act on a jQuery object that has selected individual form elements, such as <code><input></code>, <code><textarea></code>, and <code><select></code>. However, it is typically easier to select the <code><form></code> tag itself for serialization:</p>
<pre>$('form').submit(function() {
alert($(this).serializeArray());
return false;
});</pre>
<p>This produces the following data structure:</p>
<pre>[
{
name: a
value: 1
},
{
name: b
value: 2
},
{
name: c
value: 3
},
{
name: d
value: 4
},
{
name: e
value: 5
}
]</pre></html>
!Examples
* {{multiLine{Get the values from a form, iterate through them, and append them to a results display.
{{{
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();
}}}
}}}
Display the matched elements.
|!Name|!Type|!Optional|!Description|h
|duration|String,Number|no|A string or number determining how long the animation will run.|
|callback|Callback|yes|A function to call once the animation is complete.|
|Arguments|c
!Description
<html>
<p>With no parameters, the <code>.show()</code> method is the simplest way to display an element:
</p>
<pre>$('.target').show();
</pre>
<p>The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling <code>.css('display', 'block')</code>, except that the <code>display</code> property is restored to whatever it was initially. If an element has a <code>display</code> value of <code>inline</code>, then is hidden and shown, it will once again be displayed <code>inline</code>.</p>
<p>When a duration is provided, <code>.show()</code> becomes an animation method. The <code>.show()</code> method animates the width, height, and opacity of the matched elements simultaneously.</p>
<p>Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings <code>'fast'</code> and <code>'slow'</code> can be supplied to indicate durations of <code>200</code> and <code>600</code> milliseconds, respectively.</p>
<p>If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but <code>this</code> is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.</p>
<p>We can animate any element, such as a simple image:</p>
<pre><div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
With the element initially hidden, we can show it slowly:
$('#clickme').click(function() {
$('#book').show('slow', function() {
// Animation complete.
});
});</pre>
<p class="image four-across">
<img src="/images/0042_06_01.png" alt=""/>
<img src="/images/0042_06_02.png" alt=""/>
<img src="/images/0042_06_03.png" alt=""/>
<img src="/images/0042_06_04.png" alt=""/>
</p>
</html>
!Examples
* {{multiLine{Animates all hidden paragraphs to show slowly, completing the animation within 600 milliseconds.
{{{
$("button").click(function () {
$("p").show("slow");
});
}}}
}}}
* {{multiLine{Animates all hidden divs to show fastly in order, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one.
{{{
$("#showr").click(function () {
$("div:eq(0)").show("fast", function () {
/* use callee so don't have to name the function */
$(this).next("div").show("fast", arguments.callee);
});
});
$("#hidr").click(function () {
$("div").hide(2000);
});
}}}
}}}
* {{multiLine{Animates all span and input elements to show normally. Once the animation is done, it changes the text.
{{{
function doIt() {
$("span,div").show("normal");
}
/* can pass in function name */
$("button").click(doIt);
$("form").submit(function () {
if ($("input").val() == "yes") {
$("p").show(4000, function () {
$(this).text("Ok, DONE! (now showing)");
});
}
$("span,div").hide("normal");
/* to stop the submit */
return false;
});
}}}
}}}
Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
|!Name|!Type|!Optional|!Description|h
|selector|Selector|yes|A string containing a selector expression to match elements against.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.siblings()</code> method allows us to search through the siblings of these elements in the DOM tree and construct a new jQuery object from the matching elements.</p>
<p>The method optionally accepts a selector expression of the same type that we can pass to the <code>$()</code> function. If the selector is supplied, the elements will be filtered by testing whether they match it.</p>
<p>Consider a page with a simple list on it:</p>
<pre>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
</pre>
<p>If we begin at the third item, we can find its siblings:</p>
<pre>$('li.third-item').siblings().css('background-color', 'red');</pre>
<p>The result of this call is a red background behind items 1, 2, 4, and 5. Since we do not supply a selector expression, all of the siblings are part of the object. If we had supplied one, only the matching items among these four would be included.</p>
<p>The original element is not included among the siblings, which is important to remember when we wish to find all elements at a particular level of the DOM tree.</p></html>
!Examples
* {{multiLine{Find the unique siblings of all yellow li elements in the 3 lists (including other yellow li elements if appropriate).
{{{
var len = $(".hilite").siblings()
.css("color", "red")
.length;
$("b").text(len);
}}}
}}}
* {{multiLine{Find all siblings with a class "selected" of each div.
{{{
$("p").siblings(".selected").css("background", "yellow");
}}}
}}}
Return the number of DOM elements matched by the jQuery object.
!Description
<html>Suppose we had a simple unordered list on the page:
<pre>
<ul>
<li>foo</li>
<li>bar</li>
</ul>
</pre>
<p>We can determine the number of list items by calling <code>.size()</code>:</p>
<pre>alert('Size: ' + $('li').size());</pre>
<p>This will alert the count of items:</p>
<p><span class="output">Size: 2</span></p>
<p>The <a href="/length/">.length</a> property is a slightly faster way to get this information.</p>
</html>
!Examples
* {{multiLine{Count the divs. Click to add more.
{{{
$(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
}}}
}}}
Reduce the set of matched elements to a subset specified by a range of indices.
|!Name|!Type|!Optional|!Description|h
|start|Integer|no|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.|
|end|Integer|yes|An integer indicating the 0-based position before which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set.|
|Arguments|c
!Description
<html><p>Given a jQuery object that represents a set of DOM elements, the <code>.slice()</code> method constructs a new jQuery object from a subset of the matching elements. The supplied <code>start</code> index identifies the position of one of the elements in the set; if <code>end</code> is omitted, all elements after this one will be included in the result.</p>
<p>Consider a page with a simple list on it:</p>
<pre>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
</pre>
<p>We can apply this method to the set of list items:</p>
<pre>$('li').slice(2).css('background-color', 'red');</pre>
<p>The result of this call is a red background for items 3, 4, and 5. Note that the supplied index is zero-based, and refers to the position of elements within the jQuery object, not within the DOM tree.</p>
<p>The end parameter allows us to limit the selected range even further. For example:</p>
<pre>$('li').slice(2, 4).css('background-color', 'red');</pre>
<p>Now only items 3 and 4 are selected. The index is once again zero-based; the range extends up to but not including the specified index.</p>
<h4>Negative Indices</h4>
<p>The jQuery <code>.slice()</code> method is patterned after the JavaScript .slice() method for arrays. One of the features that it mimics is the ability for negative numbers to be passed as either the <code>start</code> or <code>end</code> parameter. If a negative number is provided, this indicates a position starting from the end of the set, rather than the beginning. For example:</p>
<pre>$('li').slice(-2, -1).css('background-color', 'red');</pre>
<p>This time only list item 4 is turned red, since it is the only item in the range between two from the end (<code>-2</code>) and one from the end (<code>-1</code>).</p></html>
!Examples
* {{multiLine{Turns divs yellow based on a random slice.
{{{
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);
}}}
}}}
* {{multiLine{Selects all paragraphs, then slices the selection to include only the first element.
{{{
$("p").slice(0, 1).wrapInner("<b></b>");
}}}
}}}
* {{multiLine{Selects all paragraphs, then slices the selection to include only the first and second element.
{{{
$("p").slice(0, 2).wrapInner("<b></b>");
}}}
}}}
* {{multiLine{Selects all paragraphs, then slices the selection to include only the second element.
{{{
$("p").slice(1, 2).wrapInner("<b></b>");
}}}
}}}
* {{multiLine{Selects all paragraphs, then slices the selection to include only the second and third element.
{{{
$("p").slice(1).wrapInner("<b></b>");
}}}
}}}
* {{multiLine{Selects all paragraphs, then slices the selection to include only the third element.
{{{
$("p").slice(-1).wrapInner("<b></b>");
}}}
}}}
Display the matched elements with a sliding motion.
|!Name|!Type|!Optional|!Description|h
|duration|String,Number|yes|A string or number determining how long the animation will run.|
|callback|Callback|yes|A function to call once the animation is complete.|
|Arguments|c
!Description
<html>
<p>The <code>.slideDown()</code> method animates the height of the matched elements. This causes lower parts of the page to slide down, making way for the revealed items.</p>
<p>Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings <code>'fast'</code> and <code>'slow'</code> can be supplied to indicate durations of <code>200</code> and <code>600</code> milliseconds, respectively. If any other string is supplied, or if the <code>duration</code> parameter is omitted, the default duration of <code>400</code> milliseconds is used.</p>
<p>If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but <code>this</code> is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.</p>
<p>We can animate any element, such as a simple image:</p>
<pre><div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" /></pre>
<p>With the element initially hidden, we can show it slowly:</p>
<pre>$('#clickme').click(function() {
$('#book').slideDown('slow', function() {
// Animation complete.
});
});</pre>
<p class="image four-across">
<img src="/images/0042_06_17.png" alt=""/>
<img src="/images/0042_06_18.png" alt=""/>
<img src="/images/0042_06_19.png" alt=""/>
<img src="/images/0042_06_20.png" alt=""/>
</p>
</html>
!Examples
* {{multiLine{Animates all divs to slide down and show themselves over 600 milliseconds.
{{{
$(document.body).click(function () {
if ($("div:first").is(":hidden")) {
$("div").slideDown("slow");
} else {
$("div").hide();
}
});
}}}
}}}
* {{multiLine{Animates all inputs to slide down, completing the animation within 1000 milliseconds. Once the animation is done, the input look is changed especially if it is the middle input which gets the focus.
{{{
$("div").click(function () {
$(this).css({ borderStyle:"inset", cursor:"wait" });
$("input").slideDown(1000,function(){
$(this).css("border", "2px red inset")
.filter(".middle")
.css("background", "yellow")
.focus();
$("div").css("visibility", "hidden");
});
});
}}}
}}}
Display or hide the matched elements with a sliding motion.
|!Name|!Type|!Optional|!Description|h
|duration|String,Number|yes|A string or number determining how long the animation will run.|
|callback|Callback|yes|A function to call once the animation is complete.|
|Arguments|c
!Description
<html>
<p>The <code>.slideToggle()</code> method animates the height of the matched elements. This causes lower parts of the page to slide up or down, appearing to reveal or conceal the items. If the element is initially displayed, it will be hidden; if hidden, it will be shown. The <code>display</code> property is saved and restored as needed. If an element has a <code>display</code> value of <code>inline</code>, then is hidden and shown, it will once again be displayed <code>inline</code>. When the height reaches 0 after a hiding animation, the <code>display</code> style property is set to <code>none</code> to ensure that the element no longer affects the layout of the page.</p>
<p>Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings <code>'fast'</code> and <code>'slow'</code> can be supplied to indicate durations of <code>200</code> and <code>600</code> milliseconds, respectively.</p>
<p>If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but <code>this</code> is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.</p>
<p>We can animate any element, such as a simple image:</p>
<pre><div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" /></pre>
<p>We will cause <code>.slideToggle()</code> to be called when another element is clicked:</p>
<pre>$('#clickme').click(function() {
$('#book').slideToggle('slow', function() {
// Animation complete.
});
});
</pre>
<p>With the element initially shown, we can hide it slowly with the first click:</p>
<p class="image four-across">
<img src="/images/0042_06_25.png" alt=""/>
<img src="/images/0042_06_26.png" alt=""/>
<img src="/images/0042_06_27.png" alt=""/>
<img src="/images/0042_06_28.png" alt=""/>
</p>
<p>A second click will show the element once again:</p>
<p class="image four-across">
<img src="/images/0042_06_29.png" alt=""/>
<img src="/images/0042_06_30.png" alt=""/>
<img src="/images/0042_06_31.png" alt=""/>
<img src="/images/0042_06_32.png" alt=""/>
</p>
</html>
!Examples
* {{multiLine{Animates all paragraphs to slide up or down, completing the animation within 600 milliseconds.
{{{
$("button").click(function () {
$("p").slideToggle("slow");
});
}}}
}}}
* {{multiLine{Animates divs between dividers with a toggle that makes some appear and some disappear.
{{{
$("#aa").click(function () {
$("div:not(.still)").slideToggle("slow", function () {
var n = parseInt($("span").text(), 10);
$("span").text(n + 1);
});
});
}}}
}}}
Hide the matched elements with a sliding motion.
|!Name|!Type|!Optional|!Description|h
|duration|String,Number|yes|A string or number determining how long the animation will run.|
|callback|Callback|yes|A function to call once the animation is complete.|
|Arguments|c
!Description
<html>
<p>The <code>.slideUp()</code> method animates the height of the matched elements. This causes lower parts of the page to slide up, appearing to conceal the items. Once the height reaches 0, the <code>display</code> style property is set to <code>none</code> to ensure that the element no longer affects the layout of the page.</p>
<p>Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings <code>'fast'</code> and <code>'slow'</code> can be supplied to indicate durations of <code>200</code> and <code>600</code> milliseconds, respectively. If any other string is supplied, or if the <code>duration</code> parameter is omitted, the default duration of <code>400</code> milliseconds is used.</p>
<p>If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but <code>this</code> is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.</p>
<p>We can animate any element, such as a simple image:</p>
<pre><div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" /></pre>
<p>With the element initially shown, we can hide it slowly:</p>
<pre>$('#clickme').click(function() {
$('#book').slideUp('slow', function() {
// Animation complete.
});
});
</pre>
<p class="image four-across">
<img src="/images/0042_06_21.png" alt=""/>
<img src="/images/0042_06_22.png" alt=""/>
<img src="/images/0042_06_23.png" alt=""/>
<img src="/images/0042_06_24.png" alt=""/>
</p>
</html>
!Examples
* {{multiLine{Animates all divs to slide up, completing the animation within 400 milliseconds.
{{{
$(document.body).click(function () {
if ($("div:first").is(":hidden")) {
$("div").show("slow");
} else {
$("div").slideUp();
}
});
}}}
}}}
* {{multiLine{Animates the parent paragraph to slide up, completing the animation within 200 milliseconds. Once the animation is done, it displays an alert.
{{{
$("button").click(function () {
$(this).parent().slideUp("slow", function () {
$("#msg").text($("button", this).text() + " has completed.");
});
});
}}}
}}}
Stop the currently-running animation on the matched elements.
|!Name|!Type|!Optional|!Description|h
|clearQueue|Boolean|yes|A Boolean indicating whether to remove queued animation as well. Defaults to false.|
|jumpToEnd|Boolean|yes|A Boolean indicating whether to complete the current animation immediately. Defaults to false.|
|Arguments|c
!Description
<html>
<p>When <code>.stop()</code> is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with <code>.slideUp()</code> when <code>.stop()</code> is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called.</p>
<p>If more than one animation method is called on the same element, the later animations are placed in the effects queue for the element. These animations will not begin until the first one completes. When <code>.stop()</code> is called, the next animation in the queue begins immediately. If the <code>clearQueue</code> parameter is provided with a value of <code>true</code>, then the rest of the animations in the queue are removed and never run.</p>
<p>If the <code>jumpToEnd</code> property is provided with a value of <code>true</code>, the current animation stops, but the element is immediately given its target values for each CSS property. In our above <code>.slideUp()</code> example, the element would be immediately hidden. The callback function is then immediately called, if provided.</p>
<p>The usefulness of the <code>.stop()</code> method is evident when we need to animate an element on <code>mouseenter</code> and <code>mouseleave</code>:</p>
<pre><div id="hoverme">
Hover me
<img id="hoverme" src="book.png" alt="" width="100" height="123" />
</div></pre>
<p>We can create a nice fade effect without the common problem of multiple queued animations by adding <code>.stop(true, true)</code> to the chain:</p>
<pre>$('#hoverme-stop-2').hover(function() {
$(this).find('img').stop(true, true).fadeOut();
}, function() {
$(this).find('img').stop(true, true).fadeIn();
});</pre>
<blockquote><p>Animations may be stopped globally by setting the property <code>$.fx.off</code> to <code>true</code>. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.</p></blockquote>
</html>
!Examples
* {{multiLine{Click the Go button once to start the animation, then click the STOP button to stop it where it's currently positioned. Another option is to click several buttons to queue them up and see that stop just kills the currently playing one.
{{{
// 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);
});
}}}
}}}
Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute each time the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('submit', handler)</code> in the first variation, and <code>.trigger('submit')</code> in the second.</p>
<p>The <code>submit</code> event is sent to an element when the user is attempting to submit a form. It can only be attached to <code><form></code> elements. Forms can be submitted either by clicking an explicit <code><input type="submit"></code>, <code><input type="image"></code>, or <code><button type="submit"></code>, or by pressing <kbd>Enter</kbd> when certain form element has focus.</p>
<blockquote><p>Depending on the browser, the Enter key may only cause a form submission if the form has exactly one text field, or only when there is a submit button present. The interface should not rely on a particular behavior for this key unless the issue is forced by observing the keypress event for presses of the Enter key.</p></blockquote>
<p>For example, consider the HTML:</p>
<pre><form id="target" action="destination.html">
<input type="text" value="Hello there" />
<input type="submit" value="Go" />
</form>
<div id="other">
Trigger the handler
</div></pre>
<p>The event handler can be bound to the form:</p>
<pre>$('#target').submit(function() {
alert('Handler for .submit() called.');
return false;
});</pre>
<p>Now when the form is submitted, the message is alerted. This happens prior to the actual submission, so we can cancel the submit action by calling <code>.preventDefault()</code> on the event object or by returning <code>false</code> from our handler. We can trigger the event manually when another element is clicked:</p>
<pre>$('#other').click(function() {
$('#target').submit();
});</pre>
<p>After this code executes, clicks on <span class="output">Trigger the handler</span> will also display the message. In addition, the default <code>submit</code> action on the form will be fired, so the form will be submitted.</p>
<p>The JavaScript <code>submit</code> event does not bubble in Internet Explorer. However, scripts that rely on event delegation with the <code>submit</code> event will work consistently across browsers as of jQuery 1.4, which has normalized the event's behavior. </p>
</html>
!Examples
* {{multiLine{If you'd like to prevent forms from being submitted unless a flag variable is set, try:
{{{
$("form").submit(function() {
if ($("input:first").val() == "correct") {
$("span").text("Validated...").show();
return true;
}
$("span").text("Not valid!").show().fadeOut(1000);
return false;
});
}}}
}}}
* {{multiLine{If you'd like to prevent forms from being submitted unless a flag variable is set, try:
{{{
$("form").submit( function () {
return this.some_flag_variable;
} );
}}}
}}}
* {{multiLine{To trigger the submit event on the first form on the page, try:
{{{
$("form:first").submit();
}}}
}}}
Set the content of each element in the set of matched elements to the specified text.
|!Name|!Type|!Optional|!Description|h
|textString|String|no|A string of text to set as the content of each matched element.|
|function(index, text)|Function|no|A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.|
|Arguments|c
!Description
<html><p>Unlike the <code>.html()</code> method, <code>.text()</code> can be used in both XML and HTML documents. </p>
<p>We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method <code>.createTextNode()</code>, which replaces special characters with their HTML entity equivalents (such as <code>&lt;</code> for <code><</code>). Consider the following HTML:</p>
<pre><div class="demo-container">
<div class="demo-box">Demonstration Box</div>
<ul>
<li>list item 1</li>
<li>list <strong>item</strong> 2</li>
</ul>
</div>
</pre>
<p>The code <code>$('div.demo-container').text('<p>This is a test.</p>');</code> will produce the following DOM output:</p>
<pre><div class="demo-container">
&lt;p&gt;This is a test.&lt;/p&gt;
</div></pre>
<p>It will appear on a rendered page as though the tags were exposed, like this:</p>
<pre><p>This is a test</p></pre>
<p>The <code>.text()</code> method cannot be used on input elements. For input field text, use the <a href="/val">.val()</a> method.</p>
<p>As of jQuery 1.4, the <code>.text()</code> method allows us to set the text content by passing in a function.</p>
<pre>$('ul li').text(function(index) {
return 'item number ' + (index + 1);
});</pre>
<p>Given an unordered list with three <code><li></code> elements, this example will produce the following DOM output:</p>
<pre><ul>
<li>item number 1</li>
<li>item number 2</li>
<li>item number 3</li>
</ul>
</pre>
</html>
!Examples
* {{multiLine{Add text to the paragraph (notice the bold tag is escaped).
{{{
$("p").text("<b>Some</b> new text.");
}}}
}}}
Retrieve all the DOM elements contained in the jQuery set, as an array.
!Description
<html><p><code>.toArray()</code> returns all of the elements in the jQuery set:</p>
<pre>alert($('li').toArray());</pre>
<p>All of the matched DOM nodes are returned by this call, contained in a standard array:</p>
<p><span class="result">[<li id="foo">, <li id="bar">]</span></p></html>
!Examples
* {{multiLine{Selects all divs in the document and returns the DOM Elements as an Array, then uses the built-in reverse-method to reverse that 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() );
}}}
}}}
Display or hide the matched elements.
|!Name|!Type|!Optional|!Description|h
|duration|String,Number|yes|A string or number determining how long the animation will run.|
|callback|Callback|yes|A function to call once the animation is complete.|
|showOrHide|Boolean|no|A Boolean indicating whether to show or hide the elements.|
|Arguments|c
!Description
<html>
<![CDATA[<p>With no parameters, the <code>.toggle()</code> method simply toggles the visibility of elements:</p>
<pre>$('.target').toggle();
</pre>
<p>The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS <code>display</code> property. If the element is initially displayed, it will be hidden; if hidden, it will be shown. The <code>display</code> property is saved and restored as needed. If an element has a <code>display</code> value of <code>inline</code>, then is hidden and shown, it will once again be displayed <code>inline</code>.</p>
<p>When a duration is provided, <code>.toggle()</code> becomes an animation method. The <code>.toggle()</code> method animates the width, height, and opacity of the matched elements simultaneously. When these properties reach 0 after a hiding animation, the <code>display</code> style property is set to <code>none</code> to ensure that the element no longer affects the layout of the page.</p>
<p>Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings <code>'fast'</code> and <code>'slow'</code> can be supplied to indicate durations of <code>200</code> and <code>600</code> milliseconds, respectively.</p>
<p>If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but <code>this</code> is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.</p>
<p>We can animate any element, such as a simple image:</p>
<pre><div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
</pre>
<p>We will cause <code>.toggle()</code> to be called when another element is clicked:</p>
<pre>$('#clickme').click(function() {
$('#book').toggle('slow', function() {
// Animation complete.
});
});
</pre>
<p>With the element initially shown, we can hide it slowly with the first click:
</p>
<p class="image">
<img src="0042_06_09.png" alt="" />
<img src="0042_06_10.png" alt="" />
<img src="0042_06_11.png" alt="" />
<img src="0042_06_12.png" alt="" />
</p>
<p>A second click will show the element once again:</p>
<p class="image"><img src="0042_06_13.png" alt="" />
<img src="0042_06_14.png" alt="" />
<img src="0042_06_15.png" alt="" />
<img src="0042_06_16.png" alt="" />
</p>
<p>The second version of the method accepts a Boolean parameter. If this parameter is <code>true</code>, then the matched elements are shown; if <code>false</code>, the elements are hidden. In essence, the statement:
</p>
<pre>$('#foo').toggle(showOrHide);
is equivalent to:
if (showOrHide) {
$('#foo').show();
}
else {
$('#foo').hide();
}
</pre>
]]>
</html>
!Examples
* {{multiLine{Toggles all paragraphs.
{{{
$("button").click(function () {
$("p").toggle();
});
}}}
}}}
* {{multiLine{Animates all paragraphs to be shown if they are hidden and hidden if they are visible, completing the animation within 600 milliseconds.
{{{
$("button").click(function () {
$("p").toggle("slow");
});
}}}
}}}
* {{multiLine{Shows all paragraphs, then hides them all, back and forth.
{{{
var flip = 0;
$("button").click(function () {
$("p").toggle( flip++ % 2 == 0 );
});
}}}
}}}
Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
|!Name|!Type|!Optional|!Description|h
|className|String|no|One or more class names (separated by spaces) to be toggled for each element in the matched set.|
|className|String|no|One or more class names (separated by spaces) to be toggled for each element in the matched set.|
|switch|Boolean|no|A boolean value to determine whether the class should be added or removed.|
|function(index, class)|Function|no|A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set and the old class value as arguments.|
|switch|Boolean|yes|A boolean value to determine whether the class should be added or removed.|
|Arguments|c
!Description
<html><p>This method takes one or more class names as its parameter. In the first version, if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added. For example, we can apply <code>.toggleClass()</code> to a simple <code><div></code>: </p>
<pre><div class="tumble">Some text.</div>
</pre>
<p>The first time we apply <code>$('div.tumble').toggleClass('bounce')</code>, we get the following:</p>
<pre><div class="tumble bounce">Some text.</div>
</pre>
<p>The second time we apply <code>$('div.tumble').toggleClass('bounce')</code>, the <code><div></code> class is returned to the single <code>tumble</code> value:</p>
<pre><div class="tumble">Some text.</div></pre>
<p>Applying <code>.toggleClass('bounce spin')</code> to the same <code><div></code> alternates between <code><div class="tumble bounce spin"></code> and <code><div class="tumble"></code>.</p>
<p>The second version of <code>.toggleClass()</code> uses the second parameter for determining whether the class should be added or removed. If this parameter's value is <code>true</code>, then the class is added; if <code>false</code>, the class is removed. In essence, the statement:</p>
<pre>$('#foo').toggleClass(className, addOrRemove);</pre>
<p>is equivalent to:</p>
<pre>if (addOrRemove) {
$('#foo').addClass(className);
}
else {
$('#foo').removeClass(className);
}
</pre>
<p>As of jQuery 1.4, the <code>.toggleClass()</code> method allows us to indicate the class name to be toggled by passing in a function.</p>
<pre>$('div.foo').toggleClass(function() {
if ($(this).parent().is('.bar')) {
return 'happy';
} else {
return 'sad';
}
});</pre>
<p>This example will toggle the <code>happy</code> class for <code><div class="foo"></code> elements if their parent element has a class of <code>bar</code>; otherwise, it will toggle the <code>sad</code> class.</p>
</html>
!Examples
* {{multiLine{Toggle the class 'highlight' when a paragraph is clicked.
{{{
$("p").click(function () {
$(this).toggleClass("highlight");
});
}}}
}}}
* {{multiLine{Add the "highlight" class to the clicked paragraph on every third click of that paragraph, remove it every first and second click.
{{{
var count = 0;
$("p").each(function() {
var $thisParagraph = $(this);
var count = 0;
$thisParagraph.click(function() {
count++;
$thisParagraph.find("span").text('clicks: ' + count);
$thisParagraph.toggleClass("highlight", count % 3 == 0);
});
});
}}}
}}}
Execute all handlers and behaviors attached to the matched elements for the given event type.
|!Name|!Type|!Optional|!Description|h
|eventType|String|no|A string containing a JavaScript event type, such as click or submit.|
|extraParameters|Array|no|An array of additional parameters to pass along to the event handler.|
|Arguments|c
!Description
<html>
<p>Any event handlers attached with <code>.bind()</code> or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the <code>.trigger()</code> method. A call to <code>.trigger()</code> executes the handlers in the same order they would be if the event were triggered naturally by the user:</p>
<pre>$('#foo').bind('click', function() {
alert($(this).text());
});
$('#foo').trigger('click');</pre>
<p>While <code>.trigger()</code> simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.</p>
<p>When we define a custom event type using the <code>.bind()</code> method, the second argument to <code>.trigger()</code> can become useful. For example, suppose we have bound a handler for the <code>custom</code> event to our element instead of the built-in <code>click</code> event as we did above:</p>
<pre>$('#foo').bind('custom', function(event, param1, param2) {
alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);
</pre>
<p>The event object is always passed as the first parameter to an event handler, but if additional parameters are specified during a <code>.trigger()</code> call as they are here, these parameters will be passed along to the handler as well.</p>
<p>Note the difference between the extra parameters we're passing here and the <code>eventData</code> parameter to the <a href="/bind/">.bind()</a> method. Both are mechanisms for passing information to an event handler, but the <code>extraParameters</code> argument to <code>.trigger()</code> allows information to be determined at the time the event is triggered, while the <code>eventData</code> argument to <code>.bind()</code> requires the information to be already computed at the time the handler is bound.</p>
</html>
!Examples
* {{multiLine{Clicks to button #2 also trigger a click for button #1.
{{{
$("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);
}
}}}
}}}
* {{multiLine{To submit the first form without using the submit() function, try:
{{{
$("form:first").trigger("submit")
}}}
}}}
* {{multiLine{To submit the first form without using the submit() function, try:
{{{
var event = jQuery.Event("submit");
$("form:first").trigger(event);
if ( event.isDefaultPrevented() ) {
// Perform an action...
}
}}}
}}}
* {{multiLine{To pass arbitrary data to an event:
{{{
$("p").click( function (event, a, b) {
// when a normal click fires, a and b are undefined
// for a trigger like below a refers to "foo" and b refers to "bar"
} ).trigger("click", ["foo", "bar"]);
}}}
}}}
* {{multiLine{To pass arbitrary data through an event object:
{{{
var event = jQuery.Event("logged");
event.user = "foo";
event.pass = "bar";
$("body").trigger(event);
}}}
}}}
* {{multiLine{Alternate way to pass data through an event object:
{{{
$("body").trigger({
type:"logged",
user:"foo",
pass:"bar"
});
}}}
}}}
Execute all handlers attached to an element for an event.
|!Name|!Type|!Optional|!Description|h
|eventType|String|no|A string containing a JavaScript event type, such as click or submit.|
|extraParameters|Array|no|An array of additional parameters to pass along to the event handler.|
|Arguments|c
!Description
<html>
<p>The <code>.triggerHandler()</code> method behaves similarly to <code>.trigger()</code>, with the following exceptions:</p>
<ul>
<li>The <code>.triggerHandler()</code> method does not cause the default behavior of an event to occur (such as a form submission).</li>
<li>While <code>.trigger()</code> will operate on all elements matched by the jQuery object, <code>.triggerHandler()</code> only affects the first matched element.</li>
<li>Events created with <code>.triggerHandler()</code> do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.</li>
<li>Instead of returning the jQuery object (to allow chaining), <code>.triggerHandler()</code> returns whatever value was returned by the last handler it caused to be executed. If no handlers are triggered, it returns <code>undefined</code></li>
</ul>
<p>For more information on this method, see the discussion for <code><a href="/trigger">.trigger()</a></code>.</p>
</html>
!Examples
* {{multiLine{If you called .triggerHandler() on a focus event - the browser's default focus action would not be triggered, only the event handlers bound to the focus event.
{{{
$("#old").click(function(){
$("input").trigger("focus");
});
$("#new").click(function(){
$("input").triggerHandler("focus");
});
$("input").focus(function(){
$("<span>Focused!</span>").appendTo("body").fadeOut(1000);
});
}}}
}}}
Remove a previously-attached event handler from the elements.
|!Name|!Type|!Optional|!Description|h
|eventType|String|no|A string containing a JavaScript event type, such as click or submit.|
|handler(eventObject)|Function|no|The function that is to be no longer executed.|
|event|Object|no|A JavaScript event object as passed to an event handler.|
|Arguments|c
!Description
<html>
<p>Any handler that has been attached with <code>.bind()</code> can be removed with <code>.unbind()</code>. In the simplest case, with no arguments, <code>.unbind()</code> removes all handlers attached to the elements:</p>
<pre>$('#foo').unbind();</pre>
<p>This version removes the handlers regardless of type. To be more precise, we can pass an event type:</p>
<pre>$('#foo').unbind('click');</pre>
<p>By specifying the <code>click</code> event type, only handlers for that event type will be unbound. This approach can still have negative ramifications if other scripts might be attaching behaviors to the same element, however. Robust and extensible applications typically demand the two-argument version for this reason:</p>
<pre>var handler = function() {
alert('The quick brown fox jumps over the lazy dog.');
};
$('#foo').bind('click', handler);
$('#foo').unbind('click', handler);
</pre>
<p>By naming the handler, we can be assured that no other functions are caught in the crossfire. Note that the following will <em>not</em> work:</p>
<pre>$('#foo').bind('click', function() {
alert('The quick brown fox jumps over the lazy dog.');
});
$('#foo').unbind('click', function() {
alert('The quick brown fox jumps over the lazy dog.');
});</pre>
<p>Even though the two functions are identical in content, they are created separately and so JavaScript is free to keep them as distinct function objects. To unbind a particular handler, we need a reference to that function and not a different one that happens to do the same thing.</p>
<h4>Using Namespaces</h4>
<p>Instead of maintaining references to handlers in order to unbind them, we can namespace the events and use this capability to narrow the scope of our unbinding actions. As shown in the discussion for the <code>.bind()</code> method, namespaces are defined by using a period (<code>.</code>) character when binding a handler:</p>
<pre>$('#foo').bind('click.myEvents', handler);</pre>
<p>When a handler is bound in this fashion, we can still unbind it the normal way:</p>
<pre>$('#foo').unbind('click');</pre>
<p>However, if we want to avoid affecting other handlers, we can be more specific:</p>
<pre>$('#foo').unbind('click.myEvents');</pre>
<p>If multiple namespaced handlers are bound, we can unbind them at once:</p>
<pre>$('#foo').unbind('click.myEvents.yourEvents');</pre>
<p>This syntax is similar to that used for CSS class selectors; they are not hierarchical. This method call is thus the same as:</p>
<pre>$('#foo').unbind('click.yourEvents.myEvents');</pre>
<p>We can also unbind all of the handlers in a namespace, regardless of event type:</p>
<pre>$('#foo').unbind('.myEvents');</pre>
<p>It is particularly useful to attach namespaces to event bindings when we are developing plug-ins or otherwise writing code that may interact with other event-handling code in the future.</p>
<h4>Using the Event Object</h4>
<p>The second form of the <code>.unbind()</code> method is used when we wish to unbind a handler from within itself. For example, suppose we wish to trigger an event handler only three times:</p>
<pre>var timesClicked = 0;
$('#foo').bind('click', function(event) {
alert('The quick brown fox jumps over the lazy dog.');
timesClicked++;
if (timesClicked >= 3) {
$(this).unbind(event);
}
});
</pre>
<p>The handler in this case must take a parameter, so that we can capture the event object and use it to unbind the handler after the third click. The event object contains the context necessary for <code>.unbind()</code> to know which handler to remove.
This example is also an illustration of a closure. Since the handler refers to the <code>timesClicked</code> variable, which is defined outside the function, incrementing the variable has an effect even between invocations of the handler.</p>
</html>
!Examples
* {{multiLine{Can bind and unbind events to the colored button.
{{{
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...");
});
}}}
}}}
* {{multiLine{To unbind all events from all paragraphs, write:
{{{
$("p").unbind()
}}}
}}}
* {{multiLine{To unbind all click events from all paragraphs, write:
{{{
$("p").unbind( "click" )
}}}
}}}
* {{multiLine{To unbind just one previously bound handler, pass the function in as the second argument:
{{{
var foo = function () {
// code to handle some kind of event
};
$("p").bind("click", foo); // ... now foo will be called when paragraphs are clicked ...
$("p").unbind("click", foo); // ... foo will no longer be called.
}}}
}}}
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.
|!Name|!Type|!Optional|!Description|h
|selector|String|no|A selector which will be used to filter the event results.|
|eventType|String|no|A string containing a JavaScript event type, such as "click" or "keydown"|
|selector|String|no|A selector which will be used to filter the event results.|
|eventType|String|no|A string containing a JavaScript event type, such as "click" or "keydown"|
|handler|Function|no|A function to execute at the time the event is triggered.|
|Arguments|c
!Description
<html>
<p>Undelegate is a way of removing event handlers that have been bound using <a href="/delegate">.delegate()</a>. It works virtually identically to <a href="/die">.die()</a> with the addition of a selector filter argument (which is required for delegation to work).</p>
</html>
!Examples
* {{multiLine{Can bind and unbind events to the colored button.
{{{
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...");
});
}}}
}}}
* {{multiLine{To unbind all delegated events from all paragraphs, write:
{{{
$("p").undelegate()
}}}
}}}
* {{multiLine{To unbind all delegated click events from all paragraphs, write:
{{{
$("p").undelegate( "click" )
}}}
}}}
* {{multiLine{To undelegate just one previously bound handler, pass the function in as the third argument:
{{{
var foo = function () {
// code to handle some kind of event
};
$("body").delegate("p", "click", foo); // ... now foo will be called when paragraphs are clicked ...
$("body").undelegate("p", "click", foo); // ... foo will no longer be called.
}}}
}}}
Bind an event handler to the "unload" JavaScript event.
|!Name|!Type|!Optional|!Description|h
|handler(eventObject)|Function|no|A function to execute when the event is triggered.|
|Arguments|c
!Description
<html>
<p>This method is a shortcut for <code>.bind('unload', handler)</code>.</p>
<p>The <code>unload</code> event is sent to the <code>window</code> element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an <code>unload</code> event.</p>
<blockquote><p>The exact handling of the <code>unload</code> event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers, and contrasted with the proprietary <code>beforeunload</code> event.</p></blockquote>
<p>Any <code>unload</code> event handler should be bound to the <code>window</code> object:</p>
<pre>$(window).unload(function() {
alert('Handler for .unload() called.');
});
</pre>
<p>After this code executes, the alert will be displayed whenever the browser leaves the current page.
It is not possible to cancel the <code>unload</code> event with <code>.preventDefault()</code>. This event is available so that scripts can perform cleanup when the user leaves the page.
</p>
</html>
!Examples
* {{multiLine{To display an alert when a page is unloaded:
{{{
$(window).unload( function () { alert("Bye now!"); } );
}}}
}}}
Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
!Description
<html><p>The <code>.unwrap()</code> method removes the element's parent. This is effectively the inverse of the <code><a href="/wrap">.wrap()</a></code> method. The matched elements (and their siblings, if any) replace their parents within the DOM structure.</p></html>
!Examples
* {{multiLine{Wrap/unwrap a div around each of the paragraphs.
{{{
$("button").toggle(function(){
$("p").wrap("<div></div>");
}, function(){
$("p").unwrap();
});
}}}
}}}
Set the value of each element in the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|value|String|no|A string of text or an array of strings to set as the value property of each matched element.|
|function(index, value)|Function|no|A function returning the value to set.|
|Arguments|c
!Description
<html><p>This method is typically used to set the values of form fields. For <code><select multiple="multiple"></code> elements, multiple <code><option></code>s can be selected by passing in an array.</p>
<p>The <code>.val()</code> method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value: </p>
<pre>$('input:text.items').val(function(index, value) {
return value + ' ' + this.className;
});
</pre>
<p>This example appends the string " items" to the text inputs' values.</p>
</html>
!Examples
* {{multiLine{Set the value of an input box.
{{{
$("button").click(function () {
var text = $(this).text();
$("input").val(text);
});
}}}
}}}
* {{multiLine{Set a single select and a multiple select .
{{{
$("#single").val("Single2");
$("#multiple").val(["Multiple2", "Multiple3"]);
$("input").val(["check1","check2", "radio1" ]);
}}}
}}}
Selects all elements that are visible.
!Description
<html> <p>Elements can be considered hidden for several reasons:</p>
<ul>
<li>They have a display value of none.</li>
<li>They are form elements with type="hidden".</li>
<li>Their width and height are explicitly set to 0.</li>
<li>An ancestor element is hidden, so the element is not shown on the page.</li>
</ul>
<p>How <code>:visible</code> is calculated was changed in jQuery 1.3.2. The <a href="http://docs.jquery.com/Release:jQuery_1.3.2#:visible.2F:hidden_Overhauled">release notes</a> outline the changes in more detail.</p></html>
!Examples
* {{multiLine{Make all visible divs turn yellow on click.
{{{
$("div:visible").click(function () {
$(this).css("background", "yellow");
});
$("button").click(function () {
$("div:hidden").show("fast");
});
}}}
}}}
Set the CSS width of each element in the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|value|String, Number|no|An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).|
|function(index, width)|Function|no|A function returning the width to set. Receives the index position of the element in the set and the old width as arguments.|
|Arguments|c
!Description
<html><p>When calling <code>.width('value')</code>, the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit. If a string is provided, however, any valid CSS measurement may be used for the width (such as <code>100px</code>, <code>50%</code>, or <code>auto</code>). Note that in modern browsers, the CSS width property does not include padding, border, or margin.</p>
<p>If no explicit unit was specified (like 'em' or '%') then "px" is concatenated to the value.</p></html>
!Examples
* {{multiLine{To set the width of each div on click to 30px plus a color change.
{{{
$("div").one('click', function () {
$(this).width(30)
.css({cursor:"auto", "background-color":"blue"});
});
}}}
}}}
Wrap an HTML structure around each element in the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|wrappingElement|String, Selector, Element, jQuery|no|An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.|
|wrappingFunction|Function|no|A callback function which generates a structure to wrap around the matched elements.|
|Arguments|c
!Description
<html><p>The <code>.wrap()</code> function can take any string or object that could be passed to the <code>$()</code> factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around each of the elements in the set of matched elements. This method returns the original set of elements for chaining purposes.</p>
<p>Consider the following HTML:</p>
<pre><div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>Using <code>.wrap()</code>, we can insert an HTML structure around the inner <code><div></code> elements like so:</p>
<pre>$('.inner').wrap('<div class="new" />');</pre>
<p>The new <code><div></code> element is created on the fly and added to the DOM. The result is a new <code><div></code> wrapped around each matched element:</p>
<pre><div class="container">
<div class="new">
<div class="inner">Hello</div>
</div>
<div class="new">
<div class="inner">Goodbye</div>
</div>
</div></pre>
<p>The second version of this method allows us to instead specify a callback function. This callback function will be called once for every matched element; it should return a DOM element, jQuery object, or HTML snippet in which to wrap the corresponding element. For example:</p>
<pre>$('.inner').wrap(function() {
return '<div class="' + $(this).text() + '" />';
});</pre>
<p>This will cause each <code><div></code> to have a class corresponding to the text it wraps:</p>
<pre><div class="container">
<div class="Hello">
<div class="inner">Hello</div>
</div>
<div class="Goodbye">
<div class="inner">Goodbye</div>
</div>
</div></pre>
</html>
!Examples
* {{multiLine{Wrap a new div around all of the paragraphs.
{{{
$("p").wrap("<div></div>");
}}}
}}}
* {{multiLine{Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the <strong> (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html.
{{{
$("span").wrap("<div><div><p><em><b></b></em></p></div></div>");
}}}
}}}
* {{multiLine{Wrap a new div around all of the paragraphs.
{{{
$("p").wrap(document.createElement("div"));
}}}
}}}
* {{multiLine{Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target.
{{{
$("p").wrap($(".doublediv"));
}}}
}}}
Wrap an HTML structure around all elements in the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|wrappingElement|String, Selector, Element, jQuery|no|An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.|
|Arguments|c
!Description
<html><p>The <code>.wrapAll()</code> function can take any string or object that could be passed to the <code>$()</code> function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around all of the elements in the set of matched elements, as a single group.</p>
<p>Consider the following HTML:</p>
<pre><div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>Using <code>.wrapAll()</code>, we can insert an HTML structure around the inner <code><div></code> elements like so:</p>
<pre>$('.inner').wrapAll('<div class="new" />');</pre>
<p>The new <code><div></code> element is created on the fly and added to the DOM. The result is a new <code><div></code> wrapped around all matched elements:</p>
<pre><div class="container">
<div class="new">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
</div></pre></html>
!Examples
* {{multiLine{Wrap a new div around all of the paragraphs.
{{{
$("p").wrapAll("<div></div>");
}}}
}}}
* {{multiLine{Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the <strong> (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html.
{{{
$("span").wrapAll("<div><div><p><em><b></b></em></p></div></div>");
}}}
}}}
* {{multiLine{Wrap a new div around all of the paragraphs.
{{{
$("p").wrapAll(document.createElement("div"));
}}}
}}}
* {{multiLine{Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target.
{{{
$("p").wrapAll($(".doublediv"));
}}}
}}}
Wrap an HTML structure around the content of each element in the set of matched elements.
|!Name|!Type|!Optional|!Description|h
|wrappingElement|String|no|An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements.|
|wrappingFunction|Function|no|A callback function which generates a structure to wrap around the content of the matched elements.|
|Arguments|c
!Description
<html><p>The <code>.wrapInner()</code> function can take any string or object that could be passed to the <code>$()</code> factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around the content of each of the elements in the set of matched elements.</p>
<p>Consider the following HTML:</p>
<pre><div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div></pre>
<p>Using <code>.wrapInner()</code>, we can insert an HTML structure around the content of each inner <code><div></code> elements like so:</p>
<pre>$('.inner').wrapInner('<div class="new" />');</pre>
<p>The new <code><div></code> element is created on the fly and added to the DOM. The result is a new <code><div></code> wrapped around the content of each matched element:</p>
<pre><div class="container">
<div class="inner">
<div class="new">Hello</div>
</div>
<div class="inner">
<div class="new">Goodbye</div>
</div>
</div></pre>
<p>The second version of this method allows us to instead specify a callback function. This callback function will be called once for every matched element; it should return a DOM element, jQuery object, or HTML snippet in which to wrap the content of the corresponding element. For example:</p>
<pre>$('.inner').wrapInner(function() {
return '<div class="' + this.nodeValue + '" />';
});</pre>
<p>This will cause each <code><div></code> to have a class corresponding to the text it wraps:</p>
<pre><div class="container">
<div class="inner">
<div class="Hello">Hello</div>
</div>
<div class="inner">
<div class="Goodbye">Goodbye</div>
</div>
</div></pre></html>
!Examples
* {{multiLine{Selects all paragraphs and wraps a bold tag around each of its contents.
{{{
$("p").wrapInner("<b></b>");
}}}
}}}
* {{multiLine{Wraps a newly created tree of objects around the inside of the body.
{{{
$("body").wrapInner("<div><div><p><em><b></b></em></p></div></div>");
}}}
}}}
* {{multiLine{Selects all paragraphs and wraps a bold tag around each of its contents.
{{{
$("p").wrapInner(document.createElement("b"));
}}}
}}}
* {{multiLine{Selects all paragraphs and wraps a jQuery object around each of its contents.
{{{
$("p").wrapInner($("<span class='red'></span>"));
}}}
}}}