This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<desc>Lock a callback list in its current state.</desc>
<longdesc>
<p>This method returns the Callbacks object onto which it is attached (<code>this</code>).</p>
<p>This method returns the Callbacks object onto which it is attached (<code>this</code>).</p>
<p>If the Callbacks object is created with the <code>"memory"</code> flag as its argument, additional functions may be added and fired after the callback list is locked.</p>
</longdesc>
<example>
<desc>Use <code>callbacks.lock()</code> to lock a callback list to avoid further changes being made to the list state:</desc>
<code><![CDATA[// a sample logging function to be added to a callbacks list
<code><![CDATA[
// A sample logging function to be added to a callbacks list
var foo = function( value ) {
console.log( "foo:" + value );
};
var callbacks = $.Callbacks();
// add the logging function to the callback list
// Add the logging function to the callback list
callbacks.add( foo );
// fire the items on the list, passing an argument
// Fire the items on the list, passing an argument
callbacks.fire( "hello" );
// outputs "foo: hello"
// Outputs "foo: hello"
// lock the callbacks list
// Lock the callbacks list
callbacks.lock();
// try firing the items again
// Try firing the items again
callbacks.fire( "world" );
// as the list was locked, no items
// were called, so "world" isn"t logged
// As the list was locked, no items were called,
// so "world" isn't logged
]]></code>
</example>
<example>
<desc>Use <code>callbacks.lock()</code> to lock a callback list with "memory," and then resume using the list:</desc>
<html><![CDATA[<div id="log"></div>]]></html>
<code><![CDATA[// simple function for logging results
var log = function( value) {
<html><![CDATA[
<div id="log"></div>
]]></html>
<code><![CDATA[
// Simple function for logging results
var log = function( value ) {
$( "#log" ).append( "<p>" + value + "</p>" );
};
// two sample functions to be added to a callbacks list
// Two sample functions to be added to a callbacks list
var foo = function( value ) {
log( "foo: " + value );
};
var bar = function( value ) {
log( "bar: " + value );
};
// create the callbacks object with the "memory" flag
// Create the callbacks object with the "memory" flag
var callbacks = $.Callbacks( "memory" );
// add the foo logging function to the callback list
// Add the foo logging function to the callback list
callbacks.add( foo );
// fire the items on the list, passing an argument
// Fire the items on the list, passing an argument
callbacks.fire( "hello" );
// outputs "foo: hello"
// Outputs "foo: hello"
// lock the callbacks list
// Lock the callbacks list
callbacks.lock();
// try firing the items again
// Try firing the items again
callbacks.fire( "world" );
// as the list was locked, no items were called,
// As the list was locked, no items were called,
// so "foo: world" isn't logged
// add the foo function to the callback list again
// Add the foo function to the callback list again
callbacks.add( foo );
// try firing the items again
// Try firing the items again
callbacks.fire( "silentArgument" );
// outputs "foo: hello" because the argument value was stored in memory
// Outputs "foo: hello" because the argument value was stored in memory
// add the bar function to the callback list
// Add the bar function to the callback list
callbacks.add( bar );
callbacks.fire( "youHadMeAtHello" );
// outputs "bar: hello" because the list is still locked,
// Outputs "bar: hello" because the list is still locked,
// and the argument value is still stored in memory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p>This method is a shortcut for <code>.on('change', handler)</code> in the first two variations, and <code>.trigger('change')</code> in the third.</p>
<p>This method is a shortcut for <code>.on( "change", handler)</code> in the first two variations, and <code>.trigger( "change" )</code> in the third.</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>The event handler can be bound to the text input and the select box:</p>
<pre><code>$('.target').change(function() {
alert('Handler for .change() called.');
});</code></pre>
<pre><code>
$( ".target" ).change(function() {
alert( "Handler for .change() called." );
});
</code></pre>
<p>Now when the second option is selected from the dropdown, the alert is displayed. It is also displayed if you 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. To trigger the event manually, apply <code>.change()</code> without arguments:</p>
<pre><code>$('#other').click(function() {
$('.target').change();
});</code></pre>
<pre><code>
$( "#other" ).click(function() {
$( ".target" ).change();
});
</code></pre>
<p>After this code executes, clicks on <samp>Trigger the handler</samp> will also alert the message. The message will display 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 bubbles in Internet Explorer, behaving consistently with the event in other modern browsers.</p>
</longdesc>
<example>
<desc>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.</desc>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<desc>Selects all elements of type checkbox.</desc>
<longdesc>
<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>
<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>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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>
</longdesc>
<example>
<desc>Find all children of the clicked element.</desc>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p>This method is a shortcut for <code>.on('click', handler)</code> in the first two variations, and <code>.trigger('click')</code> in the third.
<p>This method is a shortcut for <code>.on( "click", handler)</code> in the first two variations, and <code>.trigger( "click" )</code> in the third.
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.
For example, consider the HTML:</p>
<pre><code><div id="target">
<pre><code>
<div id="target">
Click here
</div>
<div id="other">
Trigger the handler
</div></code></pre>
</div>
</code></pre>
<pclass="image">
<imgsrc="/resources/0042_05_03.png"alt=""/>
</p>
<p>The event handler can be bound to any <code><div></code>:</p>
<pre><code>$("#target").click(function() {
alert("Handler for .click() called.");
});</code></pre>
<pre><code>
$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});
</code></pre>
<p>Now if we click on this element, the alert is displayed:</p>
<p>
<samp>Handler for .click() called.</samp>
</p>
<p>We can also trigger the event when a different element is clicked:</p>
<pre><code>$("#other").click(function() {
$("#target").click();
});</code></pre>
<pre><code>
$( "#other" ).click(function() {
$( "#target" ).click();
});
</code></pre>
<p>After this code executes, clicks on <samp>Trigger the handler</samp> will also alert the message.</p>
<p>The <code>click</code> event is only triggered after this exact series of events:</p>
<ul>
@@ -56,22 +62,31 @@
<example>
<desc>Hide paragraphs on a page when they are clicked:</desc>
<code><![CDATA[
$("p").click(function() {
$(this).slideUp();
});
$( "p").click(function() {
$( this).slideUp();
});
]]></code>
<css><![CDATA[
p { color:red; margin:5px; cursor:pointer; }
p:hover { background:yellow; }
]]></css>
<html><![CDATA[<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>]]></html>
p {
color: red;
margin: 5px;
cursor: pointer;
}
p:hover {
background: yellow;
}
]]></css>
<html><![CDATA[
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
]]></html>
</example>
<example>
<desc>Trigger the click event on all of the paragraphs on the page:</desc>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<desc>Create a deep copy of the set of matched elements.</desc>
<longdesc>
<p>The <code>.clone()</code> method performs a <em>deep</em> copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes. For performance reasons, the dynamic state of form elements (e.g., user data typed into <code>input</code>, and <code>textarea</code> or user selections made to a <code>select</code>) is not copied to the cloned elements. The clone operation sets these fields to their default values as specified in the HTML.</p>
<p>When used in conjunction with one of the insertion methods, <code>.clone()</code> is a convenient way to duplicate elements on a page. Consider the following HTML:</p>
<pre><code><div class="container">
<p>When used in conjunction with one of the insertion methods, <code>.clone()</code> is a convenient way to duplicate elements on a page. Consider the following HTML:</p>
<pre><code>
<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div></code></pre>
</div>
</code></pre>
<p>As shown in the discussion for <code><ahref="http://api.jquery.com/append/">.append()</a></code>, normally when an element is inserted somewhere in the DOM, it is moved from its old location. So, given the code:</p>
<p><strong>Note:</strong> When using the <code>.clone()</code> method, you can modify the cloned elements or their contents before (re-)inserting them into the document.</p>
</div>
<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>
<p>However, objects and arrays within element data are not copied and will continue to be shared between the cloned element and the original element. To deep copy all data, copy each one manually:</p>
<pre><code>var $elem = $('#elem').data( "arr": [ 1 ] ), // Original element with attached data
<pre><code>
// Original element with attached data
var $elem = $( "#elem" ).data( "arr": [ 1 ] ),
$clone = $elem.clone( true )
.data( "arr", $.extend( [], $elem.data("arr") ) ); // Deep copy to prevent data sharing
<p>As of jQuery 1.5, <code>withDataAndEvents</code> can be optionally enhanced with <code>deepWithDataAndEvents </code> to copy the events and data for all children of the cloned element.</p>
<divclass="warning">
<p><strong>Note:</strong> Using <code>.clone()</code> has the side-effect of producing elements with duplicate <code>id</code> attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using <code>class</code> attributes as identifiers instead.</p>
@@ -60,10 +73,10 @@
<example>
<desc>Clones all b elements (and selects the clones) and prepends them to all paragraphs.</desc>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p>Suppose we perform a search for <code><ul></code> elements starting at item A:</p>
<pre><code>
$('li.item-a').closest('ul')
.css('background-color', 'red');
</code></pre>
$( "li.item-a" )
.closest( "ul" )
.css( "background-color", "red" );
</code></pre>
<p>This will change the color of the level-2 <code><ul></code>, since it is the first encountered when traveling up the DOM tree.</p>
<p>Suppose we search for an <code><li></code> element instead:</p>
<pre><code>$('li.item-a').closest('li')
.css('background-color', 'red');
</code></pre>
<pre><code>
$( "li.item-a" )
.closest( "li" )
.css( "background-color", "red" );
</code></pre>
<p>This will change the color of list item A. The <code>.closest()</code> method begins its search <em>with the element itself</em> before progressing up the DOM tree, and stops when item A matches the selector.</p>
<p>We can pass in a DOM element as the context within which to search for the closest element.</p>
<p>This will change the color of the level-2 <code><ul></code>, because it is both the first <code><ul></code> ancestor of list item A and a descendant of list item II. It will not change the color of the level-1 <code><ul></code>, however, because it is not a descendant of list item II.</p>
</longdesc>
<example>
<desc>Show how event delegation can be done with closest. The closest list element toggles a yellow background when it or its descendent is clicked.</desc>
<desc>Get an array of all the elements and selectors matched against the current element up through the DOM tree.</desc>
<longdesc>
<p><strong>This signature (only!) is deprecated as of jQuery 1.7 and <em>removed</em> in jQuery 1.8</strong>. It was primarily meant to be used internally or by plugin authors.</p>
<divclass="warning"><strong>This signature (only!) is deprecated as of jQuery 1.7 and <em>removed</em> in jQuery 1.8</strong>. It was primarily meant to be used internally or by plugin authors.</div>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p>Given a jQuery object that represents a set of DOM elements, the <code>.contents()</code> method allows us to search throughthe 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><code><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
<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><code>
<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
<br><br>
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur.
</div>
</code></pre>
</code></pre>
<p>We can employ the <code>.contents()</code> method to help convert this blob of text into three well-formed paragraphs:</p>
<pre><code>
$('.container').contents().filter(function() {
return this.nodeType == 3;
})
.wrap('<p></p>')
.end()
.filter('br')
.remove();
</code></pre>
$( ".container" )
.contents()
.filter(function() {
return this.nodeType === 3;
})
.wrap( "<p></p>" )
.end()
.filter( "br" )
.remove();
</code></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 <ahref="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>
</longdesc>
<example>
<desc>Find all the text nodes inside a paragraph and wrap them with a bold tag.</desc>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<desc>Get the value of style properties for the first element in the set of matched elements.</desc>
<longdesc>
<p>The <code>.css()</code> method is a convenient way to get a style property from the first matched element, especially in light of the different ways browsers access most of those properties (the <code>getComputedStyle()</code> method in standards-based browsers versus the <code>currentStyle</code> and <code>runtimeStyle</code> properties in Internet Explorer) and the different terms browsers use for certain properties. For example, Internet Explorer's DOM implementation refers to the <code>float</code> property as <code>styleFloat</code>, while W3C standards-compliant browsers refer to it as <code>cssFloat</code>. For consistency, you can simply use <code>"float"</code>, and jQuery will translate it to the correct value for each browser.</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')</code> and <code>.css('backgroundColor')</code>. Different browsers may return CSS color values that are logically but not textually equal, e.g., #FFF, #ffffff, and rgb(255,255,255).</p>
<p>Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: <code>$(elem).css('marginTop')</code> and <code>$(elem).css('marginRight')</code>, and so on.</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" )</code> and <code>.css( "backgroundColor" )</code>. Different browsers may return CSS color values that are logically but not textually equal, e.g., #FFF, #ffffff, and rgb(255,255,255).</p>
<p>Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: <code>$(elem).css( "marginTop" )</code> and <code>$(elem).css( "marginRight" )</code>, and so on.</p>
<p><strong>As of jQuery 1.9</strong>, passing an array of style properties to <code>.css()</code> will result in an object of property-value pairs.</p>
</longdesc>
<example>
<desc>Get the background color of a clicked div.</desc>
<code><![CDATA[
$("div").click(function() {
var color = $(this).css("background-color");
$("#result").html("That div is <span style='color:" +
color + ";'>" + color + "</span>.");
$("div").click(function() {
var color = $(this).css("background-color");
$("#result").html("That div is <span style='color:" +
color + ";'>" + color + "</span>.");
});
]]></code>
<css><![CDATA[
div { width:60px; height:60px; margin:5px; float:left; }
<desc>Set one or more CSS properties for the set of matched elements.</desc>
<longdesc>
<p>As with the <code>.prop()</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 object of key-value pairs.</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>When using <code>.css()</code> as a setter, jQuery modifies the element's <code>style</code> property. For example, <code>$('#mydiv').css('color', 'green')</code> is equivalent to <code>document.getElementById('mydiv').style.color = 'green'</code>. Setting the value of a style property to an empty string — e.g. <code>$('#mydiv').css('color', '')</code> — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's <code>.css()</code> method, or through direct DOM manipulation of the <code>style</code> property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <code><style></code> element. <strong>Warning:</strong> one notable exception is that, for IE 8 and below, removing a shorthand property such as <code>border</code> or <code>background></code> will remove that style entirely from the element, regardless of what is set in a stylesheet or <code><style></code> element.</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>When using <code>.css()</code> as a setter, jQuery modifies the element's <code>style</code> property. For example, <code>$( "#mydiv" ).css( "color", "green" )</code> is equivalent to <code>document.getElementById( "mydiv" ).style.color = "green"</code>. Setting the value of a style property to an empty string — e.g. <code>$( "#mydiv" ).css( "color", "" )</code> — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's <code>.css()</code> method, or through direct DOM manipulation of the <code>style</code> property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <code><style></code> element. <strong>Warning:</strong> one notable exception is that, for IE 8 and below, removing a shorthand property such as <code>border</code> or <code>background></code> will remove that style entirely from the element, regardless of what is set in a stylesheet or <code><style></code> element.</p>
<p>As of jQuery 1.6, <code>.css()</code> accepts relative values similar to <code>.animate()</code>. Relative values are a string starting with <code>+=</code> or <code>-=</code> to increment or decrement the current value. For example, if an element's padding-left was 10px, <code>.css( "padding-left", "+=15" )</code> would result in a total padding-left of 25px.</p>
<p>As of jQuery 1.4, <code>.css()</code> allows us to pass a function as the property value:</p>
$( "div.example" ).css( "width", function( index ) {
return index * 50;
});</code></pre>
});
</code></pre>
<p>This example sets the widths of the matched elements to incrementally larger values.</p>
<p><strong>Note: </strong>If nothing is returned in the setter function (ie. <code>function(index, style){})</code>, or if <code>undefined</code> is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.</p>
<p><strong>Note: </strong>If nothing is returned in the setter function (ie. <code>function(index, style){})</code>, or if <code>undefined</code> is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.</p>
</longdesc>
<example>
<desc>Change the color of any paragraph to red on mouseover event.</desc>
<code><![CDATA[
$("p").on( "mouseover", function() {
$(this).css( "color", "red" );
});
$( "p").on( "mouseover", function() {
$( this).css( "color", "red" );
});
]]></code>
<css><![CDATA[
p { color:blue; width:200px; font-size:14px; }
]]></css>
p {
color: blue;
width: 200px;
font-size: 14px;
}
]]></css>
<html><![CDATA[
<p>Just roll the mouse over me.</p>
<p>Or me to see a color change.</p>
]]></html>
]]></html>
</example>
<example>
<desc>Increase the width of #box by 200 pixels the first time it is clicked.</desc>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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.</p>
<p> We can set several distinct values for a single element and retrieve them later:</p>
<p>In jQuery 1.4.3 setting an element's data object with <code>.data(obj)</code> extends the data previously stored with that element. jQuery itself uses the <code>.data()</code> method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.</p>
<p>Prior to jQuery 1.4.3 (starting in jQuery 1.4) the .data() method completely replaced all data, instead of just extending the data object. If you are using third-party plugins it may not be advisable to completely replace the element's data object, since plugins may have also set data.</p>
<p>Due to the way browsers interact with plugins and external code, the <code>.data()</code> method cannot be used on <code><object></code> (unless it's a Flash plugin), <code><applet></code> or <code><embed></code> elements.</p>
<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><code>
alert($('body').data('foo'));
alert($('body').data());
</code></pre>
alert( $( "body" ).data( "foo" ) );
alert( $( "body" ).data());
</code></pre>
<p>The above lines alert the data values that were set on the <code>body</code> element. If no data at all was set on that element, <code>undefined</code> is returned.</p>
<pre><code>
alert( $("body").data("foo")); //undefined
$("body").data("bar", "foobar");
alert( $("body").data("bar")); //foobar
</code></pre>
alert( $("body").data("foo" ) ); //undefined
$("body").data("bar", "foobar");
alert( $("body").data("bar" ) ); //foobar
</code></pre>
<h4id="data-html5">
<ahref="#data-html5">HTML5 data-* Attributes</a>
</h4>
<p>As of jQuery 1.4.3 <ahref="http://ejohn.org/blog/html-5-data-attributes/">HTML 5 data- attributes</a> will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the <ahref="http://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes">W3C HTML5 specification</a>.</p>
<p>Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.</p>
<p>When the data attribute is an object (starts with '{') or array (starts with '[') then <code>jQuery.parseJSON</code> is used to parse the string; it must follow <ahref="http://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example">valid JSON syntax</a> <em>including quoted property names</em>. If the value isn't parseable as a JavaScript value, it is left as a string.</p>
<p>To retrieve the value's attribute as a string without any attempt to convert it, use the <code><ahref="/attr/">attr()</a></code> method.</p>
<p>The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).</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>. Using the object directly to get or set values is faster than making individual calls to <code>.data()</code> to get or set each value:</p>
<pre><code>
var mydata = $("#mydiv").data();
var mydata = $("#mydiv").data();
if ( mydata.count < 9 ) {
mydata.count = 43;
mydata.status = "embiggened";
mydata.count = 43;
mydata.status = "embiggened";
}
</code></pre>
</code></pre>
</longdesc>
<noteid="no-data-on-xml"type="additional"/>
<example>
<desc>Get the data named "blah" stored at for an element.</desc>
<code><![CDATA[
$("button").click(function(e) {
$("button").click(function() {
var value;
switch ($("button").index(this)) {
switch ( $( "button").index(this ) ) {
case 0 :
value = $("div").data("blah");
value = $("div").data("blah");
break;
case 1 :
$("div").data("blah", "hello");
$("div").data("blah", "hello");
value = "Stored!";
break;
case 2 :
$("div").data("blah", 86);
$("div").data("blah", 86);
value = "Stored!";
break;
case 3 :
$("div").removeData("blah");
$("div").removeData("blah");
value = "Removed!";
break;
}
$("span").text("" + value);
$("span").text("" + value);
});
]]></code>
<css><![CDATA[
div { margin:5px; background:yellow; }
button { margin:5px; font-size:14px; }
p { margin:5px; color:blue; }
span { color:red; }
]]></css>
<html><![CDATA[<div>A div</div>
<button>Get "blah" from the div</button>
<button>Set "blah" to "hello"</button>
<button>Set "blah" to 86</button>
<button>Remove "blah" from the div</button>
<p>The "blah" value of this div is <span>?</span></p>]]></html>
div {
margin: 5px;
background: yellow;
}
button {
margin: 5px;
font-size: 14px;
}
p {
margin: 5px;
color: blue;
}
span {
color: red;
}
]]></css>
<html><![CDATA[
<div>A div</div>
<button>Get "blah" from the div</button>
<button>Set "blah" to "hello"</button>
<button>Set "blah" to 86</button>
<button>Remove "blah" from the div</button>
<p>The "blah" value of this div is <span>?</span></p>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p>This method is a shortcut for <code>.on('dblclick', handler)</code> in the first two variations, and <code>.trigger('dblclick')</code> in the third.
<p>This method is a shortcut for <code>.on( "dblclick", handler)</code> in the first two variations, and <code>.trigger( "dblclick" )</code> in the third.
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><code><div id="target">
<pre><code>
<div id="target">
Double-click here
</div>
<div id="other">
Trigger the handler
</div></code></pre>
</div>
</code></pre>
<pclass="image">
<imgsrc="/resources/0042_05_04.png"alt=""/>
</p>
<p>The event handler can be bound to any <code><div></code>:</p>
<pre><code>$('#target').dblclick(function() {
alert('Handler for .dblclick() called.');
});</code></pre>
<pre><code>
$( "#target" ).dblclick(function() {
alert( "Handler for .dblclick() called." );
});
</code></pre>
<p>Now double-clicking on this element displays the alert:</p>
<p>
<samp>Handler for .dblclick() called.</samp>
</p>
<p>To trigger the event manually, apply <code>.dblclick()</code> without an argument:</p>
<pre><code>$('#other').click(function() {
$('#target').dblclick();
});</code></pre>
<pre><code>
$( "#other" ).click(function() {
$( "#target" ).dblclick();
});
</code></pre>
<p>After this code executes, (single) clicks on <samp>Trigger the handler</samp> will also alert the message.</p>
<p>The <code>dblclick</code> event is only triggered after this exact series of events:</p>
<ul>
@@ -58,25 +64,36 @@
</longdesc>
<example>
<desc>To bind a "Hello World!" alert box the dblclick event on every paragraph on the page:</desc>
<code><![CDATA[$("p").dblclick( function () { alert("Hello World!"); });]]></code>
<code><![CDATA[
$( "p" ).dblclick(function() {
alert( "Hello World!" );
});
]]></code>
</example>
<example>
<desc>Double click to toggle background color.</desc>
<code><![CDATA[
var divdbl = $("div:first");
divdbl.dblclick(function() {
divdbl.toggleClass('dbl');
});
var divdbl = $("div:first");
divdbl.dblclick(function() {
divdbl.toggleClass( "dbl" );
});
]]></code>
<css><![CDATA[
div { background:blue;
color:white;
height:100px;
width:150px;
div {
background: blue;
color: white;
height: 100px;
width: 150px;
}
div.dbl { background:yellow;color:black; }
]]></css>
<html><![CDATA[<div></div><span>Double click the block</span>]]></html>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<desc>Since the <ahref="http://api.jquery.com/jQuery.get/"><code>jQuery.get()</code></a> method returns a <code>jqXHR</code> object, which is derived from a Deferred object, we can attach a callback for both success and error using the <code>deferred.always()</code> method.</desc>
<code><![CDATA[
$.get("test.php").always(function() {
alert("$.get completed with success or error callback arguments");
});
$.get("test.php").always(function() {
alert("$.get completed with success or error callback arguments");
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<desc>Since the <ahref="/jQuery.get"><code>jQuery.get</code></a> method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the <code>.done()</code> method.</desc>
<code><![CDATA[
$.get("test.php").done(function() {
alert("$.get succeeded");
$.get("test.php").done(function() {
alert("$.get succeeded");
});
]]></code>
</example>
<example>
<desc>Resolve a Deferred object when the user clicks a button, triggering a number of callback functions:</desc>
<code><![CDATA[
/* 3 functions to call when the Deferred object is resolved */
// 3 functions to call when the Deferred object is resolved
function fn1() {
$("p").append(" 1 ");
$("p").append(" 1 ");
}
function fn2() {
$("p").append(" 2 ");
$("p").append(" 2 ");
}
function fn3(n) {
$("p").append(n + " 3 " + n);
function fn3( n ) {
$("p").append(n + " 3 " + n);
}
/* create a deferred object */
// Create a deferred object
var dfd = $.Deferred();
/* add handlers to be called when dfd is resolved */
// Add handlers to be called when dfd is resolved
dfd
/* .done() can take any number of functions or arrays of functions */
.done( [fn1, fn2], fn3, [fn2, fn1] )
/* we can chain done methods, too */
.done(function(n) {
$("p").append(n + " we're done.");
});
// .done() can take any number of functions or arrays of functions
.done( [fn1, fn2], fn3, [fn2, fn1] )
// We can chain done methods, too
.done(function( n ) {
$( "p").append(n + " we're done.");
});
/* resolve the Deferred object when the button is clicked */
$("button").on("click", function() {
dfd.resolve("and");
// Resolve the Deferred object when the button is clicked
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<desc>Since the <ahref="http://api.jquery.com/jQuery.get/"><code>jQuery.get</code></a> method returns a jqXHR object, which is derived from a Deferred, you can attach a success and failure callback using the <code>deferred.done()</code> and <code>deferred.fail()</code> methods.</desc>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<desc>Create a Deferred and set two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action. Also set a timer-based progress notification function, and call a progress handler that adds "working..." to the document body.</desc>
<code><![CDATA[
function asyncEvent(){
var dfd = new jQuery.Deferred();
function asyncEvent(){
var dfd = new jQuery.Deferred();
// Resolve after a random interval
setTimeout(function(){
dfd.resolve("hurray");
}, Math.floor(400+Math.random()*2000));
// Resolve after a random interval
setTimeout(function(){
dfd.resolve("hurray");
}, Math.floor(400 + Math.random() * 2000 ) );
// Reject after a random interval
setTimeout(function(){
dfd.reject("sorry");
}, Math.floor(400+Math.random()*2000));
// Reject after a random interval
setTimeout(function(){
dfd.reject("sorry");
}, Math.floor(400 + Math.random() * 2000 ) );
// Show a "working..." message every half-second
setTimeout(function working(){
if ( dfd.state() === "pending" ) {
dfd.notify("working... ");
setTimeout(working, 500);
}
}, 1);
// Show a "working..." message every half-second
setTimeout(function working(){
if ( dfd.state() === "pending" ) {
dfd.notify("working... ");
setTimeout(working, 500);
}
}, 1);
// Return the Promise so caller can't change the Deferred
return dfd.promise();
// Return the Promise so caller can't change the Deferred
return dfd.promise();
}
// Attach a done, fail, and progress handler for the asyncEvent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<desc>Since the <ahref="/jQuery.get"><code>jQuery.get</code></a> method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the <code>.then</code> method.</desc>
<code><![CDATA[
$.get("test.php").then(
function(){ alert("$.get succeeded"); },
function(){ alert("$.get failed!"); }
$.get( "test.php" ).then(
function() {
alert( "$.get succeeded" );
}, function() {
alert( "$.get failed!" );
}
);
]]></code>
</example>
@@ -83,11 +86,10 @@ $.get("test.php").then(
]]></html>
<code><![CDATA[
var filterResolve = function() {
var defer = $.Deferred(),
filtered = defer.then(function( value ) {
return value * 2;
});
filtered = defer.then(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
@@ -97,15 +99,14 @@ var filterResolve = function() {
$( "button" ).on( "click", filterResolve );
]]></code>
</example>
<example>
<desc>Filter reject value:</desc>
<code><![CDATA[
var defer = $.Deferred(),
filtered = defer.then( null, function( value ) {
return value * 3;
});
filtered = defer.then( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
@@ -117,14 +118,13 @@ filtered.fail(function( value ) {
<desc>Chain tasks:</desc>
<code><![CDATA[
var request = $.ajax( url, { dataType: "json" } ),
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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. Only subsequent events in a queue are delayed; for example this will <em>not</em> delay the no-arguments forms of <code>.show()</code> or <code>.hide()</code> which do not use the effects 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>
<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>
<divclass="warning">
<p>
@@ -26,20 +28,33 @@
<example>
<desc>Animate the hiding and showing of two divs, delaying the first before showing it.</desc>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p>As of jQuery 1.7, <code>.delegate()</code> has been superseded by the <ahref="http://api.jquery.com/on">.on()</a> method. For earlier versions, however, it remains the most effective means to use event delegation. More information on event binding and delegation is in the <ahref="http://api.jquery.com/on">.on()</a> method. In general, these are the equivalent templates for the two methods:</p>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters