Core
$(html)

$(html)

Create DOM elements on-the-fly from the provided String of raw HTML.

Returns

jQuery

Parameters

  • html (String): A string of HTML to create on the fly.

Example

Creates a div element (and all of its contents) dynamically, and appends it to the body element. Internally, an element is created and its innerHTML property set to the given markup. It is therefore both quite flexible and limited.

jQuery Code

$("<div><p>Hello</p></div>").appendTo("body")
$(elems)

$(elems)

Wrap jQuery functionality around a single or multiple DOM Element(s).

This function also accepts XML Documents and Window objects as valid arguments (even though they are not DOM Elements).

Returns

jQuery

Parameters

  • elems (Element|Array<Element>): DOM element(s) to be encapsulated by a jQuery object.

Example

Sets the background color of the page to black.

jQuery Code

$(document.body).css( "background", "black" );

Example

Hides all the input elements within a form

jQuery Code

$( myForm.elements ).hide()
$(fn)

$(fn)

A shorthand for $(document).ready(), allowing you to bind a function to be executed when the DOM document has finished loading. This function behaves just like $(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready to be operated on. While this function is, technically, chainable - there really isn't much use for chaining against it.

You can have as many $(document).ready events on your page as you like.

See ready(Function) for details about the ready event.

Returns

jQuery

Parameters

  • fn (Function): The function to execute when the DOM is ready.

Example

Executes the function when the DOM is ready to be used.

jQuery Code

$(function(){
  // Document is ready
});

Example

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 Code

jQuery(function($) {
  // Your code using failsafe $ alias here...
});
$(expr, context)

$(expr, context)

This function accepts a string containing a CSS or basic XPath selector which is then used to match a set of elements.

The core functionality of jQuery centers around this function. Everything in jQuery is based upon this, or uses this in some way. The most basic use of this function is to pass in an expression (usually consisting of CSS or XPath), which then finds all matching elements.

By default, if no context is specified, $() looks for DOM elements within the context of the current HTML document. If you do specify a context, such as a DOM element or jQuery object, the expression will be matched against the contents of that context.

See [[DOM/Traversing/Selectors]] for the allowed CSS/XPath syntax for expressions.

Returns

jQuery

Parameters

  • expr (String): An expression to search with
  • context (Element|jQuery): (optional) A DOM Element, Document or jQuery to use as context

Example

Finds all p elements that are children of a div element.

jQuery Code

$("div > p")

Before

<p>one</p> <div><p>two</p></div> <p>three</p>

Result:

[ <p>two</p> ]

Example

Searches for all inputs of type radio within the first form in the document

jQuery Code

$("input:radio", document.forms[0])

Example

This finds all div elements within the specified XML document.

jQuery Code

$("div", xml.responseXML)
$.extend(prop)

$.extend(prop)

Extends the jQuery object itself. Can be used to add functions into the jQuery namespace and to [[Plugins/Authoring|add plugin methods]] (plugins).

Returns

Object

Parameters

  • prop (Object): The object that will be merged into the jQuery object

Example

Adds two plugin methods.

jQuery Code

jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});
$("input[@type=checkbox]").check();
$("input[@type=radio]").uncheck();

Example

Adds two functions into the jQuery namespace

jQuery Code

jQuery.extend({
  min: function(a, b) { return a < b ? a : b; },
  max: function(a, b) { return a > b ? a : b; }
});
$.noConflict()

$.noConflict()

Run this function to give control of the $ variable back to whichever library first implemented it. This helps to make sure that jQuery doesn't conflict with the $ object of other libraries.

By using this function, you will only be able to access jQuery using the 'jQuery' variable. For example, where you used to do $("div p"), you now must do jQuery("div p").

Returns

undefined

Example

Maps the original object that was referenced by $ back to $

jQuery Code

jQuery.noConflict();
// Do something with jQuery
jQuery("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';

Example

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 Code

jQuery.noConflict();
(function($) { 
  $(function() {
    // more code using $ as alias to jQuery
  });
})(jQuery);
// other code using $ as an alias to the other library
each(fn)

each(fn)

Execute a function within the context of every matched element. This means that every time the passed-in function is executed (which is once for every element matched) the 'this' keyword points to the specific DOM element.

Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set (integer, zero-index).

Returns

jQuery

Parameters

  • fn (Function): A function to execute

Example

Iterates over two images and sets their src property

jQuery Code

$("img").each(function(i){
  this.src = "test" + i + ".jpg";
});

Before

<img/><img/>

Result:

<img src="test0.jpg"/><img src="test1.jpg"/>
eq(pos)

eq(pos)

Reduce the set of matched elements to a single element. The position of the element in the set of matched elements starts at 0 and goes to length - 1.

Returns

jQuery

Parameters

  • pos (Number): The index of the element that you wish to limit to.

Example

jQuery Code

$("p").eq(1)

Before

<p>This is just a test.</p><p>So is this</p>

Result:

[ <p>So is this</p> ]
get()

get()

Access all matched DOM elements. This serves as a backwards-compatible way of accessing all matched elements (other than the jQuery object itself, which is, in fact, an array of elements).

It is useful if you need to operate on the DOM elements themselves instead of using built-in jQuery functions.

Returns

Array<Element>

Example

Selects all images in the document and returns the DOM Elements as an Array

jQuery Code

$("img").get();

Before

<img src="test1.jpg"/> <img src="test2.jpg"/>

Result:

[ <img src="test1.jpg"/> <img src="test2.jpg"/> ]
get(num)

get(num)

Access a single matched DOM element at a specified index in the matched set. This allows you to extract the actual DOM element and operate on it directly without necessarily using jQuery functionality on it.

Returns

Element

Parameters

  • num (Number): Access the element in the Nth position.

Example

Selects all images in the document and returns the first one

jQuery Code

$("img").get(0);

Before

<img src="test1.jpg"/> <img src="test2.jpg"/>

Result:

<img src="test1.jpg"/>
gt(pos)

gt(pos)

Reduce the set of matched elements to all elements after a given position. The position of the element in the set of matched elements starts at 0 and goes to length - 1.

Returns

jQuery

Parameters

  • pos (Number): Reduce the set to all elements after this position.

Example

jQuery Code

$("p").gt(0)

Before

<p>This is just a test.</p><p>So is this</p>

Result:

[ <p>So is this</p> ]
index(subject)

index(subject)

Searches every matched element for the object and returns the index of the element, if found, starting with zero. Returns -1 if the object wasn't found.

Returns

Number

Parameters

  • subject (Element): Object to search for

Example

Returns the index for the element with ID foobar

jQuery Code

$("*").index( $('#foobar')[0] )

Before

<div id="foobar"><b></b><span id="foo"></span></div>

Result:

0

Example

Returns the index for the element with ID foo within another element

jQuery Code

$("*").index( $('#foo')[0] )

Before

<div id="foobar"><b></b><span id="foo"></span></div>

Result:

2

Example

Returns -1, as there is no element with ID bar

jQuery Code

$("*").index( $('#bar')[0] )

Before

<div id="foobar"><b></b><span id="foo"></span></div>

Result:

-1
length

length

The number of elements currently matched. The size function will return the same value.

Returns

Number

Example

jQuery Code

$("img").length;

Before

<img src="test1.jpg"/> <img src="test2.jpg"/>

Result:

2
lt(pos)

lt(pos)

Reduce the set of matched elements to all elements before a given position. The position of the element in the set of matched elements starts at 0 and goes to length - 1.

Returns

jQuery

Parameters

  • pos (Number): Reduce the set to all elements below this position.

Example

jQuery Code

$("p").lt(1)

Before

<p>This is just a test.</p><p>So is this</p>

Result:

[ <p>This is just a test.</p> ]
size()

size()

Get the number of elements currently matched. This returns the same number as the 'length' property of the jQuery object.

Returns

Number

Example

jQuery Code

$("img").size();

Before

<img src="test1.jpg"/> <img src="test2.jpg"/>

Result:

2
DOM
Attributes
addClass(class)

addClass(class)

Adds the specified class(es) to each of the set of matched elements.

Returns

jQuery

Parameters

  • class (String): One or more CSS classes to add to the elements

Example

jQuery Code

$("p").addClass("selected")

Before

<p>Hello</p>

Result:

[ <p class="selected">Hello</p> ]

Example

jQuery Code

$("p").addClass("selected highlight")

Before

<p>Hello</p>

Result:

[ <p class="selected highlight">Hello</p> ]
attr(name)

attr(name)

Access a property on the first matched element. This method makes it easy to retrieve a property value from the first matched element.

If the element does not have an attribute with such a name, undefined is returned.

Returns

Object

Parameters

  • name (String): The name of the property to access.

Example

Returns the src attribute from the first image in the document.

jQuery Code

$("img").attr("src");

Before

<img src="test.jpg"/>

Result:

test.jpg
attr(properties)

attr(properties)

Set a key/value object as properties to all matched elements.

This serves as the best way to set a large number of properties on all matched elements.

Returns

jQuery

Parameters

  • properties (Map): Key/value pairs to set as object properties.

Example

Sets src and alt attributes to all images.

jQuery Code

$("img").attr({ src: "test.jpg", alt: "Test Image" });

Before

<img/>

Result:

<img src="test.jpg" alt="Test Image"/>
attr(key, value)

attr(key, value)

Set a single property to a value, on all matched elements.

Note that you can't set the name property of input elements in IE. Use $(html) or .append(html) or .html(html) to create elements on the fly including the name property.

Returns

jQuery

Parameters

  • key (String): The name of the property to set.
  • value (Object): The value to set the property to.

Example

Sets src attribute to all images.

jQuery Code

$("img").attr("src","test.jpg");

Before

<img/>

Result:

<img src="test.jpg"/>
attr(key, value)

attr(key, value)

Set a single property to a computed value, on all matched elements.

Instead of supplying a string value as described [[DOM/Attributes#attr.28_key.2C_value_.29|above]], a function is provided that computes the value.

Returns

jQuery

Parameters

  • key (String): The name of the property to set.
  • value (Function): A function returning the value to set. Scope: Current element, argument: Index of current element

Example

Sets title attribute from src attribute.

jQuery Code

$("img").attr("title", function() { return this.src });

Before

<img src="test.jpg" />

Result:

<img src="test.jpg" title="test.jpg" />

Example

Enumerate title attribute.

jQuery Code

$("img").attr("title", function(index) { return this.title + (i + 1); });

Before

<img title="pic" /><img title="pic" /><img title="pic" />

Result:

<img title="pic1" /><img title="pic2" /><img title="pic3" />
html()

html()

Get the html contents of the first matched element. This property is not available on XML documents.

Returns

String

Example

jQuery Code

$("div").html();

Before

<div><input/></div>

Result:

<input/>
html(val)

html(val)

Set the html contents of every matched element. This property is not available on XML documents.

Returns

jQuery

Parameters

  • val (String): Set the html contents to the specified value.

Example

jQuery Code

$("div").html("<b>new stuff</b>");

Before

<div><input/></div>

Result:

<div><b>new stuff</b></div>
removeAttr(name)

removeAttr(name)

Remove an attribute from each of the matched elements.

Returns

jQuery

Parameters

  • name (String): The name of the attribute to remove.

Example

jQuery Code

$("input").removeAttr("disabled")

Before

<input disabled="disabled"/>

Result:

<input/>
removeClass(class)

removeClass(class)

Removes all or the specified class(es) from the set of matched elements.

Returns

jQuery

Parameters

  • class (String): (optional) One or more CSS classes to remove from the elements

Example

jQuery Code

$("p").removeClass()

Before

<p class="selected">Hello</p>

Result:

[ <p>Hello</p> ]

Example

jQuery Code

$("p").removeClass("selected")

Before

<p class="selected first">Hello</p>

Result:

[ <p class="first">Hello</p> ]

Example

jQuery Code

$("p").removeClass("selected highlight")

Before

<p class="highlight selected first">Hello</p>

Result:

[ <p class="first">Hello</p> ]
text()

text()

Get the text contents of all matched elements. The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents.

Returns

String

Example

Gets the concatenated text of all paragraphs

jQuery Code

$("p").text();

Before

<p><b>Test</b> Paragraph.</p><p>Paraparagraph</p>

Result:

Test Paragraph.Paraparagraph
text(val)

text(val)

Set the text contents of all matched elements.

Similar to html(), but escapes HTML (replace "<" and ">" with their HTML entities).

Returns

String

Parameters

  • val (String): The text value to set the contents of the element to.

Example

Sets the text of all paragraphs.

jQuery Code

$("p").text("<b>Some</b> new text.");

Before

<p>Test Paragraph.</p>

Result:

<p>&lt;b&gt;Some&lt;/b&gt; new text.</p>

Example

Sets the text of all paragraphs.

jQuery Code

$("p").text("<b>Some</b> new text.", true);

Before

<p>Test Paragraph.</p>

Result:

<p>Some new text.</p>
toggleClass(class)

toggleClass(class)

Adds the specified class if it is not present, removes it if it is present.

Returns

jQuery

Parameters

  • class (String): A CSS class with which to toggle the elements

Example

jQuery Code

$("p").toggleClass("selected")

Before

<p>Hello</p><p class="selected">Hello Again</p>

Result:

[ <p class="selected">Hello</p>, <p>Hello Again</p> ]
val()

val()

Get the content of the value attribute of the first matched element.

Use caution when relying on this function to check the value of multiple-select elements and checkboxes in a form. While it will still work as intended, it may not accurately represent the value the server will receive because these elements may send an array of values. For more robust handling of field values, see the [http://www.malsup.com/jquery/form/#fields fieldValue function of the Form Plugin].

Returns

String

Example

jQuery Code

$("input").val();

Before

<input type="text" value="some text"/>

Result:

"some text"
val(val)

val(val)

Set the value attribute of every matched element.

Returns

jQuery

Parameters

  • val (String): Set the property to the specified value.

Example

jQuery Code

$("input").val("test");

Before

<input type="text" value="some text"/>

Result:

<input type="text" value="test"/>
Manipulation
after(content)

after(content)

Insert content after each of the matched elements.

Returns

jQuery

Parameters

  • content (<Content>): Content to insert after each target.

Example

Inserts some HTML after all paragraphs.

jQuery Code

$("p").after("<b>Hello</b>");

Before

<p>I would like to say: </p>

Result:

<p>I would like to say: </p><b>Hello</b>

Example

Inserts an Element after all paragraphs.

jQuery Code

$("p").after( $("#foo")[0] );

Before

<b id="foo">Hello</b><p>I would like to say: </p>

Result:

<p>I would like to say: </p><b id="foo">Hello</b>

Example

Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs.

jQuery Code

$("p").after( $("b") );

Before

<b>Hello</b><p>I would like to say: </p>

Result:

<p>I would like to say: </p><b>Hello</b>
append(content)

append(content)

Append content to the inside of every matched element.

This operation is similar to doing an appendChild to all the specified elements, adding them into the document.

Returns

jQuery

Parameters

  • content (<Content>): Content to append to the target

Example

Appends some HTML to all paragraphs.

jQuery Code

$("p").append("<b>Hello</b>");

Before

<p>I would like to say: </p>

Result:

<p>I would like to say: <b>Hello</b></p>

Example

Appends an Element to all paragraphs.

jQuery Code

$("p").append( $("#foo")[0] );

Before

<p>I would like to say: </p><b id="foo">Hello</b>

Result:

<p>I would like to say: <b id="foo">Hello</b></p>

Example

Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.

jQuery Code

$("p").append( $("b") );

Before

<p>I would like to say: </p><b>Hello</b>

Result:

<p>I would like to say: <b>Hello</b></p>
appendTo(content)

appendTo(content)

Append all of the matched elements to another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).append(B), in that instead of appending B to A, you're appending A to B.

Returns

jQuery

Parameters

  • content (<Content>): Content to append to the selected element to.

Example

Appends all paragraphs to the element with the ID "foo"

jQuery Code

$("p").appendTo("#foo");

Before

<p>I would like to say: </p><div id="foo"></div>

Result:

<div id="foo"><p>I would like to say: </p></div>
before(content)

before(content)

Insert content before each of the matched elements.

Returns

jQuery

Parameters

  • content (<Content>): Content to insert before each target.

Example

Inserts some HTML before all paragraphs.

jQuery Code

$("p").before("<b>Hello</b>");

Before

<p>I would like to say: </p>

Result:

<b>Hello</b><p>I would like to say: </p>

Example

Inserts an Element before all paragraphs.

jQuery Code

$("p").before( $("#foo")[0] );

Before

<p>I would like to say: </p><b id="foo">Hello</b>

Result:

<b id="foo">Hello</b><p>I would like to say: </p>

Example

Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs.

jQuery Code

$("p").before( $("b") );

Before

<p>I would like to say: </p><b>Hello</b>

Result:

<b>Hello</b><p>I would like to say: </p>
clone(deep)

clone(deep)

Clone matched DOM Elements and select the clones.

This is useful for moving copies of the elements to another location in the DOM.

Returns

jQuery

Parameters

  • deep (Boolean): (Optional) Set to false if you don't want to clone all descendant nodes, in addition to the element itself.

Example

Clones all b elements (and selects the clones) and prepends them to all paragraphs.

jQuery Code

$("b").clone().prependTo("p");

Before

<b>Hello</b><p>, how are you?</p>

Result:

<b>Hello</b><p><b>Hello</b>, how are you?</p>
empty()

empty()

Removes all child nodes from the set of matched elements.

Returns

jQuery

Example

jQuery Code

$("p").empty()

Before

<p>Hello, <span>Person</span> <a href="#">and person</a></p>

Result:

[ <p></p> ]
insertAfter(content)

insertAfter(content)

Insert all of the matched elements after another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).after(B), in that instead of inserting B after A, you're inserting A after B.

Returns

jQuery

Parameters

  • content (<Content>): Content to insert the selected element after.

Example

Same as $("#foo").after("p")

jQuery Code

$("p").insertAfter("#foo");

Before

<p>I would like to say: </p><div id="foo">Hello</div>

Result:

<div id="foo">Hello</div><p>I would like to say: </p>
insertBefore(content)

insertBefore(content)

Insert all of the matched elements before another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).before(B), in that instead of inserting B before A, you're inserting A before B.

Returns

jQuery

Parameters

  • content (<Content>): Content to insert the selected element before.

Example

Same as $("#foo").before("p")

jQuery Code

$("p").insertBefore("#foo");

Before

<div id="foo">Hello</div><p>I would like to say: </p>

Result:

<p>I would like to say: </p><div id="foo">Hello</div>
prepend(content)

prepend(content)

Prepend content to the inside of every matched element.

This operation is the best way to insert elements inside, at the beginning, of all matched elements.

Returns

jQuery

Parameters

  • content (<Content>): Content to prepend to the target.

Example

Prepends some HTML to all paragraphs.

jQuery Code

$("p").prepend("<b>Hello</b>");

Before

<p>I would like to say: </p>

Result:

<p><b>Hello</b>I would like to say: </p>

Example

Prepends an Element to all paragraphs.

jQuery Code

$("p").prepend( $("#foo")[0] );

Before

<p>I would like to say: </p><b id="foo">Hello</b>

Result:

<p><b id="foo">Hello</b>I would like to say: </p>

Example

Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.

jQuery Code

$("p").prepend( $("b") );

Before

<p>I would like to say: </p><b>Hello</b>

Result:

<p><b>Hello</b>I would like to say: </p>
prependTo(content)

prependTo(content)

Prepend all of the matched elements to another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).prepend(B), in that instead of prepending B to A, you're prepending A to B.

Returns

jQuery

Parameters

  • content (<Content>): Content to prepend to the selected element to.

Example

Prepends all paragraphs to the element with the ID "foo"

jQuery Code

$("p").prependTo("#foo");

Before

<p>I would like to say: </p><div id="foo"><b>Hello</b></div>

Result:

<div id="foo"><p>I would like to say: </p><b>Hello</b></div>
remove(expr)

remove(expr)

Removes all matched elements from the DOM. This does NOT remove them from the jQuery object, allowing you to use the matched elements further.

Can be filtered with an optional expressions.

Returns

jQuery

Parameters

  • expr (String): (optional) A jQuery expression to filter elements by.

Example

jQuery Code

$("p").remove();

Before

<p>Hello</p> how are <p>you?</p>

Result:

how are

Example

jQuery Code

$("p").remove(".hello");

Before

<p class="hello">Hello</p> how are <p>you?</p>

Result:

how are <p>you?</p>
wrap(html)

wrap(html)

Wrap all matched elements with a structure of other elements. This wrapping process is most useful for injecting additional stucture into a document, without ruining the original semantic qualities of a document.

This works by going through the first element provided (which is generated, on the fly, from the provided HTML) and finds the deepest ancestor element within its structure - it is that element that will en-wrap everything else.

This does not work with elements that contain text. Any necessary text must be added after the wrapping is done.

Returns

jQuery

Parameters

  • html (String): A string of HTML, that will be created on the fly and wrapped around the target.

Example

jQuery Code

$("p").wrap("<div class='wrap'></div>");

Before

<p>Test Paragraph.</p>

Result:

<div class='wrap'><p>Test Paragraph.</p></div>
wrap(elem)

wrap(elem)

Wrap all matched elements with a structure of other elements. This wrapping process is most useful for injecting additional stucture into a document, without ruining the original semantic qualities of a document.

This works by going through the first element provided and finding the deepest ancestor element within its structure - it is that element that will en-wrap everything else.

This does not work with elements that contain text. Any necessary text must be added after the wrapping is done.

Returns

jQuery

Parameters

  • elem (Element): A DOM element that will be wrapped around the target.

Example

jQuery Code

$("p").wrap( document.getElementById('content') );

Before

<p>Test Paragraph.</p><div id="content"></div>

Result:

<div id="content"><p>Test Paragraph.</p></div>
Traversing
add(expr)

add(expr)

Adds more elements, matched by the given expression, to the set of matched elements.

Returns

jQuery

Parameters

  • expr (String): An expression whose matched elements are added

Example

Compare the above result to the result of <code>$('p')</code>, which would just result in <code><nowiki>[ <p>Hello</p> ]</nowiki></code>. Using add(), matched elements of <code>$('span')</code> are simply added to the returned jQuery-object.

jQuery Code

$("p").add("span")

Before

(HTML) <p>Hello</p><span>Hello Again</span>

Result:

(jQuery object matching 2 elements) [ <p>Hello</p>, <span>Hello Again</span> ]
add(html)

add(html)

Adds more elements, created on the fly, to the set of matched elements.

Returns

jQuery

Parameters

  • html (String): A string of HTML to create on the fly.

Example

jQuery Code

$("p").add("<span>Again</span>")

Before

<p>Hello</p>

Result:

[ <p>Hello</p>, <span>Again</span> ]
add(elements)

add(elements)

Adds one or more Elements to the set of matched elements.

Returns

jQuery

Parameters

  • elements (Element|Array<Element>): One or more Elements to add

Example

jQuery Code

$("p").add( document.getElementById("a") )

Before

<p>Hello</p><p><span id="a">Hello Again</span></p>

Result:

[ <p>Hello</p>, <span id="a">Hello Again</span> ]

Example

jQuery Code

$("p").add( document.forms[0].elements )

Before

<p>Hello</p><p><form><input/><button/></form>

Result:

[ <p>Hello</p>, <input/>, <button/> ]
children(expr)

children(expr)

Get a set of elements containing all of the unique children of each of the matched set of elements.

This set can be filtered with an optional expression that will cause only elements matching the selector to be collected.

Returns

jQuery

Parameters

  • expr (String): (optional) An expression to filter the child Elements with

Example

Find all children of each div.

jQuery Code

$("div").children()

Before

<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>

Result:

[ <span>Hello Again</span> ]

Example

Find all children with a class "selected" of each div.

jQuery Code

$("div").children(".selected")

Before

<div><span>Hello</span><p class="selected">Hello Again</p><p>And Again</p></div>

Result:

[ <p class="selected">Hello Again</p> ]
contains(str)

contains(str)

Filter the set of elements to those that contain the specified text.

Returns

jQuery

Parameters

  • str (String): The string that will be contained within the text of an element.

Example

jQuery Code

$("p").contains("test")

Before

<p>This is just a test.</p><p>So is this</p>

Result:

[ <p>This is just a test.</p> ]
end()

end()

Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state (right before the destructive operation).

If there was no destructive operation before, an empty set is returned.

A 'destructive' operation is any operation that changes the set of matched jQuery elements. These functions are: <code>add</code>, <code>children</code>, <code>clone</code>, <code>filter</code>, <code>find</code>, <code>not</code>, <code>next</code>, <code>parent</code>, <code>parents</code>, <code>prev</code> and <code>siblings</code>.

Returns

jQuery

Example

Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.

jQuery Code

$("p").find("span").end();

Before

<p><span>Hello</span>, how are you?</p>

Result:

[ <p>...</p> ]
filter(expression)

filter(expression)

Removes all elements from the set of matched elements that do not match the specified expression(s). This method is used to narrow down the results of a search.

Provide a comma-separated list of expressions to apply multiple filters at once.

Returns

jQuery

Parameters

  • expression (String): Expression(s) to search with.

Example

Selects all paragraphs and removes those without a class "selected".

jQuery Code

$("p").filter(".selected")

Before

<p class="selected">Hello</p><p>How are you?</p>

Result:

[ <p class="selected">Hello</p> ]

Example

Selects all paragraphs and removes those without class "selected" and being the first one.

jQuery Code

$("p").filter(".selected, :first")

Before

<p>Hello</p><p>Hello Again</p><p class="selected">And Again</p>

Result:

[ <p>Hello</p>, <p class="selected">And Again</p> ]
filter(filter)

filter(filter)

Removes all elements from the set of matched elements that do not pass the specified filter. This method is used to narrow down the results of a search.

Returns

jQuery

Parameters

  • filter (Function): A function to use for filtering

Example

Remove all elements that have a child ol element

jQuery Code

$("p").filter(function(index) {
  return $("ol", this).length == 0;
})

Before

<p><ol><li>Hello</li></ol></p><p>How are you?</p>

Result:

[ <p>How are you?</p> ]
find(expr)

find(expr)

Searches for all elements that match the specified expression. This method is a good way to find additional descendant elements with which to process.

All searching is done using a jQuery expression. The expression can be written using CSS 1-3 Selector syntax, or basic XPath.

Returns

jQuery

Parameters

  • expr (String): An expression to search with.

Example

Starts with all paragraphs and searches for descendant span elements, same as $("p span")

jQuery Code

$("p").find("span");

Before

<p><span>Hello</span>, how are you?</p>

Result:

[ <span>Hello</span> ]
is(expr)

is(expr)

Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression.

Does return false, if no element fits or the expression is not valid.

filter(String) is used internally, therefore all rules that apply there apply here, too.

Returns

Boolean

Parameters

  • expr (String): The expression with which to filter

Example

Returns true, because the parent of the input is a form element

jQuery Code

$("input[@type='checkbox']").parent().is("form")

Before

<form><input type="checkbox" /></form>

Result:

true

Example

Returns false, because the parent of the input is a p element

jQuery Code

$("input[@type='checkbox']").parent().is("form")

Before

<form><p><input type="checkbox" /></p></form>

Result:

false
next(expr)

next(expr)

Get a set of elements containing the unique next siblings of each of the matched set of elements.

It only returns the very next sibling for each element, not all next siblings.

You may provide an optional expression to filter the match.

Returns

jQuery

Parameters

  • expr (String): (optional) An expression to filter the next Elements with

Example

Find the very next sibling of each paragraph.

jQuery Code

$("p").next()

Before

<p>Hello</p><p>Hello Again</p><div><span>And Again</span></div>

Result:

[ <p>Hello Again</p>, <div><span>And Again</span></div> ]

Example

Find the very next sibling of each paragraph that has a class "selected".

jQuery Code

$("p").next(".selected")

Before

<p>Hello</p><p class="selected">Hello Again</p><div><span>And Again</span></div>

Result:

[ <p class="selected">Hello Again</p> ]
not(el)

not(el)

Removes the specified Element from the set of matched elements. This method is used to remove a single Element from a jQuery object.

Returns

jQuery

Parameters

  • el (Element): An element to remove from the set

Example

Removes the element with the ID "selected" from the set of all paragraphs.

jQuery Code

$("p").not( $("#selected")[0] )

Before

<p>Hello</p><p id="selected">Hello Again</p>

Result:

[ <p>Hello</p> ]
not(expr)

not(expr)

Removes elements matching the specified expression from the set of matched elements. This method is used to remove one or more elements from a jQuery object.

Returns

jQuery

Parameters

  • expr (String): An expression with which to remove matching elements

Example

Removes the element with the ID "selected" from the set of all paragraphs.

jQuery Code

$("p").not("#selected")

Before

<p>Hello</p><p id="selected">Hello Again</p>

Result:

[ <p>Hello</p> ]
not(elems)

not(elems)

Removes any elements inside the array of elements from the set of matched elements. This method is used to remove one or more elements from a jQuery object.

Please note: the expression cannot use a reference to the element name. See the two examples below.

Returns

jQuery

Parameters

  • elems (jQuery): A set of elements to remove from the jQuery set of matched elements.

Example

Removes all elements that match "div p.selected" from the total set of all paragraphs.

jQuery Code

$("p").not( $("div p.selected") )

Before

<div><p>Hello</p><p class="selected">Hello Again</p></div>

Result:

[ <p>Hello</p> ]
parent(expr)

parent(expr)

Get a set of elements containing the unique parents of the matched set of elements.

You may use an optional expression to filter the set of parent elements that will match.

Returns

jQuery

Parameters

  • expr (String): (optional) An expression to filter the parents with

Example

Find the parent element of each paragraph.

jQuery Code

$("p").parent()

Before

<div><p>Hello</p><p>Hello</p></div>

Result:

[ <div><p>Hello</p><p>Hello</p></div> ]

Example

Find the parent element of each paragraph with a class "selected".

jQuery Code

$("p").parent(".selected")

Before

<div><p>Hello</p></div><div class="selected"><p>Hello Again</p></div>

Result:

[ <div class="selected"><p>Hello Again</p></div> ]
parents(expr)

parents(expr)

Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).

The matched elements can be filtered with an optional expression.

Returns

jQuery

Parameters

  • expr (String): (optional) An expression to filter the ancestors with

Example

Find all parent elements of each span.

jQuery Code

$("span").parents()

Before

<html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html>

Result:

[ <body>...</body>, <div>...</div>, <p><span>Hello</span></p> ]

Example

Find all parent elements of each span that is a paragraph.

jQuery Code

$("span").parents("p")

Before

<html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html>

Result:

[ <p><span>Hello</span></p> ]
prev(expr)

prev(expr)

Get a set of elements containing the unique previous siblings of each of the matched set of elements.

Use an optional expression to filter the matched set.

Only the immediately previous sibling is returned, not all previous siblings.

Returns

jQuery

Parameters

  • expr (String): (optional) An expression to filter the previous Elements with

Example

Find the very previous sibling of each paragraph.

jQuery Code

$("p").prev()

Before

<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>

Result:

[ <div><span>Hello Again</span></div> ]

Example

Find the very previous sibling of each paragraph that has a class "selected".

jQuery Code

$("p").prev(".selected")

Before

<div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p>

Result:

[ <div><span>Hello</span></div> ]
siblings(expr)

siblings(expr)

Get a set of elements containing all of the unique siblings of each of the matched set of elements.

Can be filtered with an optional expressions.

Returns

jQuery

Parameters

  • expr (String): (optional) An expression to filter the sibling Elements with

Example

Find all siblings of each div.

jQuery Code

$("div").siblings()

Before

<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>

Result:

[ <p>Hello</p>, <p>And Again</p> ]

Example

Find all siblings with a class "selected" of each div.

jQuery Code

$("div").siblings(".selected")

Before

<div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p>

Result:

[ <p class="selected">Hello Again</p> ]
CSS
css(name)

css(name)

Access a style property on the first matched element. This method makes it easy to retrieve a style property value from the first matched element.

Returns

String

Parameters

  • name (String): The name of the property to access.

Example

Retrieves the color style of the first paragraph

jQuery Code

$("p").css("color");

Before

<p style="color:red;">Test Paragraph.</p>

Result:

"red"

Example

Retrieves the font-weight style of the first paragraph.

jQuery Code

$("p").css("font-weight");

Before

<p style="font-weight: bold;">Test Paragraph.</p>

Result:

"bold"
css(properties)

css(properties)

Set a key/value object as style properties to all matched elements.

This serves as the best way to set a large number of style properties on all matched elements.

Returns

jQuery

Parameters

  • properties (Map): Key/value pairs to set as style properties.

Example

Sets color and background styles to all p elements.

jQuery Code

$("p").css({ color: "red", background: "blue" });

Before

<p>Test Paragraph.</p>

Result:

<p style="color:red; background:blue;">Test Paragraph.</p>
css(key, value)

css(key, value)

Set a single style property to a value, on all matched elements. If a number is provided, it is automatically converted into a pixel value.

Returns

jQuery

Parameters

  • key (String): The name of the property to set.
  • value (String|Number): The value to set the property to.

Example

Changes the color of all paragraphs to red

jQuery Code

$("p").css("color","red");

Before

<p>Test Paragraph.</p>

Result:

<p style="color:red;">Test Paragraph.</p>

Example

Changes the left of all paragraphs to "30px"

jQuery Code

$("p").css("left",30);

Before

<p>Test Paragraph.</p>

Result:

<p style="left:30px;">Test Paragraph.</p>
height()

height()

Get the current computed, pixel, height of the first matched element.

Returns

String

Example

jQuery Code

$("p").height();

Before

<p>This is just a test.</p>

Result:

300
height(val)

height(val)

Set the CSS height of every matched element. If no explicit unit was specified (like 'em' or '%') then "px" is added to the width.

Returns

jQuery

Parameters

  • val (String|Number): Set the CSS property to the specified value.

Example

jQuery Code

$("p").height(20);

Before

<p>This is just a test.</p>

Result:

<p style="height:20px;">This is just a test.</p>

Example

jQuery Code

$("p").height("20em");

Before

<p>This is just a test.</p>

Result:

<p style="height:20em;">This is just a test.</p>
width()

width()

Get the current computed, pixel, width of the first matched element.

Returns

String

Example

jQuery Code

$("p").width();

Before

<p>This is just a test.</p>

Result:

300
width(val)

width(val)

Set the CSS width of every matched element. If no explicit unit was specified (like 'em' or '%') then "px" is added to the width.

Returns

jQuery

Parameters

  • val (String|Number): Set the CSS property to the specified value.

Example

jQuery Code

$("p").width(20);

Before

<p>This is just a test.</p>

Result:

<p style="width:20px;">This is just a test.</p>

Example

jQuery Code

$("p").width("20em");

Before

<p>This is just a test.</p>

Result:

<p style="width:20em;">This is just a test.</p>
JavaScript
$.browser

$.browser

Contains flags for the useragent, read from navigator.userAgent. Available flags are: safari, opera, msie, mozilla

This property is available before the DOM is ready, therefore you can use it to add ready events only for certain browsers.

There are situations where object detections is not reliable enough, in that cases it makes sense to use browser detection. Simply try to avoid both!

A combination of browser and object detection yields quite reliable results.

Returns

Boolean

Example

Returns true if the current useragent is some version of microsoft's internet explorer

jQuery Code

$.browser.msie

Example

Alerts "this is safari!" only for safari browsers

jQuery Code

if($.browser.safari) { $( function() { alert("this is safari!"); } ); }
$.each(obj, fn)

$.each(obj, fn)

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. This function is not the same as $().each() - which is used to iterate, exclusively, over a jQuery object. This function can be used to iterate over anything.

The callback has two arguments:the key (objects) or index (arrays) as first the first, and the value as the second.

Returns

Object

Parameters

  • obj (Object): The object, or array, to iterate over.
  • fn (Function): The function that will be executed on every object.

Example

This is an example of iterating over the items in an array, accessing both the current item and its index.

jQuery Code

$.each( [0,1,2], function(i, n){
  alert( "Item #" + i + ": " + n );
});

Example

This is an example of iterating over the properties in an Object, accessing both the current item and its key.

jQuery Code

$.each( { name: "John", lang: "JS" }, function(i, n){
  alert( "Name: " + i + ", Value: " + n );
});
$.extend(target, prop1, propN)

$.extend(target, prop1, propN)

Extend one object with one or more others, returning the original, modified, object. This is a great utility for simple inheritance.

Returns

Object

Parameters

  • target (Object): The object to extend
  • prop1 (Object): The object that will be merged into the first.
  • propN (Object): (optional) More objects to merge into the first

Example

Merge settings and options, modifying settings

jQuery Code

var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);

Result:

settings == { validate: true, limit: 5, name: "bar" }

Example

Merge defaults and options, without modifying the defaults

jQuery Code

var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = jQuery.extend({}, defaults, options);

Result:

settings == { validate: true, limit: 5, name: "bar" }
$.grep(array, fn, inv)

$.grep(array, fn, inv)

Filter items out of an array, by using a filter function.

The specified function will be passed two arguments: The current array item and the index of the item in the array. The function must return 'true' to keep the item in the array, false to remove it.

Returns

Array

Parameters

  • array (Array): The Array to find items in.
  • fn (Function): The function to process each item against.
  • inv (Boolean): Invert the selection - select the opposite of the function.

Example

jQuery Code

$.grep( [0,1,2], function(i){
  return i > 0;
});

Result:

[1, 2]
$.map(array, fn)

$.map(array, fn)

Translate all items in an array to another array of items.

The translation function that is provided to this method is called for each item in the array and is passed one argument: The item to be translated.

The function can then return the translated value, 'null' (to remove the item), or an array of values - which will be flattened into the full array.

Returns

Array

Parameters

  • array (Array): The Array to translate.
  • fn (Function): The function to process each item against.

Example

Maps the original array to a new one and adds 4 to each value.

jQuery Code

$.map( [0,1,2], function(i){
  return i + 4;
});

Result:

[4, 5, 6]

Example

Maps the original array to a new one and adds 1 to each value if it is bigger then zero, otherwise it's removed-

jQuery Code

$.map( [0,1,2], function(i){
  return i > 0 ? i + 1 : null;
});

Result:

[2, 3]

Example

Maps the original array to a new one, each element is added with it's original value and the value plus one.

jQuery Code

$.map( [0,1,2], function(i){
  return [ i, i + 1 ];
});

Result:

[0, 1, 1, 2, 2, 3]
$.merge(first, second)

$.merge(first, second)

Merge two arrays together, removing all duplicates.

The result is the altered first argument with the unique elements from the second array added.

Returns

Array

Parameters

  • first (Array): The first array to merge, the unique elements of second added.
  • second (Array): The second array to merge into the first, unaltered.

Example

Merges two arrays, removing the duplicate 2

jQuery Code

$.merge( [0,1,2], [2,3,4] )

Result:

[0,1,2,3,4]

Example

Merges two arrays, removing the duplicates 3 and 2

jQuery Code

var array = [3,2,1];
$.merge( array, [4,3,2] )

Result:

array == [3,2,1,4]
$.trim(str)

$.trim(str)

Remove the whitespace from the beginning and end of a string.

Returns

String

Parameters

  • str (String): The string to trim.

Example

jQuery Code

$.trim("  hello, how are you?  ");

Result:

"hello, how are you?"
Events
bind(type, data, fn)

bind(type, data, fn)

Binds a handler to a particular event (like click) for each matched element. The event handler is passed an event object that you can use to prevent default behaviour. To stop both default action and event bubbling, your handler has to return false.

In most cases, you can define your event handlers as anonymous functions (see first example). In cases where that is not possible, you can pass additional data as the second parameter (and the handler function as the third), see second example.

Returns

jQuery

Parameters

  • type (String): An event type
  • data (Object): (optional) Additional data passed to the event handler as event.data
  • fn (Function): A function to bind to the event on each of the set of matched elements

Example

jQuery Code

$("p").bind("click", function(){
  alert( $(this).text() );
});

Before

<p>Hello</p>

Result:

alert("Hello")

Example

Pass some additional data to the event handler.

jQuery Code

function handler(event) {
  alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)

Result:

alert("bar")

Example

Cancel a default action and prevent it from bubbling by returning false from your function.

jQuery Code

$("form").bind("submit", function() { return false; })

Example

Cancel only the default action by using the preventDefault method.

jQuery Code

$("form").bind("submit", function(event){
  event.preventDefault();
});

Example

Stop only an event from bubbling by using the stopPropagation method.

jQuery Code

$("form").bind("submit", function(event){
  event.stopPropagation();
});
blur()

blur()

Trigger the blur event of each matched element. This causes all of the functions that have been bound to that blur event to be executed, and calls the browser's default blur action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the blur event.

Note: This does not execute the blur method of the underlying elements! If you need to blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();

Returns

jQuery

Example

jQuery Code

$("p").blur();

Before

<p onblur="alert('Hello');">Hello</p>

Result:

alert('Hello');
blur(fn)

blur(fn)

Bind a function to the blur event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the blur event on each of the matched elements.

Example

jQuery Code

$("p").blur( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onblur="alert('Hello');">Hello</p>
change(fn)

change(fn)

Bind a function to the change event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the change event on each of the matched elements.

Example

jQuery Code

$("p").change( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onchange="alert('Hello');">Hello</p>
click()

click()

Trigger the click event of each matched element. This causes all of the functions that have been bound to thet click event to be executed.

Returns

jQuery

Example

jQuery Code

$("p").click();

Before

<p onclick="alert('Hello');">Hello</p>

Result:

alert('Hello');
click(fn)

click(fn)

Bind a function to the click event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the click event on each of the matched elements.

Example

jQuery Code

$("p").click( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onclick="alert('Hello');">Hello</p>
dblclick(fn)

dblclick(fn)

Bind a function to the dblclick event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the dblclick event on each of the matched elements.

Example

jQuery Code

$("p").dblclick( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p ondblclick="alert('Hello');">Hello</p>
error(fn)

error(fn)

Bind a function to the error event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the error event on each of the matched elements.

Example

jQuery Code

$("p").error( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onerror="alert('Hello');">Hello</p>
focus()

focus()

Trigger the focus event of each matched element. This causes all of the functions that have been bound to thet focus event to be executed.

Note: This does not execute the focus method of the underlying elements! If you need to focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();

Returns

jQuery

Example

jQuery Code

$("p").focus();

Before

<p onfocus="alert('Hello');">Hello</p>

Result:

alert('Hello');
focus(fn)

focus(fn)

Bind a function to the focus event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the focus event on each of the matched elements.

Example

jQuery Code

$("p").focus( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onfocus="alert('Hello');">Hello</p>
hover(over, out)

hover(over, out)

A method for simulating hovering (moving the mouse on, and off, an object). This is a custom method which provides an 'in' to a frequent task.

Whenever the mouse cursor is moved over a matched element, the first specified function is fired. Whenever the mouse moves off of the element, the second specified function fires. Additionally, checks are in place to see if the mouse is still within the specified element itself (for example, an image inside of a div), and if it is, it will continue to 'hover', and not move out (a common error in using a mouseout event handler).

Returns

jQuery

Parameters

  • over (Function): The function to fire whenever the mouse is moved over a matched element.
  • out (Function): The function to fire whenever the mouse is moved off of a matched element.

Example

jQuery Code

$("p").hover(function(){
  $(this).addClass("hover");
},function(){
  $(this).removeClass("hover");
});
keydown(fn)

keydown(fn)

Bind a function to the keydown event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the keydown event on each of the matched elements.

Example

jQuery Code

$("p").keydown( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onkeydown="alert('Hello');">Hello</p>
keypress(fn)

keypress(fn)

Bind a function to the keypress event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the keypress event on each of the matched elements.

Example

jQuery Code

$("p").keypress( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onkeypress="alert('Hello');">Hello</p>
keyup(fn)

keyup(fn)

Bind a function to the keyup event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the keyup event on each of the matched elements.

Example

jQuery Code

$("p").keyup( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onkeyup="alert('Hello');">Hello</p>
load(fn)

load(fn)

Bind a function to the load event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the load event on each of the matched elements.

Example

jQuery Code

$("p").load( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onload="alert('Hello');">Hello</p>
mousedown(fn)

mousedown(fn)

Bind a function to the mousedown event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the mousedown event on each of the matched elements.

Example

jQuery Code

$("p").mousedown( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onmousedown="alert('Hello');">Hello</p>
mousemove(fn)

mousemove(fn)

Bind a function to the mousemove event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the mousemove event on each of the matched elements.

Example

jQuery Code

$("p").mousemove( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onmousemove="alert('Hello');">Hello</p>
mouseout(fn)

mouseout(fn)

Bind a function to the mouseout event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the mouseout event on each of the matched elements.

Example

jQuery Code

$("p").mouseout( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onmouseout="alert('Hello');">Hello</p>
mouseover(fn)

mouseover(fn)

Bind a function to the mouseover event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the mousedown event on each of the matched elements.

Example

jQuery Code

$("p").mouseover( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onmouseover="alert('Hello');">Hello</p>
mouseup(fn)

mouseup(fn)

Bind a function to the mouseup event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the mouseup event on each of the matched elements.

Example

jQuery Code

$("p").mouseup( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onmouseup="alert('Hello');">Hello</p>
one(type, data, fn)

one(type, data, fn)

Binds a handler to a particular event (like click) for each matched element. The handler is executed only once for each element. Otherwise, the same rules as described in bind() apply. The event handler is passed an event object that you can use to prevent default behaviour. To stop both default action and event bubbling, your handler has to return false.

In most cases, you can define your event handlers as anonymous functions (see first example). In cases where that is not possible, you can pass additional data as the second paramter (and the handler function as the third), see second example.

Returns

jQuery

Parameters

  • type (String): An event type
  • data (Object): (optional) Additional data passed to the event handler as event.data
  • fn (Function): A function to bind to the event on each of the set of matched elements

Example

jQuery Code

$("p").one("click", function(){
  alert( $(this).text() );
});

Before

<p>Hello</p>

Result:

alert("Hello")
ready(fn)

ready(fn)

Bind a function to be executed whenever the DOM is ready to be traversed and manipulated. This is probably the most important function included in the event module, as it can greatly improve the response times of your web applications.

In a nutshell, this is a solid replacement for using window.onload, and attaching a function to that. By using this method, your bound function will be called the instant the DOM is ready to be read and manipulated, which is when what 99.99% of all JavaScript code needs to run.

There is one argument passed to the ready event handler: A reference to the jQuery function. You can name that argument whatever you like, and can therefore stick with the $ alias without risk of naming collisions.

Please ensure you have no code in your <body> onload event handler, otherwise $(document).ready() may not fire.

You can have as many $(document).ready events on your page as you like. The functions are then executed in the order they were added.

Returns

jQuery

Parameters

  • fn (Function): The function to be executed when the DOM is ready.

Example

jQuery Code

$(document).ready(function(){ Your code here... });

Example

Uses both the [[Core#.24.28_fn_.29|shortcut]] for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.

jQuery Code

jQuery(function($) {
  // Your code using failsafe $ alias here...
});
resize(fn)

resize(fn)

Bind a function to the resize event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the resize event on each of the matched elements.

Example

jQuery Code

$("p").resize( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onresize="alert('Hello');">Hello</p>
scroll(fn)

scroll(fn)

Bind a function to the scroll event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the scroll event on each of the matched elements.

Example

jQuery Code

$("p").scroll( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onscroll="alert('Hello');">Hello</p>
select()

select()

Trigger the select event of each matched element. This causes all of the functions that have been bound to that select event to be executed, and calls the browser's default select action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the select event.

Returns

jQuery

Example

jQuery Code

$("p").select();

Before

<p onselect="alert('Hello');">Hello</p>

Result:

alert('Hello');
select(fn)

select(fn)

Bind a function to the select event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the select event on each of the matched elements.

Example

jQuery Code

$("p").select( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onselect="alert('Hello');">Hello</p>
submit()

submit()

Trigger the submit event of each matched element. This causes all of the functions that have been bound to that submit event to be executed, and calls the browser's default submit action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the submit event.

Note: This does not execute the submit method of the form element! If you need to submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();

Returns

jQuery

Example

Triggers all submit events registered to the matched form(s), and submits them.

jQuery Code

$("form").submit();
submit(fn)

submit(fn)

Bind a function to the submit event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the submit event on each of the matched elements.

Example

Prevents the form submission when the input has no value entered.

jQuery Code

$("#myform").submit( function() {
  return $("input", this).val().length > 0;
} );

Before

<form id="myform"><input /></form>
toggle(even, odd)

toggle(even, odd)

Toggle between two function calls every other click. Whenever a matched element is clicked, the first specified function is fired, when clicked again, the second is fired. All subsequent clicks continue to rotate through the two functions.

Use unbind("click") to remove.

Returns

jQuery

Parameters

  • even (Function): The function to execute on every even click.
  • odd (Function): The function to execute on every odd click.

Example

jQuery Code

$("p").toggle(function(){
  $(this).addClass("selected");
},function(){
  $(this).removeClass("selected");
});
trigger(type, data)

trigger(type, data)

Trigger a type of event on every matched element. This will also cause the default action of the browser with the same name (if one exists) to be executed. For example, passing 'submit' to the trigger() function will also cause the browser to submit the form. This default action can be prevented by returning false from one of the functions bound to the event.

You can also trigger custom events registered with bind.

Returns

jQuery

Parameters

  • type (String): An event type to trigger.
  • data (Array): (optional) Additional data to pass as arguments (after the event object) to the event handler

Example

jQuery Code

$("p").trigger("click")

Before

<p click="alert('hello')">Hello</p>

Result:

alert('hello')

Example

Example of how to pass arbitrary data to an event

jQuery Code

$("p").click(function(event, a, b) {
  // when a normal click fires, a and b are undefined
  // for a trigger like below a refers too "foo" and b refers to "bar"
}).trigger("click", ["foo", "bar"]);

Example

jQuery Code

$("p").bind("myEvent",function(event,message1,message2) {
	alert(message1 + ' ' + message2);
});
$("p").trigger("myEvent",["Hello","World"]);

Result:

alert('Hello World') // One for each paragraph
unbind(type, fn)

unbind(type, fn)

The opposite of bind, removes a bound event from each of the matched elements.

Without any arguments, all bound events are removed.

If the type is provided, all bound events of that type are removed.

If the function that was passed to bind is provided as the second argument, only that specific event handler is removed.

Returns

jQuery

Parameters

  • type (String): (optional) An event type
  • fn (Function): (optional) A function to unbind from the event on each of the set of matched elements

Example

jQuery Code

$("p").unbind()

Before

<p onclick="alert('Hello');">Hello</p>

Result:

[ <p>Hello</p> ]

Example

jQuery Code

$("p").unbind( "click" )

Before

<p onclick="alert('Hello');">Hello</p>

Result:

[ <p>Hello</p> ]

Example

jQuery Code

$("p").unbind( "click", function() { alert("Hello"); } )

Before

<p onclick="alert('Hello');">Hello</p>

Result:

[ <p>Hello</p> ]
unload(fn)

unload(fn)

Bind a function to the unload event of each matched element.

Returns

jQuery

Parameters

  • fn (Function): A function to bind to the unload event on each of the matched elements.

Example

jQuery Code

$("p").unload( function() { alert("Hello"); } );

Before

<p>Hello</p>

Result:

<p onunload="alert('Hello');">Hello</p>
Ajax
$.ajax(properties)

$.ajax(properties)

Load a remote page using an HTTP request.

This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks).

$.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually.

'''Note:''' If you specify the dataType option described below, make sure the server sends the correct MIME type in the response (eg. xml as "text/xml"). Sending the wrong MIME type can lead to unexpected problems in your script. See [[Specifying the Data Type for AJAX Requests]] for more information.

Supported datatypes are (see dataType option):

"xml": Returns a XML document that can be processed via jQuery.

"html": Returns HTML as plain text, included script tags are evaluated.

"script": Evaluates the response as Javascript and returns it as plain text.

"json": Evaluates the response as JSON and returns a Javascript Object

$.ajax() takes one argument, an object of key/value pairs, that are used to initalize and handle the request. These are all the key/values that can be used:

(String) url - The URL to request.

(String) type - The type of request to make ("POST" or "GET"), default is "GET".

(String) dataType - The type of data that you're expecting back from the server. No default: If the server sends xml, the responseXML, otherwise the responseText is passed to the success callback.

(Boolean) ifModified - Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header.

(Number) timeout - Local timeout to override global timeout, eg. to give a single request a longer timeout while all others timeout after 1 second. See $.ajaxTimeout() for global timeouts.

(Boolean) global - Whether to trigger global AJAX event handlers for this request, default is true. Set to false to prevent that global handlers like ajaxStart or ajaxStop are triggered.

(Function) error - A function to be called if the request fails. The function gets passed tree arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occured.

(Function) success - A function to be called if the request succeeds. The function gets passed one argument: The data returned from the server, formatted according to the 'dataType' parameter.

(Function) complete - A function to be called when the request finishes. The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request.

(Object|String) data - Data to be sent to the server. Converted to a query string, if not already a string. Is appended to the url for GET-requests. See processData option to prevent this automatic processing.

(String) contentType - When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases.

(Boolean) processData - By default, data passed in to the data option as an object other as string will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments, set this option to false.

(Boolean) async - By default, all requests are sent asynchronous (set to true). If you need synchronous requests, set this option to false.

(Function) beforeSend - A pre-callback to set custom headers etc., the XMLHttpRequest is passed as the only argument.

Returns

XMLHttpRequest

Parameters

  • properties (Map): Key/value pairs to initialize the request with.

Example

Load and execute a JavaScript file.

jQuery Code

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
})

Example

Save some data to the server and notify the user once its complete.

jQuery Code

$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
    alert( "Data Saved: " + msg );
  }
});

Example

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.

jQuery Code

var html = $.ajax({
 url: "some.php",
 async: false
}).responseText;

Example

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.

jQuery Code

var xmlDocument = [create xml document];
$.ajax({
  url: "page.php",
  processData: false,
  data: xmlDocument,
  success: handleResponse
});
$.ajaxSetup(settings)

$.ajaxSetup(settings)

Setup global settings for AJAX requests.

See $.ajax for a description of all available options.

Returns

undefined

Parameters

  • settings (Map): Key/value pairs to use for all AJAX requests

Example

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.

jQuery Code

$.ajaxSetup( {
  url: "/xmlhttp/",
  global: false,
  type: "POST"
} );
$.ajax({ data: myData });
$.ajaxTimeout(time)

$.ajaxTimeout(time)

Set the timeout of all AJAX requests to a specific amount of time. This will make all future AJAX requests timeout after a specified amount of time.

Set to null or 0 to disable timeouts (default).

You can manually abort requests with the XMLHttpRequest's (returned by all ajax functions) abort() method.

Deprecated. Use $.ajaxSetup instead.

Returns

undefined

Parameters

  • time (Number): How long before an AJAX request times out.

Example

Make all AJAX requests timeout after 5 seconds.

jQuery Code

$.ajaxTimeout( 5000 );
$.get(url, params, callback)

$.get(url, params, callback)

Load a remote page using an HTTP GET request.

This is an easy way to send a simple GET request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). If you need to have both error and success callbacks, you may want to use $.ajax.

Returns

XMLHttpRequest

Parameters

  • url (String): The URL of the page to load.
  • params (Map): (optional) Key/value pairs that will be sent to the server.
  • callback (Function): (optional) A function to be executed whenever the data is loaded successfully.

Example

jQuery Code

$.get("test.cgi");

Example

jQuery Code

$.get("test.cgi", { name: "John", time: "2pm" } );

Example

jQuery Code

$.get("test.cgi", function(data){
  alert("Data Loaded: " + data);
});

Example

jQuery Code

$.get("test.cgi",
  { name: "John", time: "2pm" },
  function(data){
    alert("Data Loaded: " + data);
  }
);
$.getIfModified(url, params, callback)

$.getIfModified(url, params, callback)

Load a remote page using an HTTP GET request, only if it hasn't been modified since it was last retrieved.

Returns

XMLHttpRequest

Parameters

  • url (String): The URL of the page to load.
  • params (Map): (optional) Key/value pairs that will be sent to the server.
  • callback (Function): (optional) A function to be executed whenever the data is loaded successfully.

Example

jQuery Code

$.getIfModified("test.html");

Example

jQuery Code

$.getIfModified("test.html", { name: "John", time: "2pm" } );

Example

jQuery Code

$.getIfModified("test.cgi", function(data){
  alert("Data Loaded: " + data);
});

Example

jQuery Code

$.getifModified("test.cgi",
  { name: "John", time: "2pm" },
  function(data){
    alert("Data Loaded: " + data);
  }
);
$.getJSON(url, params, callback)

$.getJSON(url, params, callback)

Load JSON data using an HTTP GET request.

Returns

XMLHttpRequest

Parameters

  • url (String): The URL of the page to load.
  • params (Map): (optional) Key/value pairs that will be sent to the server.
  • callback (Function): A function to be executed whenever the data is loaded successfully.

Example

jQuery Code

$.getJSON("test.js", function(json){
  alert("JSON Data: " + json.users[3].name);
});

Example

jQuery Code

$.getJSON("test.js",
  { name: "John", time: "2pm" },
  function(json){
    alert("JSON Data: " + json.users[3].name);
  }
);
$.getScript(url, callback)

$.getScript(url, callback)

Loads, and executes, a remote JavaScript file using an HTTP GET request.

Warning: Safari <= 2.0.x is unable to evaluate scripts in a global context synchronously. If you load functions via getScript, make sure to call them after a delay.

Returns

XMLHttpRequest

Parameters

  • url (String): The URL of the page to load.
  • callback (Function): (optional) A function to be executed whenever the data is loaded successfully.

Example

jQuery Code

$.getScript("test.js");

Example

jQuery Code

$.getScript("test.js", function(){
  alert("Script loaded and executed.");
});
$.post(url, params, callback)

$.post(url, params, callback)

Load a remote page using an HTTP POST request.

Returns

XMLHttpRequest

Parameters

  • url (String): The URL of the page to load.
  • params (Map): (optional) Key/value pairs that will be sent to the server.
  • callback (Function): (optional) A function to be executed whenever the data is loaded successfully.

Example

jQuery Code

$.post("test.cgi");

Example

jQuery Code

$.post("test.cgi", { name: "John", time: "2pm" } );

Example

jQuery Code

$.post("test.cgi", function(data){
  alert("Data Loaded: " + data);
});

Example

jQuery Code

$.post("test.cgi",
  { name: "John", time: "2pm" },
  function(data){
    alert("Data Loaded: " + data);
  }
);
ajaxComplete(callback)

ajaxComplete(callback)

Attach a function to be executed whenever an AJAX request completes.

The XMLHttpRequest and settings used for that request are passed as arguments to the callback.

Returns

jQuery

Parameters

  • callback (Function): The function to execute.

Example

Show a message when an AJAX request completes.

jQuery Code

$("#msg").ajaxComplete(function(request, settings){
  $(this).append("<li>Request Complete.</li>");
});
ajaxError(callback)

ajaxError(callback)

Attach a function to be executed whenever an AJAX request fails.

The XMLHttpRequest and settings used for that request are passed as arguments to the callback. A third argument, an exception object, is passed if an exception occured while processing the request.

Returns

jQuery

Parameters

  • callback (Function): The function to execute.

Example

Show a message when an AJAX request fails.

jQuery Code

$("#msg").ajaxError(function(request, settings){
  $(this).append("<li>Error requesting page " + settings.url + "</li>");
});
ajaxSend(callback)

ajaxSend(callback)

Attach a function to be executed before an AJAX request is sent.

The XMLHttpRequest and settings used for that request are passed as arguments to the callback.

Returns

jQuery

Parameters

  • callback (Function): The function to execute.

Example

Show a message before an AJAX request is sent.

jQuery Code

$("#msg").ajaxSend(function(request, settings){
  $(this).append("<li>Starting request at " + settings.url + "</li>");
});
ajaxStart(callback)

ajaxStart(callback)

Attach a function to be executed whenever an AJAX request begins and there is none already active.

Returns

jQuery

Parameters

  • callback (Function): The function to execute.

Example

Show a loading message whenever an AJAX request starts (and none is already active).

jQuery Code

$("#loading").ajaxStart(function(){
  $(this).show();
});
ajaxStop(callback)

ajaxStop(callback)

Attach a function to be executed whenever all AJAX requests have ended.

Returns

jQuery

Parameters

  • callback (Function): The function to execute.

Example

Hide a loading message after all the AJAX requests have stopped.

jQuery Code

$("#loading").ajaxStop(function(){
  $(this).hide();
});
ajaxSuccess(callback)

ajaxSuccess(callback)

Attach a function to be executed whenever an AJAX request completes successfully.

The XMLHttpRequest and settings used for that request are passed as arguments to the callback.

Returns

jQuery

Parameters

  • callback (Function): The function to execute.

Example

Show a message when an AJAX request completes successfully.

jQuery Code

$("#msg").ajaxSuccess(function(request, settings){
  $(this).append("<li>Successful Request!</li>");
});
load(url, params, callback)

load(url, params, callback)

Load HTML from a remote file and inject it into the DOM.

Note: Avoid to use this to load scripts, instead use $.getScript. IE strips script tags when there aren't any other characters in front of it.

Returns

jQuery

Parameters

  • url (String): The URL of the HTML file to load.
  • params (Object): (optional) A set of key/value pairs that will be sent as data to the server.
  • callback (Function): (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).

Example

jQuery Code

$("#feeds").load("feeds.html");

Before

<div id="feeds"></div>

Result:

<div id="feeds"><b>45</b> feeds found.</div>

Example

Same as above, but with an additional parameter and a callback that is executed when the data was loaded.

jQuery Code

$("#feeds").load("feeds.html",
  {limit: 25},
  function() { alert("The last 25 entries in the feed have been loaded"); }
);
loadIfModified(url, params, callback)

loadIfModified(url, params, callback)

Load HTML from a remote file and inject it into the DOM, only if it's been modified by the server.

Returns

jQuery

Parameters

  • url (String): The URL of the HTML file to load.
  • params (Map): (optional) Key/value pairs that will be sent to the server.
  • callback (Function): (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).

Example

jQuery Code

$("#feeds").loadIfModified("feeds.html");

Before

<div id="feeds"></div>

Result:

<div id="feeds"><b>45</b> feeds found.</div>
serialize()

serialize()

Serializes a set of input elements into a string of data. This will serialize all given elements.

A serialization similar to the form submit of a browser is provided by the [http://www.malsup.com/jquery/form/ Form Plugin]. It also takes multiple-selects into account, while this method recognizes only a single option.

Returns

String

Example

Serialize a selection of input elements to a string

jQuery Code

$("input[@type=text]").serialize();

Before

<input type='text' name='name' value='John'/>
<input type='text' name='location' value='Boston'/>
Effects
animate(params, speed, easing, callback)

animate(params, speed, easing, callback)

A function for making your own, custom animations. The key aspect of this function is the object of style properties that will be animated, and to what end. Each key within the object represents a style property that will also be animated (for example: "height", "top", or "opacity").

Note that properties should be specified using camel case eg. marginLeft instead of margin-left.

The value associated with the key represents to what end the property will be animated. If a number is provided as the value, then the style property will be transitioned from its current state to that new number. Otherwise if the string "hide", "show", or "toggle" is provided, a default animation will be constructed for that property.

Returns

jQuery

Parameters

  • params (Hash): A set of style attributes that you wish to animate, and to what end.
  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • easing (String): (optional) The name of the easing effect that you want to use (Plugin Required).
  • callback (Function): (optional) A function to be executed whenever the animation completes.

Example

jQuery Code

$("p").animate({
  height: 'toggle', opacity: 'toggle'
}, "slow");

Example

jQuery Code

$("p").animate({
  left: 50, opacity: 'show'
}, 500);

Example

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 (Only 'linear' is provided by default, with jQuery).

jQuery Code

$("p").animate({
  opacity: 'show'
}, "slow", "easein");
fadeIn(speed, callback)

fadeIn(speed, callback)

Fade in all matched elements by adjusting their opacity and firing an optional callback after completion.

Only the opacity is adjusted for this animation, meaning that all of the matched elements should already have some form of height and width associated with them.

Returns

jQuery

Parameters

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes.

Example

jQuery Code

$("p").fadeIn("slow");

Example

jQuery Code

$("p").fadeIn("slow",function(){
  alert("Animation Done.");
});
fadeOut(speed, callback)

fadeOut(speed, callback)

Fade out all matched elements by adjusting their opacity and firing an optional callback after completion.

Only the opacity is adjusted for this animation, meaning that all of the matched elements should already have some form of height and width associated with them.

Returns

jQuery

Parameters

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes.

Example

jQuery Code

$("p").fadeOut("slow");

Example

jQuery Code

$("p").fadeOut("slow",function(){
  alert("Animation Done.");
});
fadeTo(speed, opacity, callback)

fadeTo(speed, opacity, callback)

Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion.

Only the opacity is adjusted for this animation, meaning that all of the matched elements should already have some form of height and width associated with them.

Returns

jQuery

Parameters

  • speed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • opacity (Number): The opacity to fade to (a number from 0 to 1).
  • callback (Function): (optional) A function to be executed whenever the animation completes.

Example

jQuery Code

$("p").fadeTo("slow", 0.5);

Example

jQuery Code

$("p").fadeTo("slow", 0.5, function(){
  alert("Animation Done.");
});
hide()

hide()

Hides each of the set of matched elements if they are shown.

Returns

jQuery

Example

jQuery Code

$("p").hide()

Before

<p>Hello</p>

Result:

[ <p style="display: none">Hello</p> ]
hide(speed, callback)

hide(speed, callback)

Hide all matched elements using a graceful animation and firing an optional callback after completion.

The height, width, and opacity of each of the matched elements are changed dynamically according to the specified speed.

Returns

jQuery

Parameters

  • speed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes.

Example

jQuery Code

$("p").hide("slow");

Example

jQuery Code

$("p").hide("slow",function(){
  alert("Animation Done.");
});
show()

show()

Displays each of the set of matched elements if they are hidden.

Returns

jQuery

Example

jQuery Code

$("p").show()

Before

<p style="display: none">Hello</p>

Result:

[ <p style="display: block">Hello</p> ]
show(speed, callback)

show(speed, callback)

Show all matched elements using a graceful animation and firing an optional callback after completion.

The height, width, and opacity of each of the matched elements are changed dynamically according to the specified speed.

Returns

jQuery

Parameters

  • speed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes.

Example

jQuery Code

$("p").show("slow");

Example

jQuery Code

$("p").show("slow",function(){
  alert("Animation Done.");
});
slideDown(speed, callback)

slideDown(speed, callback)

Reveal all matched elements by adjusting their height and firing an optional callback after completion.

Only the height is adjusted for this animation, causing all matched elements to be revealed in a "sliding" manner.

Returns

jQuery

Parameters

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes.

Example

jQuery Code

$("p").slideDown("slow");

Example

jQuery Code

$("p").slideDown("slow",function(){
  alert("Animation Done.");
});
slideToggle(speed, callback)

slideToggle(speed, callback)

Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion.

Only the height is adjusted for this animation, causing all matched elements to be hidden in a "sliding" manner.

Returns

jQuery

Parameters

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes.

Example

jQuery Code

$("p").slideToggle("slow");

Example

jQuery Code

$("p").slideToggle("slow",function(){
  alert("Animation Done.");
});
slideUp(speed, callback)

slideUp(speed, callback)

Hide all matched elements by adjusting their height and firing an optional callback after completion.

Only the height is adjusted for this animation, causing all matched elements to be hidden in a "sliding" manner.

Returns

jQuery

Parameters

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes.

Example

jQuery Code

$("p").slideUp("slow");

Example

jQuery Code

$("p").slideUp("slow",function(){
  alert("Animation Done.");
});
toggle()

toggle()

Toggles each of the set of matched elements. If they are shown, toggle makes them hidden. If they are hidden, toggle makes them shown.

Returns

jQuery

Example

jQuery Code

$("p").toggle()

Before

<p>Hello</p><p style="display: none">Hello Again</p>

Result:

[ <p style="display: none">Hello</p>, <p style="display: block">Hello Again</p> ]
Plugins
Accordion
Accordion(options)

Accordion(options)

Make the selected elements Accordion widgets.

This is very similar to the Squeezebox widget, only that there can be only one open element.

Semantic requirements:

If the structure of your container is flat with unique tags for header and content elements, eg. a definition list (dl > dt + dd), you don't have to specify any options at all.

If your structure uses the same elements for header and content or uses some kind of nested structure, you have to specify the header elements, eg. via class, see the second example.

Use activate(Number) to change the active content programmatically.

A change event is triggered everytime the accordion changes. Apart from the event object, all arguments are jQuery objects. Arguments: event, newHeader, oldHeader, newContent, oldContent

Returns

jQuery

Parameters

  • options (Map): key/value pairs of optional settings.

Hash Options

  • active (String|Element|jQuery|Boolean): Selector for the active element, default is the first child, set to false to display none at start
  • header (String|Element|jQuery): Selector for the header element, eg. div.title, a.head, default is the first child's tagname
  • showSpeed (String|Number): Speed for the slideIn, default is 'normal' (for numbers: smaller = faster)
  • hideSpeed (String|Number): Speed for the slideOut, default is 'normal' (for numbers: smaller = faster)
  • selectedClass (String): Class for active header elements, default is 'selected'
  • alwaysOpen (Boolean): Whether there must be one content element open, default is true.
  • animated (Boolean): Set to false to disable animations. Default: true
  • event (String): The event on which to trigger the accordion, eg. "mouseover". Default: "click"
  • cloneFirst (Boolean): Use this for a navigation menu where the header element must be available as a selectable target, see related example for more details

Example

Creates an Accordion from the given definition list

jQuery Code

jQuery('#nav').Accordion();

Before

<dl id="nav">
  <dt>Header 1</dt>
  <dd>Content 1</dd>
  <dt>Header 2</dt>
  <dd>Content 2</dd>
</dl>

Example

Creates an Accordion from the given div structure

jQuery Code

jQuery('#nav').Accordion({
  header: 'div.title'
});

Before

<div id="nav">
 <div>
   <div class="title">Header 1</div>
   <div>Content 1</div>
 </div>
 <div>
   <div class="title">Header 2</div>
   <div>Content 2</div>
 </div>
</div>

Example

Creates an Accordion from the given navigation list, cloning the header element to produce a clickable link. The class as specified in the header selector is removed from the cloned element. Currently this works only with the above structure, the header must be an anchor followed by a list.

jQuery Code

jQuery('#nav').Accordion({
  header: '.head',
	 cloneFirst: true
});

Before

<ul id="nav">
  <li>
    <a class="head" href="books/">Books</a>
    <ul>
      <li><a href="books/fantasy/">Fantasy</a></li>
      <li><a href="books/programming/">Programming</a></li>
    </ul>
  </li>
  <li>
    <a class="head" href="movies/">Movies</a>
    <ul>
      <li><a href="movies/fantasy/">Fantasy</a></li>
      <li><a href="movies/programming/">Programming</a></li>
    </ul>
  </li>
</ul>

Example

Updates the element with id status with the text of the selected header every time the accordion changes

jQuery Code

jQuery('#accordion').Accordion().change(function(event, newHeader, oldHeader, newContent, oldContent) {
  jQuery('#status').html(newHeader.text());
});
activate(index)

activate(index)

Activate a content part of the Accordion programmatically.

The index can be a zero-indexed number to match the position of the header to close or a string expression matching an element.

Returns

jQuery

Parameters

  • index (String|Number): (optional) An Integer specifying the zero-based index of the content to be activated or an expression specifying the element to close. Default: closes all.

Example

Activate the second content of the Accordion contained in <div id="accordion">.

jQuery Code

jQuery('#accordion').activate(1);

Example

Activate the first element matching the given expression.

jQuery Code

jQuery('#accordion').activate("a:first");

Example

Close all content parts of the accordion.

jQuery Code

jQuery('#nav').activate();
jQuery.Accordion.setDefaults(options)

jQuery.Accordion.setDefaults(options)

Override the default settings of the Accordion. Affects only following plugin calls.

Returns

jQuery

Parameters

  • options (Map): key/value pairs of optional settings, see Accordion() for details

Example

jQuery Code

jQuery.Accordion.setDefaults({
	showSpeed: 1000,
	hideSpeed: 150
});
Button
button(hash)

button(hash)

Creates a button from an image element.

This function attempts to mimic the functionality of the "button" found in modern day GUIs. There are two different buttons you can create using this plugin; Normal buttons, and Toggle buttons.

Returns

jQuery

Parameters

  • hash (hOptions): with options, described below. sPath Full path to the images, either relative or with full URL sExt Extension of the used images (jpg|gif|png) sName Name of the button, if not specified, try to fetch from id iWidth Width of the button, if not specified, try to fetch from element.width iHeight Height of the button, if not specified, try to fetch from element.height onAction Function to call when clicked / toggled. In case of a string, the element is wrapped inside an href tag. bToggle Do we need to create a togglebutton? (boolean) bState Initial state of the button? (boolean) sType Type of hover to create (img|css)
Center
center()

center()

Takes all matched elements and centers them, absolutely, within the context of their parent element. Great for doing slideshows.

Returns

jQuery

Example

jQuery Code

$("div img").center();
Cookie
$.cookie(name)

$.cookie(name)

Get the value of a cookie with the given name.

Returns

String

Parameters

  • name (String): The name of the cookie.

Example

Get the value of a cookie.

jQuery Code

$.cookie('the_cookie');
$.cookie(name, value, options)

$.cookie(name, value, options)

Create a cookie with the given name and value and other optional parameters.

Returns

undefined

Parameters

  • name (String): The name of the cookie.
  • value (String): The value of the cookie.
  • options (Object): An object literal containing key/value pairs to provide optional cookie attributes.

Hash Options

  • expires (Number|Date): Either an integer specifying the expiration date from now on in days or a Date object. If a negative value is specified (e.g. a date in the past), the cookie will be deleted. If set to null or omitted, the cookie will be a session cookie and will not be retained when the the browser exits.
  • path (String): The value of the path atribute of the cookie (default: path of page that created the cookie).
  • domain (String): The value of the domain attribute of the cookie (default: domain of page that created the cookie).
  • secure (Boolean): If true, the secure attribute of the cookie will be set and the cookie transmission will require a secure protocol (like HTTPS).

Example

Set the value of a cookie.

jQuery Code

$.cookie('the_cookie', 'the_value');

Example

Create a cookie with all available options.

jQuery Code

$.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});

Example

Create a session cookie.

jQuery Code

$.cookie('the_cookie', 'the_value');

Example

Delete a cookie by passing null as value.

jQuery Code

$.cookie('the_cookie', null);
Dimensions
height()

height()

If used on document, returns the document's height (innerHeight) If used on window, returns the viewport's (window) height See core docs on height() to see what happens when used on an element.

Returns

Object

Example

jQuery Code

$("#testdiv").height()

Result:

200

Example

jQuery Code

$(document).height()

Result:

800

Example

jQuery Code

$(window).height()

Result:

400
innerHeight()

innerHeight()

Returns the inner height value (without border) for the first matched element. If used on document, returns the document's height (innerHeight) If used on window, returns the viewport's (window) height

Returns

Number

Example

jQuery Code

$("#testdiv").innerHeight()

Result:

800
innerWidth()

innerWidth()

Returns the inner width value (without border) for the first matched element. If used on document, returns the document's Width (innerWidth) If used on window, returns the viewport's (window) width

Returns

Number

Example

jQuery Code

$("#testdiv").innerWidth()

Result:

1000
offset(options, returnObject)

offset(options, returnObject)

Returns the location of the element in pixels from the top left corner of the viewport.

For accurate readings make sure to use pixel values for margins, borders and padding.

Known issues: - Issue: A div positioned relative or static without any content before it and its parent will report an offsetTop of 0 in Safari Workaround: Place content before the realtive div ... and set height and width to 0 and overflow to hidden

Returns

Object

Parameters

  • options (Map): Optional settings to configure the way the offset is calculated.
  • returnObject (Object): An object to store the return value in, so as not to break the chain. If passed in the chain will not be broken and the result will be assigned to this object.

Hash Options

  • margin (Boolean): Should the margin of the element be included in the calculations? True by default.
  • border (Boolean): Should the border of the element be included in the calculations? True by default.
  • padding (Boolean): Should the padding of the element be included in the calculations? False by default.
  • scroll (Boolean): Should the scroll offsets of the parent elements be included in the calculations? True by default. When true it adds the totla scroll offets of all parents to the total offset and also adds two properties to the returned object, scrollTop and scrollLeft. If scroll offsets are not needed, this can be a big performance boost if set to false.
  • ():

Example

jQuery Code

$("#testdiv").offset()

Result:

{ top: 100, left: 100, scrollTop: 10, scrollLeft: 10 }

Example

jQuery Code

$("#testdiv").offset({ scroll: false })

Result:

{ top: 90, left: 90 }

Example

jQuery Code

var offset = {}
$("#testdiv").offset({ scroll: false }, offset)

Result:

offset = { top: 90, left: 90 }
outerHeight()

outerHeight()

Returns the outer height value (including border) for the first matched element. Cannot be used on document or window.

Returns

Number

Example

jQuery Code

$("#testdiv").outerHeight()

Result:

1000
outerHeight()

outerHeight()

Returns the outer width value (including border) for the first matched element. Cannot be used on document or window.

Returns

Number

Example

jQuery Code

$("#testdiv").outerHeight()

Result:

1000
scrollLeft()

scrollLeft()

Returns how many pixels the user has scrolled to the right (scrollLeft). Works on containers with overflow: auto and window/document.

Returns

Number

Example

jQuery Code

$("#testdiv").scrollLeft()

Result:

100
scrollLeft(value)

scrollLeft(value)

Sets the scrollLeft property and continues the chain. Works on containers with overflow: auto and window/document.

Returns

jQuery

Parameters

  • value (Number): A positive number representing the desired scrollLeft.

Example

jQuery Code

$("#testdiv").scrollLeft(10).scrollLeft()

Result:

10
scrollTop()

scrollTop()

Returns how many pixels the user has scrolled to the bottom (scrollTop). Works on containers with overflow: auto and window/document.

Returns

Number

Example

jQuery Code

$("#testdiv").scrollTop()

Result:

100
scrollTop(value)

scrollTop(value)

Sets the scrollTop property and continues the chain. Works on containers with overflow: auto and window/document.

Returns

jQuery

Parameters

  • value (Number): A positive number representing the desired scrollTop.

Example

jQuery Code

$("#testdiv").scrollTop(10).scrollTop()

Result:

10
width()

width()

If used on document, returns the document's width (innerWidth) If used on window, returns the viewport's (window) width See core docs on height() to see what happens when used on an element.

Returns

Object

Example

jQuery Code

$("#testdiv").width()

Result:

200

Example

jQuery Code

$(document).width()

Result:

800

Example

jQuery Code

$(window).width()

Result:

400
Form
ajaxForm(object)

ajaxForm(object)

ajaxForm() provides a mechanism for fully automating form submission.

The advantages of using this method instead of ajaxSubmit() are:

1: This method will include coordinates for <input type="image" /> elements (if the element is used to submit the form). 2. This method will include the submit element's name/value data (for the element that was used to submit the form). 3. This method binds the submit() method to the form for you.

Note that for accurate x/y coordinates of image submit elements in all browsers you need to also use the "dimensions" plugin (this method will auto-detect its presence).

The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely passes the options argument along after properly binding events for submit elements and the form itself. See ajaxSubmit for a full description of the options argument.

Returns

jQuery

Parameters

  • object (options): literal containing options which control the form submission process

Example

Bind form's submit event so that 'myTargetDiv' is updated with the server response when the form is submitted.

jQuery Code

var options = {
    target: '#myTargetDiv'
};
$('#myForm').ajaxSForm(options);

Example

Bind form's submit event so that server response is alerted after the form is submitted.

jQuery Code

var options = {
    success: function(responseText) {
        alert(responseText);
    }
};
$('#myForm').ajaxSubmit(options);

Example

Bind form's submit event so that pre-submit callback is invoked before the form is submitted.

jQuery Code

var options = {
    beforeSubmit: function(formArray, jqForm) {
        if (formArray.length == 0) {
            alert('Please enter data.');
            return false;
        }
    }
};
$('#myForm').ajaxSubmit(options);
ajaxSubmit(object)

ajaxSubmit(object)

ajaxSubmit() provides a mechanism for submitting an HTML form using AJAX.

ajaxSubmit accepts a single argument which can be either a success callback function or an options Object. If a function is provided it will be invoked upon successful completion of the submit and will be passed the response from the server. If an options Object is provided, the following attributes are supported:

target: Identifies the element(s) in the page to be updated with the server response. This value may be specified as a jQuery selection string, a jQuery object, or a DOM element. default value: null

url: URL to which the form data will be submitted. default value: value of form's 'action' attribute

type: The method in which the form data should be submitted, 'GET' or 'POST'. default value: value of form's 'method' attribute (or 'GET' if none found)

beforeSubmit: Callback method to be invoked before the form is submitted. default value: null

success: Callback method to be invoked after the form has been successfully submitted and the response has been returned from the server default value: null

dataType: Expected dataType of the response. One of: null, 'xml', 'script', or 'json' default value: null

semantic: Boolean flag indicating whether data must be submitted in semantic order (slower). default value: false

resetForm: Boolean flag indicating whether the form should be reset if the submit is successful

clearForm: Boolean flag indicating whether the form should be cleared if the submit is successful

The 'beforeSubmit' callback can be provided as a hook for running pre-submit logic or for validating the form data. If the 'beforeSubmit' callback returns false then the form will not be submitted. The 'beforeSubmit' callback is invoked with three arguments: the form data in array format, the jQuery object, and the options object passed into ajaxSubmit. The form data array takes the following form:

[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]

If a 'success' callback method is provided it is invoked after the response has been returned from the server. It is passed the responseText or responseXML value (depending on dataType). See jQuery.ajax for further details.

The dataType option provides a means for specifying how the server response should be handled. This maps directly to the jQuery.httpData method. The following values are supported:

'xml': if dataType == 'xml' the server response is treated as XML and the 'after' callback method, if specified, will be passed the responseXML value 'json': if dataType == 'json' the server response will be evaluted and passed to the 'after' callback, if specified 'script': if dataType == 'script' the server response is evaluated in the global context

Note that it does not make sense to use both the 'target' and 'dataType' options. If both are provided the target will be ignored.

The semantic argument can be used to force form serialization in semantic order. This is normally true anyway, unless the form contains input elements of type='image'. If your form must be submitted with name/value pairs in semantic order and your form contains an input of type='image" then pass true for this arg, otherwise pass false (or nothing) to avoid the overhead for this logic.

When used on its own, ajaxSubmit() is typically bound to a form's submit event like this:

$("#form-id").submit(function() { $(this).ajaxSubmit(options); return false; // cancel conventional submit });

When using ajaxForm(), however, this is done for you.

Returns

jQuery

Parameters

  • object (options): literal containing options which control the form submission process

Example

Submit form and alert server response

jQuery Code

$('#myForm').ajaxSubmit(function(data) {
    alert('Form submit succeeded! Server returned: ' + data);
});

Example

Submit form and update page element with server response

jQuery Code

var options = {
    target: '#myTargetDiv'
};
$('#myForm').ajaxSubmit(options);

Example

Submit form and alert the server response

jQuery Code

var options = {
    success: function(responseText) {
        alert(responseText);
    }
};
$('#myForm').ajaxSubmit(options);

Example

Pre-submit validation which aborts the submit operation if form data is empty

jQuery Code

var options = {
    beforeSubmit: function(formArray, jqForm) {
        if (formArray.length == 0) {
            alert('Please enter data.');
            return false;
        }
    }
};
$('#myForm').ajaxSubmit(options);

Example

json data returned and evaluated

jQuery Code

var options = {
    url: myJsonUrl.php,
    dataType: 'json',
    success: function(data) {
       // 'data' is an object representing the the evaluated json data
    }
};
$('#myForm').ajaxSubmit(options);

Example

XML data returned from server

jQuery Code

var options = {
    url: myXmlUrl.php,
    dataType: 'xml',
    success: function(responseXML) {
       // responseXML is XML document object
       var data = $('myElement', responseXML).text();
    }
};
$('#myForm').ajaxSubmit(options);

Example

submit form and reset it if successful

jQuery Code

var options = {
    resetForm: true
};
$('#myForm').ajaxSubmit(options);

Example

Bind form's submit event to use ajaxSubmit

jQuery Code

$('#myForm).submit(function() {
   $(this).ajaxSubmit();
   return false;
});
clearFields()

clearFields()

Clears the selected form elements. Takes the following actions on the matched elements: - input text fields will have their 'value' property set to the empty string - select elements will have their 'selectedIndex' property set to -1 - checkbox and radio inputs will have their 'checked' property set to false - inputs of type submit, button, reset, and hidden will *not* be effected - button elements will *not* be effected

Returns

jQuery

Example

Clears all inputs with class myInputs

jQuery Code

$('.myInputs').clearFields();
clearForm()

clearForm()

Clears the form data. Takes the following actions on the form's input fields: - input text fields will have their 'value' property set to the empty string - select elements will have their 'selectedIndex' property set to -1 - checkbox and radio inputs will have their 'checked' property set to false - inputs of type submit, button, reset, and hidden will *not* be effected - button elements will *not* be effected

Returns

jQuery

Example

Clears all forms on the page.

jQuery Code

$('form').clearForm();
fieldSerialize(true)

fieldSerialize(true)

Serializes all field elements in the jQuery object into a query string. This method will return a string in the format: name1=value1&name2=value2

The successful argument controls whether or not serialization is limited to 'successful' controls (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The default value of the successful argument is true.

Returns

String

Parameters

  • true (successful): if only successful controls should be serialized (default is true)

Example

Collect the data from all successful input elements into a query string

jQuery Code

var data = $("input").formSerialize();

Example

Collect the data from all successful radio input elements into a query string

jQuery Code

var data = $(":radio").formSerialize();

Example

Collect the data from all successful checkbox input elements in myForm into a query string

jQuery Code

var data = $("#myForm :checkbox").formSerialize();

Example

Collect the data from all checkbox elements in myForm (even the unchecked ones) into a query string

jQuery Code

var data = $("#myForm :checkbox").formSerialize(false);

Example

Collect the data from all successful input, select, textarea and button elements into a query string

jQuery Code

var data = $(":input").formSerialize();
fieldValue(successful)

fieldValue(successful)

Returns the value(s) of the element in the matched set. For example, consider the following form:

<form><fieldset> <input name="A" type="text" /> <input name="A" type="text" /> <input name="B" type="checkbox" value="B1" /> <input name="B" type="checkbox" value="B2"/> <input name="C" type="radio" value="C1" /> <input name="C" type="radio" value="C2" /> </fieldset></form>

var v = $(':text').fieldValue(); // if no values are entered into the text inputs v == ['',''] // if values entered into the text inputs are 'foo' and 'bar' v == ['foo','bar']

var v = $(':checkbox').fieldValue(); // if neither checkbox is checked v === undefined // if both checkboxes are checked v == ['B1', 'B2']

var v = $(':radio').fieldValue(); // if neither radio is checked v === undefined // if first radio is checked v == ['C1']

The successful argument controls whether or not the field element must be 'successful' (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The default value of the successful argument is true. If this value is false the value(s) for each element is returned.

Note: This method *always* returns an array. If no valid value can be determined the array will be empty, otherwise it will contain one or more values.

Returns

Array<String>

Parameters

  • successful (Boolean): true if only the values for successful controls should be returned (default is true)

Example

Alerts the current value of the myPasswordElement element

jQuery Code

var data = $("#myPasswordElement").fieldValue();
alert(data[0]);

Example

Get the value(s) of the form elements in myForm

jQuery Code

var data = $("#myForm :input").fieldValue();

Example

Get the value(s) for the successful checkbox element(s) in the jQuery object.

jQuery Code

var data = $("#myForm :checkbox").fieldValue();

Example

Get the value(s) of the select control

jQuery Code

var data = $("#mySingleSelect").fieldValue();

Example

Get the value(s) of the text input or textarea elements

jQuery Code

var data = $(':text').fieldValue();

Example

Get the values for the select-multiple control

jQuery Code

var data = $("#myMultiSelect").fieldValue();
fieldValue(el, successful)

fieldValue(el, successful)

Returns the value of the field element.

The successful argument controls whether or not the field element must be 'successful' (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The default value of the successful argument is true. If the given element is not successful and the successful arg is not false then the returned value will be null.

Note: If the successful flag is true (default) but the element is not successful, the return will be null Note: The value returned for a successful select-multiple element will always be an array. Note: If the element has no value the return value will be undefined.

Returns

String or Array<String> or null or undefined

Parameters

  • el (Element): The DOM element for which the value will be returned
  • successful (Boolean): true if value returned must be for a successful controls (default is true)

Example

Gets the current value of the myPasswordElement element

jQuery Code

var data = jQuery.fieldValue($("#myPasswordElement")[0]);
formSerialize(true)

formSerialize(true)

Serializes form data into a 'submittable' string. This method will return a string in the format: name1=value1&name2=value2

The semantic argument can be used to force form serialization in semantic order. If your form must be submitted with name/value pairs in semantic order then pass true for this arg, otherwise pass false (or nothing) to avoid the overhead for this logic (which can be significant for very large forms).

Returns

String

Parameters

  • true (semantic): if serialization must maintain strict semantic ordering of elements (slower)

Example

Collect all the data from a form into a single string

jQuery Code

var data = $("#myForm").formSerialize();
$.ajax('POST', "myscript.cgi", data);
formToArray(true)

formToArray(true)

formToArray() gathers form element data into an array of objects that can be passed to any of the following ajax functions: $.get, $.post, or load. Each object in the array has both a 'name' and 'value' property. An example of an array for a simple login form might be:

[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]

It is this array that is passed to pre-submit callback functions provided to the ajaxSubmit() and ajaxForm() methods.

The semantic argument can be used to force form serialization in semantic order. This is normally true anyway, unless the form contains input elements of type='image'. If your form must be submitted with name/value pairs in semantic order and your form contains an input of type='image" then pass true for this arg, otherwise pass false (or nothing) to avoid the overhead for this logic.

Returns

Array<Object>

Parameters

  • true (semantic): if serialization must maintain strict semantic ordering of elements (slower)

Example

Collect all the data from a form and submit it to the server.

jQuery Code

var data = $("#myForm").formToArray();
$.post( "myscript.cgi", data );
resetForm()

resetForm()

Resets the form data. Causes all form elements to be reset to their original value.

Returns

jQuery

Example

Resets all forms on the page.

jQuery Code

$('form').resetForm();
Interface
$.SortSerialize()

$.SortSerialize()

This function returns the hash and an object (can be used as arguments for $.post) for every sortable in the page or specific sortables. The hash is based on the 'id' attributes of container and items.

Returns

String

Parameters

  • ():
$.recallDroppables()

$.recallDroppables()

Recalculate all Droppables

Returns

jQuery

Example

jQuery Code

$.recallDroppable();
3D Carousel(hash)

3D Carousel(hash)

Created a 3D Carousel from a list of images, with reflections and animated by mouse position

Returns

jQuery

Parameters

  • hash (Hash): A hash of parameters

Hash Options

  • items (String): items selection
  • itemWidth (Integer): the max width for each item
  • itemHeight (Integer): the max height for each item
  • itemMinWidth (Integer): the minimum width for each item, the height is automaticaly calculated to keep proportions
  • rotationSpeed (Float): the speed for rotation animation
  • reflectionSize (Float): the reflection size a fraction from items' height

Example

Creates a 3D carousel from all images inside div tag with id 'carousel'

jQuery Code

window.onload = 
			function()
			{
				$('#carousel').Carousel(
					{
						itemWidth: 110,
						itemHeight: 62,
						itemMinWidth: 50,
						items: 'a',
						reflections: .5,
						rotationSpeed: 1.8
					}
				);
			}
HTML
			<div id="carousel">
				<a href="" title=""><img src="" width="100%" /></a>
				<a href="" title=""><img src="" width="100%" /></a>
				<a href="" title=""><img src="" width="100%" /></a>
				<a href="" title=""><img src="" width="100%" /></a>
				<a href="" title=""><img src="" width="100%" /></a>
			</div>
CSS
			#carousel
			{
				width: 700px;
				height: 150px;
				background-color: #111;
				position: absolute;
				top: 200px;
				left: 100px;
			}
			#carousel a
			{
				position: absolute;
				width: 110px;
			}
Accordion(hash)

Accordion(hash)

Create an accordion from a HTML structure

Returns

jQuery

Parameters

  • hash (Hash): A hash of parameters

Hash Options

  • panelHeight (Integer): the pannels' height
  • headerSelector (String): selector for header elements
  • panelSelector (String): selector for panel elements
  • activeClass (String): (optional) CSS Class for active header
  • hoverClass (String): (optional) CSS Class for hovered header
  • onShow (Function): (optional) callback called whenever an pannel gets active
  • onHide (Function): (optional) callback called whenever an pannel gets incative
  • onClick (Function): (optional) callback called just before an panel gets active
  • speed (Mixed): (optional) animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • crrentPanel (Integer): (otional) the active panel on initialisation

Example

Converts definition list with id 'myAccordion' into an accordion width dt tags as headers and dd tags as panels

jQuery Code

$('#myAccordion').Accordion(
				{
					headerSelector	: 'dt',
					panelSelector	: 'dd',
					activeClass		: 'myAccordionActive',
					hoverClass		: 'myAccordionHover',
					panelHeight		: 200,
					speed			: 300
				}
			);
Autocomplete(hash)

Autocomplete(hash)

Attach AJAX driven autocomplete/sugestion box to text input fields.

Returns

jQuery

Parameters

  • hash (Hash): A hash of parameters

Hash Options

  • source (String): the URL to request
  • delay (Integer): (optional) the delayed time to start the AJAX request
  • autofill (Boolean): (optional) when true the first sugested value fills the input
  • helperClass (String): (optional) the CSS class applied to sugestion box
  • selectClass (String): (optional) the CSS class applied to selected/hovered item
  • minchars (Integer): (optional) the number of characters needed before starting AJAX request
  • fx (Hash): (optional) {type:[slide|blind|fade]; duration: integer} the fx type to apply to sugestion box and duration for that fx
  • onSelect (Function): (optional) A function to be executed whenever an item it is selected
  • onShow (Function): (optional) A function to be executed whenever the suggection box is displayed
  • onHide (Function): (optional) A function to be executed whenever the suggection box is hidden
  • onHighlight (Function): (optional) A function to be executed whenever an item it is highlighted
BlindDown(speed, callback, easing)

BlindDown(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
BlindLeft(speed, callback, easing)

BlindLeft(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
BlindRight(speed, callback, easing)

BlindRight(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
BlindToggleHorizontally(speed, callback, easing)

BlindToggleHorizontally(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
BlindToggleVertically(speed, callback, easing)

BlindToggleVertically(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
BlindUp(speed, callback, easing)

BlindUp(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
Bounce(hight, callback)

Bounce(hight, callback)

Returns

jQuery

Parameters

  • hight (Integer): the hight in pxels for element to jumps to
  • callback (Function): (optional) A function to be executed whenever the animation completes.
Bounce(speed, times, callback)

Bounce(speed, times, callback)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • times (Integer): how many times to pulsate
  • callback (Function): (optional) A function to be executed whenever the animation completes.
CloseHorizontally(speed, callback, easing)

CloseHorizontally(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
CloseVertically(speed, callback, easing)

CloseVertically(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
DisableTabs()

DisableTabs()

Disable tabs in textareas

Returns

jQuery

Draggable(hash)

Draggable(hash)

Create a draggable element with a number of advanced options including callback, Google Maps type draggables, reversion, ghosting, and grid dragging.

Returns

jQuery

Parameters

  • hash (Hash): A hash of parameters. All parameters are optional.

Hash Options

  • handle (String): (optional) The jQuery selector matching the handle that starts the draggable
  • handle (DOMElement): (optional) The DOM Element of the handle that starts the draggable
  • revert (Boolean): (optional) When true, on stop-drag the element returns to initial position
  • ghosting (Boolean): (optional) When true, a copy of the element is moved
  • zIndex (Integer): (optional) zIndex depth for the element while it is being dragged
  • opacity (Float): (optional) A number between 0 and 1 that indicates the opacity of the element while being dragged
  • grid (Integer): (optional) (optional) A number of pixels indicating the grid that the element should snap to
  • grid (Array): (optional) A number of x-pixels and y-pixels indicating the grid that the element should snap to
  • fx (Integer): (optional) Duration for the effect (like ghosting or revert) applied to the draggable
  • containment (String): (optional) Define the zone where the draggable can be moved. 'parent' moves it inside parent element, while 'document' prevents it from leaving the document and forcing additional scrolling
  • containment (Array): An 4-element array (left, top, width, height) indicating the containment of the element
  • axis (String): (optional) Set an axis: vertical (with 'vertically') or horizontal (with 'horizontally')
  • onStart (Function): (optional) Callback function triggered when the dragging starts
  • onStop (Function): (optional) Callback function triggered when the dragging stops
  • onChange (Function): (optional) Callback function triggered when the dragging stop *and* the element was moved at least one pixel
  • onDrag (Function): (optional) Callback function triggered while the element is dragged. Receives two parameters: x and y coordinates. You can return an object with new coordinates {x: x, y: y} so this way you can interact with the dragging process (for instance, build your containment)
  • insideParent (Boolean): Forces the element to remain inside its parent when being dragged (like Google Maps)
  • snapDistance (Integer): (optional) The element is not moved unless it is dragged more than snapDistance. You can prevent accidental dragging and keep regular clicking enabled (for links or form elements, for instance)
  • cursorAt (Object): (optional) The dragged element is moved to the cursor position with the offset specified. Accepts value for top, left, right and bottom offset. Basically, this forces the cursor to a particular position during the entire drag operation.
  • autoSize (Boolean): (optional) When true, the drag helper is resized to its content, instead of the dragged element's sizes
  • frameClass (String): (optional) When is set the cloned element is hidden so only a frame is dragged
DraggableDestroy()

DraggableDestroy()

Destroy an existing draggable on a collection of elements

Returns

jQuery

Example

jQuery Code

$('#drag2').DraggableDestroy();
DropInDown(speed, callback, easing)

DropInDown(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
DropInLeft(speed, callback, easing)

DropInLeft(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
DropInRight(speed, callback, easing)

DropInRight(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
DropInUp(speed, callback, easing)

DropInUp(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
DropOutDown(speed, callback, easing)

DropOutDown(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
DropOutLeft(speed, callback, easing)

DropOutLeft(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
DropOutRight(speed, callback, easing)

DropOutRight(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
DropOutUp(speed, callback, easing)

DropOutUp(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
DropToggleDown(speed, callback, easing)

DropToggleDown(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
DropToggleLeft(speed, callback, easing)

DropToggleLeft(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
DropToggleRight(speed, callback, easing)

DropToggleRight(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
DropToggleUp(speed, callback, easing)

DropToggleUp(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
Droppable(options)

Droppable(options)

With the Draggables plugin, Droppable allows you to create drop zones for draggable elements.

Parameters

  • options (Hash): A hash of options

Hash Options

  • accept (String): The class name for draggables to get accepted by the droppable (mandatory)
  • activeclass (String): When an acceptable draggable is moved, the droppable gets this class
  • hoverclass (String): When an acceptable draggable is inside the droppable, the droppable gets this class
  • tolerance (String): Choose from 'pointer', 'intersect', or 'fit'. The pointer options means that the pointer must be inside the droppable in order for the draggable to be dropped. The intersect option means that the draggable must intersect the droppable. The fit option means that the entire draggable must be inside the droppable.
  • onDrop (Function): When an acceptable draggable is dropped on a droppable, this callback is called. It passes the draggable DOMElement as a parameter.
  • onHover (Function): When an acceptable draggable is hovered over a droppable, this callback is called. It passes the draggable DOMElement as a parameter.
  • onOut (Function): When an acceptable draggable leaves a droppable, this callback is called. It passes the draggable DOMElement as a parameter.

Example

jQuery Code

$('#dropzone1').Droppable(
                            {
                              accept : 'dropaccept', 
                              activeclass: 'dropzoneactive', 
                              hoverclass:	'dropzonehover',
                              ondrop:	function (drag) {
                                             alert(this); //the droppable
                                             alert(drag); //the draggable
                                       },
                              fit: true
                            }
                          )
DroppableDestroy()

DroppableDestroy()

Destroy an existing droppable on a collection of elements

Returns

jQuery

Example

jQuery Code

$('#drag2').DroppableDestroy();
EnableTabs()

EnableTabs()

Enable tabs in textareas

Returns

jQuery

Expander(limit)

Expander(limit)

Expands text and textarea elements while new characters are typed to the a miximum width

Returns

jQuery

Parameters

  • limit (Mixed): integer if only expands in width, array if expands in width and height
Fisheye(hash)

Fisheye(hash)

Build a Fisheye menu from a list of links

Returns

jQuery

Parameters

  • hash (Hash): A hash of parameters

Hash Options

  • items (String): items selection
  • container (String): container element
  • itemWidth (Integer): the minimum width for each item
  • maxWidth (Integer): the maximum width for each item
  • itemsText (String): selection of element that contains the text for each item
  • proximity (Integer): the distance from element that make item to interact
  • valign (String): vertical alignment
  • halign (String): horizontal alignment
Fold(speed, height, callback, easing)

Fold(speed, height, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • height (Integer): the height in pixels to fold element to
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
FoldToggle(speed, height, callback, easing)

FoldToggle(speed, height, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • height (Integer): the height in pixels to folds/unfolds element to
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
Grow(speed, callback, easing)

Grow(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
Highlight(speed, color, callback, easing)

Highlight(speed, color, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • color (String): color to highlight from
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
Imagebox(hash)

Imagebox(hash)

This a jQuery equivalent for Lightbox2. Alternative to image popups that will display images in an overlay. All links that have attribute 'rel' starting with 'imagebox' and link to an image will display the image inside the page. Galleries can by build buy giving the value 'imagebox-galname' to attribute 'rel'. Attribute 'title' will be used as caption. Keyboard navigation: - next image: arrow right, page down, 'n' key, space - previous image: arrow left, page up, 'p' key, backspace - close: escape

CSS #ImageBoxOverlay { background-color: #000; } #ImageBoxCaption { background-color: #F4F4EC; } #ImageBoxContainer { width: 250px; height: 250px; background-color: #F4F4EC; } #ImageBoxCaptionText { font-weight: bold; padding-bottom: 5px; font-size: 13px; color: #000; } #ImageBoxCaptionImages { margin: 0; } #ImageBoxNextImage { background-image: url(images/imagebox/spacer.gif); background-color: transparent; } #ImageBoxPrevImage { background-image: url(images/imagebox/spacer.gif); background-color: transparent; } #ImageBoxNextImage:hover { background-image: url(images/imagebox/next_image.jpg); background-repeat: no-repeat; background-position: right top; } #ImageBoxPrevImage:hover { background-image: url(images/imagebox/prev_image.jpg); background-repeat: no-repeat; background-position: left bottom; }

Returns

jQuery

Parameters

  • hash (Hash): A hash of parameters

Hash Options

  • border (Integer): border width
  • loaderSRC (String): path to loading image
  • closeHTML (String): path to close overlay image
  • overlayOpacity (Float): opacity for overlay
  • textImage (String): when a galalry it is build then the iteration is displayed
  • textImageFrom (String): when a galalry it is build then the iteration is displayed
  • fadeDuration (Integer): fade duration in miliseconds
OpenHorizontally(speed, callback, easing)

OpenHorizontally(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
OpenVertically(speed, callback, easing)

OpenVertically(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
Puff(speed, callback, easing)

Puff(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
Resizable(hash)

Resizable(hash)

Create a resizable element with a number of advanced options including callback, dragging

Returns

jQuery

Parameters

  • hash (Hash): A hash of parameters. All parameters are optional.

Hash Options

  • handlers (Hash): hash with keys for each resize direction (e, es, s, sw, w, nw, n) and value string selection
  • minWidth (Integer): (optional) the minimum width that element can be resized to
  • maxWidth (Integer): (optional) the maximum width that element can be resized to
  • minHeight (Integer): (optional) the minimum height that element can be resized to
  • maxHeight (Integer): (optional) the maximum height that element can be resized to
  • minTop (Integer): (optional) the minmum top position to wich element can be moved to
  • minLeft (Integer): (optional) the minmum left position to wich element can be moved to
  • maxRight (Integer): (optional) the maximum right position to wich element can be moved to
  • maxBottom (Integer): (optional) the maximum bottom position to wich element can be moved to
  • ratio (Float): (optional) the ratio between width and height to constrain elements sizes to that ratio
  • dragHandle (Mixed): (optional) true to make the element draggable, string selection for drag handle
  • onDragStart (Function): (optional) A function to be executed whenever the dragging starts
  • onDragStop (Function): (optional) A function to be executed whenever the dragging stops
  • onDrag (Function): (optional) A function to be executed whenever the element is dragged
  • onStart (Function): (optional) A function to be executed whenever the element starts to be resized
  • onStop (Function): (optional) A function to be executed whenever the element stops to be resized
  • onResize (Function): (optional) A function to be executed whenever the element is resized
ResizableDestroy()

ResizableDestroy()

Destroy a resizable

Returns

jQuery

Scale(speed, from, to, reastore, callback, easing)

Scale(speed, from, to, reastore, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • from (Integer): initial scalling procentage
  • to (Integer): final scalling procentage
  • reastore (Boolean): whatever to restore the initital scalling procentage when animation ends
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
ScrollTo(speed, axis, easing)

ScrollTo(speed, axis, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • axis (String): (optional) whatever to scroll on vertical, horizontal or both axis ['vertical'|'horizontal'|null]
  • easing (String): (optional) The name of the easing effect that you want to use.
ScrollToAnchors(speed, axis, easing)

ScrollToAnchors(speed, axis, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • axis (String): (optional) whatever to scroll on vertical, horizontal or both axis ['vertical'|'horizontal'|null]
  • easing (String): (optional) The name of the easing effect that you want to use.
Shake(times, callback)

Shake(times, callback)

Returns

jQuery

Parameters

  • times (Integer): how many tomes to shake the element
  • callback (Function): (optional) A function to be executed whenever the animation completes.
Shrink(speed, callback, easing)

Shrink(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SlideInDown(speed, callback, easing)

SlideInDown(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SlideInLeft(speed, callback, easing)

SlideInLeft(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SlideInRight(speed, callback, easing)

SlideInRight(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SlideInUp(speed, callback, easing)

SlideInUp(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SlideOutDown(speed, callback, easing)

SlideOutDown(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SlideOutLeft(speed, callback, easing)

SlideOutLeft(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SlideOutRight(speed, callback, easing)

SlideOutRight(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SlideOutUp(speed, callback, easing)

SlideOutUp(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SlideToggleDown(speed, callback, easing)

SlideToggleDown(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SlideToggleLeft(speed, callback, easing)

SlideToggleLeft(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SlideToggleRight(speed, callback, easing)

SlideToggleRight(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SlideToggleUp(speed, callback, easing)

SlideToggleUp(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
Slider(hash)

Slider(hash)

Create a slider width options

Returns

jQuery

Parameters

  • hash (Hash): A hash of parameters. All parameters are optional.

Hash Options

  • accepts (Mixed): string to select slider indicators or DOMElement slider indicator
  • factions (Integer): (optional) number of sgments to divide and snap slider
  • onSlide (Function): (optional) A function to be executed whenever slider indicator it is moved
  • onChanged (Function): (optional) A function to be executed whenever slider indicator was moved
  • values (Array): (optional) Initial values for slider indicators
  • restricted (Boolean): (optional) if true the slider indicator can not be moved beyond adjacent indicators
SliderSetValues()

SliderSetValues()

Get value/position for slider indicators

Returns

jQuery

SliderSetValues(values)

SliderSetValues(values)

Set value/position for slider indicators

Returns

jQuery

Parameters

  • values (Array): array width values for each indicator
Slideshow(hash)

Slideshow(hash)

Creates an image slideshow. The slideshow can autoplay slides, each image can have caption, navigation links: next, prev, each slide. A page may have more then one slideshow, eachone working independently. Each slide can be bookmarked. The source images can be defined by JavaScript in slideshow options or by HTML placing images inside container.

Returns

jQuery

Parameters

  • hash (Hash): A hash of parameters

Hash Options

  • container (String): container ID
  • loader (String): path to loading indicator image
  • linksPosition (String): (optional) images links position ['top'|'bottom'|null]
  • linksClass (String): (optional) images links cssClass
  • linksSeparator (String): (optional) images links separator
  • fadeDuration (Integer): fade animation duration in miliseconds
  • activeLinkClass (String): (optional) active image link CSS class
  • nextslideClass (String): (optional) next image CSS class
  • prevslideClass (String): (optional) previous image CSS class
  • captionPosition (String): (optional) image caption position ['top'|'bottom'|null]
  • captionClass (String): (optional) image caption CSS class
  • autoplay (String): (optional) seconds to wait untill next images is displayed. This option will make the slideshow to autoplay.
  • random (String): (optional) if slideshow autoplayes the images can be randomized
  • images (Array): (optional) array of hash with keys 'src' (path to image) and 'cation' (image caption) for images
Sortable(options)

Sortable(options)

Allows you to resort elements within a container by dragging and dropping. Requires the Draggables and Droppables plugins. The container and each item inside the container must have an ID. Sortables are especially useful for lists.

Parameters

  • options (Hash): A hash of options

Hash Options

  • accept (String): The class name for items inside the container (mandatory)
  • activeclass (String): The class for the container when one of its items has started to move
  • hoverclass (String): The class for the container when an acceptable item is inside it
  • helperclass (String): The helper is used to point to the place where the item will be moved. This is the class for the helper.
  • opacity (Float): Opacity (between 0 and 1) of the item while being dragged
  • ghosting (Boolean): When true, the sortable is ghosted when dragged
  • tolerance (String): Either 'pointer', 'intersect', or 'fit'. See Droppable for more details
  • fit (Boolean): When true, sortable must be inside the container in order to drop
  • fx (Integer): Duration for the effect applied to the sortable
  • onchange (Function): Callback that gets called when the sortable list changed. It takes an array of serialized elements
  • floats (Boolean): True if the sorted elements are floated
  • containment (String): Use 'parent' to constrain the drag to the container
  • axis (String): Use 'horizontally' or 'vertically' to constrain dragging to an axis
  • handle (String): The jQuery selector that indicates the draggable handle
  • handle (DOMElement): The node that indicates the draggable handle
  • onHover (Function): Callback that is called when an acceptable item is dragged over the container. Gets the hovering DOMElement as a parameter
  • onOut (Function): Callback that is called when an acceptable item leaves the container. Gets the leaving DOMElement as a parameter
  • cursorAt (Object): The mouse cursor will be moved to the offset on the dragged item indicated by the object, which takes "top", "bottom", "left", and "right" keys
  • onStart (Function): Callback function triggered when the dragging starts
  • onStop (Function): Callback function triggered when the dragging stops

Example

jQuery Code

$('ul').Sortable(
                           	{
                           		accept : 'sortableitem',
                           		activeclass : 'sortableactive',
                            		hoverclass : 'sortablehover',
                            		helperclass : 'sorthelper',
                            		opacity: 	0.5,
                            		fit :	false
                            	}
                            )
SortableAddItem(elem)

SortableAddItem(elem)

A new item can be added to a sortable by adding it to the DOM and then adding it via SortableAddItem.

Returns

jQuery

Parameters

  • elem (DOMElement): A DOM Element to add to the sortable list

Example

jQuery Code

$('#sortable1').append('<li id="newitem">new item</li>')
                        .SortableAddItem($("#new_item")[0])
SortableDestroy()

SortableDestroy()

Destroy a sortable

Returns

jQuery

Example

jQuery Code

$('#sortable1').SortableDestroy();
SwitchHorizontally(speed, callback, easing)

SwitchHorizontally(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
SwitchVertically(speed, callback, easing)

SwitchVertically(speed, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
ToolTip(hash)

ToolTip(hash)

Creates tooltips using title attribute

Returns

jQuery

Parameters

  • hash (Hash): A hash of parameters

Hash Options

  • position (String): tooltip's position ['top'|'left'|'right'|'bottom'|'mouse']
  • ():
  • ():
TransferTo(hash)

TransferTo(hash)

Returns

jQuery

Parameters

  • hash (Hash): A hash of parameters

Hash Options

  • to (Mixed): DOMElement or element ID to transfer to
  • className (String): CSS class to apply to transfer element
  • duration (String): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
UnFold(speed, height, callback, easing)

UnFold(speed, height, callback, easing)

Returns

jQuery

Parameters

  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • height (Integer): the height in pixels to unfold element to
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
animateClass(classToAnimate, speed, callback, easing)

animateClass(classToAnimate, speed, callback, easing)

Returns

jQuery

Parameters

  • classToAnimate (Mixed): string class to animate or array of two classes to animate from to
  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
animateStyle(styleToAnimate, speed, callback, easing)

animateStyle(styleToAnimate, speed, callback, easing)

Returns

jQuery

Parameters

  • styleToAnimate (String): string of inline CSS rules to animate to
  • speed (Mixed): animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
  • callback (Function): (optional) A function to be executed whenever the animation completes.
  • easing (String): (optional) The name of the easing effect that you want to use.
Tabs
activeTab()

activeTab()

Get the position of the currently selected tab (no zero-based index).

Returns

Number

Example

Get the position of the currently selected tab of an interface contained in <div id="container">.

jQuery Code

$('#container').activeTab();
disableTab(tab)

disableTab(tab)

Disable a tab, so that clicking it has no effect.

Returns

jQuery

Parameters

  • tab (String|Number): Either a string that matches the id of the tab (the URL's fragment identifier/hash representing a tab) or an integer specifying the position of the tab (no zero-based index) to be disabled. If this parameter is omitted, the first tab will be disabled.

Example

Disable the second tab of the tab interface contained in <div id="container">.

jQuery Code

$('#container').disableTab(2);
enableTab(tab)

enableTab(tab)

Enable a tab that has been disabled.

Returns

jQuery

Parameters

  • tab (String|Number): Either a string that matches the id of the tab (the URL's fragment identifier/hash representing a tab) or an integer specifying the position of the tab (no zero-based index) to be enabled. If this parameter is omitted, the first tab will be enabled.

Example

Enable the second tab of the tab interface contained in <div id="container">.

jQuery Code

$('#container').enableTab(2);
tabs(initial, settings)

tabs(initial, settings)

Create an accessible, unobtrusive tab interface based on a particular HTML structure.

The underlying HTML has to look like this:

<div id="container"> <ul> <li><a href="#fragment-1">Section 1</a></li> <li><a href="#fragment-2">Section 2</a></li> <li><a href="#fragment-3">Section 3</a></li> </ul> <div id="fragment-1">

</div> <div id="fragment-2">

</div> <div id="fragment-3">

</div> </div>

Each anchor in the unordered list points directly to a section below represented by one of the divs (the URI in the anchor's href attribute refers to the fragment with the corresponding id). Because such HTML structure is fully functional on its own, e.g. without JavaScript, the tab interface is accessible and unobtrusive.

A tab is also bookmarkable via hash in the URL. Use the History/Remote plugin (Tabs will auto-detect its presence) to fix the back (and forward) button.

Returns

jQuery

Parameters

  • initial (Number): An integer specifying the position of the tab (no zero-based index) that gets activated at first (on page load). Two alternative ways to specify the active tab will overrule this argument. First a li element (representing one single tab) belonging to the selected tab class, e.g. set the selected tab class (default: "tabs-selected", see option selectedClass) for one of the unordered li elements in the HTML source. In addition if a fragment identifier/hash in the URL of the page refers to the id of a tab container of a tab interface the corresponding tab will be activated and both the initial argument as well as an eventually declared class attribute will be overruled. Defaults to 1 if omitted.
  • settings (Object): An object literal containing key/value pairs to provide optional settings.

Hash Options

  • disabled (Array<Number>): An array containing the position of the tabs (no zero-based index) that should be disabled on initialization. Default value: null. A tab can also be disabled by simply adding the disabling class (default: "tabs-disabled", see option disabledClass) to the li element representing that particular tab.
  • bookmarkable (Boolean): Boolean flag indicating if support for bookmarking and history (via changing hash in the URL of the browser) is enabled. Default value: false, unless the History/Remote plugin is included. In that case the default value becomes true. @see $.ajaxHistory.initialize
  • remote (Boolean): Boolean flag indicating that tab content has to be loaded remotely from the url given in the href attribute of the tab menu anchor elements.
  • spinner (String): The content of this string is shown in a tab while remote content is loading. Insert plain text as well as an img here. To turn off this notification pass an empty string or null. Default: "Loading&#8230;".
  • hashPrefix (String): A String that is used for constructing the hash the link's href attribute of a remote tab gets altered to, such as "#remote-1". Default value: "remote-tab-".
  • fxFade (Boolean): Boolean flag indicating whether fade in/out animations are used for tab switching. Can be combined with fxSlide. Will overrule fxShow/fxHide. Default value: false.
  • fxSlide (Boolean): Boolean flag indicating whether slide down/up animations are used for tab switching. Can be combined with fxFade. Will overrule fxShow/fxHide. Default value: false.
  • fxSpeed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds (e.g. 1000) to run an animation. Default value: "normal".
  • fxShow (Object): An object literal of the form jQuery's animate function expects for making your own, custom animation to reveal a tab upon tab switch. Unlike fxFade or fxSlide this animation is independent from an optional hide animation. Default value: null. @see animate
  • fxHide (Object): An object literal of the form jQuery's animate function expects for making your own, custom animation to hide a tab upon tab switch. Unlike fxFade or fxSlide this animation is independent from an optional show animation. Default value: null. @see animate
  • fxShowSpeed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds (e.g. 1000) to run the animation specified in fxShow. Default value: fxSpeed.
  • fxHideSpeed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds (e.g. 1000) to run the animation specified in fxHide. Default value: fxSpeed.
  • fxAutoHeight (Boolean): Boolean flag that if set to true causes all tab heights to be constant (being the height of the tallest tab). Default value: false.
  • onClick (Function): A function to be invoked upon tab switch, immediatly after a tab has been clicked, e.g. before the other's tab content gets hidden. The function gets passed three arguments: the first one is the clicked tab (e.g. an anchor element), the second one is the DOM element containing the content of the clicked tab (e.g. the div), the third argument is the one of the tab that gets hidden. If this callback returns false, the tab switch is canceled (use to disallow tab switching for the reason of a failed form validation for example). Default value: null.
  • onHide (Function): A function to be invoked upon tab switch, immediatly after one tab's content got hidden (with or without an animation) and right before the next tab is revealed. The function gets passed three arguments: the first one is the clicked tab (e.g. an anchor element), the second one is the DOM element containing the content of the clicked tab, (e.g. the div), the third argument is the one of the tab that gets hidden. Default value: null.
  • onShow (Function): A function to be invoked upon tab switch. This function is invoked after the new tab has been revealed, e.g. after the switch is completed. The function gets passed three arguments: the first one is the clicked tab (e.g. an anchor element), the second one is the DOM element containing the content of the clicked tab, (e.g. the div), the third argument is the one of the tab that gets hidden. Default value: null.
  • navClass (String): A CSS class that is used to identify the tabs unordered list by class if the required HTML structure differs from the default one. Default value: "tabs-nav".
  • selectedClass (String): The CSS class attached to the li element representing the currently selected (active) tab. Default value: "tabs-selected".
  • disabledClass (String): The CSS class attached to the li element representing a disabled tab. Default value: "tabs-disabled".
  • containerClass (String): A CSS class that is used to identify tab containers by class if the required HTML structure differs from the default one. Default value: "tabs-container".
  • hideClass (String): The CSS class used for hiding inactive tabs. A class is used instead of "display: none" in the style attribute to maintain control over visibility in other media types than screen, most notably print. Default value: "tabs-hide".
  • loadingClass (String): The CSS class used for indicating that an Ajax tab is currently loading, for example by showing a spinner. Default value: "tabs-loading".
  • tabStruct (String): @deprecated A CSS selector or basic XPath expression reflecting a nested HTML structure that is different from the default single div structure (one div with an id inside the overall container holds one tab's content). If for instance an additional div is required to wrap up the several tab containers such a structure is expressed by "div>div". Default value: "div".

Example

Create a basic tab interface.

jQuery Code

$('#container').tabs();

Example

Create a basic tab interface with the second tab initially activated.

jQuery Code

$('#container').tabs(2);

Example

Create a tab interface with the third and fourth tab being disabled.

jQuery Code

$('#container').tabs({disabled: [3, 4]});

Example

Create a tab interface that uses slide down/up animations for showing/hiding tab content upon tab switching.

jQuery Code

$('#container').tabs({fxSlide: true});
triggerTab(tab)

triggerTab(tab)

Activate a tab programmatically with the given position (no zero-based index) or its id, e.g. the URL's fragment identifier/hash representing a tab, as if the tab itself were clicked.

Returns

jQuery

Parameters

  • tab (String|Number): Either a string that matches the id of the tab (the URL's fragment identifier/hash representing a tab) or an integer specifying the position of the tab (no zero-based index) to be activated. If this parameter is omitted, the first tab will be activated.

Example

Activate the second tab of the tab interface contained in <div id="container">.

jQuery Code

$('#container').triggerTab(2);

Example

Activate the first tab of the tab interface contained in <div id="container">.

jQuery Code

$('#container').triggerTab(1);

Example

Activate the first tab of the tab interface contained in <div id="container">.

jQuery Code

$('#container').triggerTab();

Example

Activate a tab via its URL fragment identifier representation.

jQuery Code

$('#container').triggerTab('fragment-2');
Tooltip
Tooltip(settings)

Tooltip(settings)

Display a customized tooltip instead of the default one for every selected element. The tooltip behaviour mimics the default one, but lets you style the tooltip and specify the delay before displaying it.

In addition, it displays the href value, if it is available.

To style the tooltip, use these selectors in your stylesheet:

#tooltip - The tooltip container

#tooltip h3 - The tooltip title

#tooltip p.body - The tooltip body, shown when using showBody

#tooltip p.url - The tooltip url, shown when using showURL

Returns

jQuery

Parameters

  • settings (Object): (optional) Customize your Tooltips

Hash Options

  • delay (Number): The number of milliseconds before a tooltip is display, default is 250
  • event (String): The event on which the tooltip is displayed, default is "mouseover", "click" works fine, too
  • track (Boolean): If true, let the tooltip track the mousemovement, default is false
  • showURL (Boolean): If true, shows the href or src attribute within p.url, default is true
  • showBody (String): If specified, uses the String to split the title, displaying the first part in the h3 tag, all following in the p.body tag, separated with <br/>s, default is null
  • extraClass (String): If specified, adds the class to the tooltip helper, default is null
  • fixPNG (Boolean): If true, fixes transparent PNGs in IE, default is false
  • bodyHandler (Function): TODO document me

Example

Shows tooltips for anchors, inputs and images, if they have a title

jQuery Code

$('a, input, img').Tooltip();

Example

Shows tooltips for labels with no delay, tracking mousemovement, displaying the tooltip when the label is clicked.

jQuery Code

$('label').Tooltip({
  delay: 0,
  track: true,
  event: "click"
});

Example

This example starts with modifying the global settings, applying them to all following Tooltips; Afterwards, Tooltips for anchors with class pretty are created with an extra class for the Tooltip: "fancy" for anchors, "fancy-img" for images

jQuery Code

// modify global settings
$.extend($.fn.Tooltip.defaults, {
	track: true,
	delay: 0,
	showURL: false,
	showBody: " - ",
 fixPNG: true
});
// setup fancy tooltips
$('a.pretty').Tooltip({
	 extraClass: "fancy"
});
 $('img.pretty').Tooltip({
	 extraClass: "fancy-img",
});