JQuery

For Javascrips & Ajax - ProminentLabs.com

JQuery Tutorial . Download from http://jquery.com

Undertakes Ruby on Rails/PHP/JavaScript Works.
Contact me on
amjithps(at)gmail.com, amjithps(at)prominentlabs.com
Skype : amjithps
Yahoo : amjith56_ps

Designed and developed by Prominent Technology Solutions. amjithps@prominentlabs.com

JQuery from Prominentlabs.com

Contents


Jquery - Complete Reference

Source : visualjquery.com
Author : Remy Sharp originally by Yehuda Katz

Prominent Systems and Technologies
Ruby on Rails, PHP and Javascript


Click here for user friendly API Tutorials

How to install jQuery

In this section we will download and install jQuery. jQuery comes as single js file. So, its very easy to download and install jQuery in any web application. You can even add it to your existing application and use jQuery functions. Due to this simplicity programmers are using jQuery for adding Ajax capabilities into their web applications.

You can download the latest version of jQuery from its official site http://jquery.com/ 

After downloading, just place a javascript reference of the file to the HTML page and you are ready to go.

(download jquery-x.x.x.min.js and add into js directory of your application. You can rename it to jquery-x.x.x.js.

You are now all set and ready to add the jQuery support into your web application.)




Functions Follows.................


Chapter 1 - Core Functions


$(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.

Examples

Description:

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

jQuery Code:
$("<div><p>Hello</p></div>").appendTo("#body")


******************************************************

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.

Examples

Before:
<p>This is just a test.</p><p>So is this</p>
jQuery Code:
$("p").eq(1)
Result:
[ <p>So is this</p> ]

**************************************************




$(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 all of the other $() operations on your page. 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.

Examples

Description:

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

jQuery Code:
$(function(){ // Document is ready });



**********************************************************



$(obj)

A means of creating a cloned copy of a jQuery object. This function copies the set of matched elements from one jQuery object and creates another, new, jQuery object containing the same elements.

Returns

jQuery

Parameters

  • obj (jQuery): The jQuery object to be cloned.

Examples

Description:

Locates all p elements with all div elements, without disrupting the original jQuery object contained in 'div' (as would normally be the case if a simple div.find("p") was done).

jQuery Code:
var div = $("div"); $( div ).find("p");


******************************************************


$(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, $() looks for DOM elements within the context of the current HTML document.

Returns

jQuery

Parameters

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

Examples

Description:

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

Before:
<p>one</p> <div><p>two</p></div> <p>three</p>
jQuery Code:
$("div > p")
Result:
[ <p>two</p> ]
Description:

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

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

This finds all div elements within the specified XML document.

jQuery Code:
$("div", xml.responseXML)


********************************************


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 element.

Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set.

Returns

jQuery

Parameters

  • fn (Function): A function to execute

Examples

Description:

Iterates over two images and sets their src property

Before:
<img/><img/>
jQuery Code:
$("img").each(function(i){ this.src = "test" + i + ".jpg"; });
Result:
<img src="test0.jpg"/><img src="test1.jpg"/>


*************************************************


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.

Examples

Before:
<p>This is just a test.</p><p>So is this</p>
jQuery Code:
$("p").eq(1)
Result:
[ <p>So is this</p> ]


*******************************************


$.extend(prop)

Extends the jQuery object itself. Can be used to add functions into the jQuery namespace and to add plugin methods (plugins).

Returns

Object

Parameters

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

Examples

Description:

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();
Description:

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; } });

***********************************************


get()

Access all matched 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).

Returns

Array<Element>

Examples

Description:

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

Before:
<img src="test1.jpg"/> <img src="test2.jpg"/>
jQuery Code:
$("img").get();
Result:
[ <img src="test1.jpg"/> <img src="test2.jpg"/> ]


*******************************************************

get(num)

Access a single matched element. num is used to access the Nth element matched.

Returns

Element

Parameters

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

Examples

Description:

Selects all images in the document and returns the first one

Before:
<img src="test1.jpg"/> <img src="test2.jpg"/>
jQuery Code:
$("img").get(0);
Result:
[ <img src="test1.jpg"/> ]


************************************************************


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.

Examples

Before:
<p>This is just a test.</p><p>So is this</p>
jQuery Code:
$("p").gt(0)
Result:
[ <p>So is this</p> ]


***************************************************



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

Examples

Description:

Returns the index for the element with ID foobar

Before:
<div id="foobar"></div><b></b><span id="foo"></span>
jQuery Code:
$("").index( $('#foobar')[0] )
Result:
0
Description:

Returns the index for the element with ID foo

Before:
<div id="foobar"></div><b></b><span id="foo"></span>
jQuery Code:
$("").index( $('#foo'))
Result:
2
Description:

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

Before:
<div id="foobar"></div><b></b><span id="foo"></span>
jQuery Code:
$("*").index( $('#bar'))
Result:
-1



**********************************************************


length

The number of elements currently matched.

Returns

Number

Examples

Before:
<img src="test1.jpg"/> <img src="test2.jpg"/>
jQuery Code:
$("img").length;
Result:
2


****************************************************


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.

Examples

Before:
<p>This is just a test.</p><p>So is this</p>
jQuery Code:
$("p").lt(1)
Result:
[ <p>This is just a test.</p> ]


*********************************************

$.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

Examples

Description:

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';
Description:

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


**************************************************


size()

The number of elements currently matched.

Returns

Number

Examples

Before:
<img src="test1.jpg"/> <img src="test2.jpg"/>
jQuery Code:
$("img").size();
Result:
2




-----------------------------------------------------------------------


Chapter 2 - DOM Functions


1. Attributes


addClass(class)

Adds the specified class to each of the set of matched elements.

Returns

jQuery

Parameters

  • class (String): A CSS class to add to the elements

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").addClass("selected")
Result:
[ <p class="selected">Hello</p> ]



************************************************


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.

Returns

Object

Parameters

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

Examples

Description:

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

Before:
<img src="test.jpg"/>
jQuery Code:
$("img").attr("src");
Result:
test.jpg



**************************************************


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.

Examples

Description:

Sets src and alt attributes to all images.

Before:
<img/>
jQuery Code:
$("img").attr({ src: "test.jpg", alt: "Test Image" });
Result:
<img src="test.jpg" alt="Test Image"/>



****************************************


attr(key, value)

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

Can compute values provided as ${formula}, see second example.

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.

Examples

Description:

Sets src attribute to all images.

Before:
<img/>
jQuery Code:
$("img").attr("src","test.jpg");
Result:
<img src="test.jpg"/>
Description:

Sets title attribute from src attribute, a shortcut for attr(String,Function)

Before:
<img src="test.jpg" />
jQuery Code:
$("img").attr("title", "${this.src}");
Result:
<img src="test.jpg" title="test.jpg" />


***************************************************



attr(key, value)

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

Instead of a value, 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.

Examples

Description:

Sets title attribute from src attribute.

Before:
<img src="test.jpg" />
jQuery Code:
$("img").attr("title", function() { return this.src });
Result:
<img src="test.jpg" title="test.jpg" />



********************************************************


html()

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

Returns

String

Examples

Before:
<div><input/></div>
jQuery Code:
$("div").html();
Result:
<input/>

*********************************************


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.

Examples

Before:
<div><input/></div>
jQuery Code:
$("div").html("<b>new stuff</b>");
Result:
<div><b>new stuff</b></div>


******************************************************


removeAttr(name)

Remove an attribute from each of the matched elements.

Returns

jQuery

Parameters

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

Examples

Before:
<input disabled="disabled"/>
jQuery Code:
$("input").removeAttr("disabled")
Result:
<input/>


*****************************************

removeClass(class)

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

Returns

jQuery

Parameters

  • class (String): (optional) A CSS class to remove from the elements

Examples

Before:
<p class="selected">Hello</p>
jQuery Code:
$("p").removeClass()
Result:
[ <p>Hello</p> ]
Before:
<p class="selected first">Hello</p>
jQuery Code:
$("p").removeClass("selected")
Result:
[ <p class="first">Hello</p> ]


*******************************************************

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

Examples

Description:

Gets the concatenated text of all paragraphs

Before:
<p><b>Test</b> Paragraph.</p><p>Paraparagraph</p>
jQuery Code:
$("p").text();
Result:
Test Paragraph.Paraparagraph


*************************************************************

text(val)

Set the text contents of all matched elements. This has the same effect as html().

Returns

String

Parameters

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

Examples

Description:

Sets the text of all paragraphs.

Before:
<p>Test Paragraph.</p>
jQuery Code:
$("p").text("Some new text.");
Result:
<p>Some new text.</p>


*****************************************************


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

Examples

Before:
<p>Hello</p><p class="selected">Hello Again</p>
jQuery Code:
$("p").toggleClass("selected")
Result:
[ <p class="selected">Hello</p>, <p>Hello Again</p> ]


********************************************************


val()

Get the current value of the first matched element.

Returns

String

Examples

Before:
<input type="text" value="some text"/>
jQuery Code:
$("input").val();
Result:
"some text"


**************************************************


val(val)

Set the value of every matched element.

Returns

jQuery

Parameters

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

Examples

Before:
<input type="text" value="some text"/>
jQuery Code:
$("input").val("test");
Result:
<input type="text" value="test"/>


*****************************************************



2. Manipulations


after(content)

Insert content after each of the matched elements.

Returns

jQuery

Parameters

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

Examples

Description:

Inserts some HTML after all paragraphs.

Before:
<p>I would like to say: </p>
jQuery Code:
$("p").after("<b>Hello</b>");
Result:
<p>I would like to say: </p><b>Hello</b>
Description:

Inserts an Element after all paragraphs.

Before:
<b id="foo">Hello</b><p>I would like to say: </p>
jQuery Code:
$("p").after( $("#foo")[0] );
Result:
<p>I would like to say: </p><b id="foo">Hello</b>
Description:

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

Before:
<b>Hello</b><p>I would like to say: </p>
jQuery Code:
$("p").after( $("b") );
Result:
<p>I would like to say: </p><b>Hello</b>




**********************************************


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

Examples

Description:

Appends some HTML to all paragraphs.

Before:
<p>I would like to say: </p>
jQuery Code:
$("p").append("<b>Hello</b>");
Result:
<p>I would like to say: <b>Hello</b></p>
Description:

Appends an Element to all paragraphs.

Before:
<p>I would like to say: </p><b id="foo">Hello</b>
jQuery Code:
$("p").append( $("#foo")[0] );
Result:
<p>I would like to say: <b id="foo">Hello</b></p>
Description:

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

Before:
<p>I would like to say: </p><b>Hello</b>
jQuery Code:
$("p").append( $("b") );
Result:
<p>I would like to say: <b>Hello</b></p>




***********************************************************


appendTo(expr)

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

  • expr (String): A jQuery expression of elements to match.

Examples

Description:

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

Before:
<p>I would like to say: </p><div id="foo"></div>
jQuery Code:
$("p").appendTo("#foo");
Result:
<div id="foo"><p>I would like to say: </p></div>

***************************************************


before(content)

Insert content before each of the matched elements.

Returns

jQuery

Parameters

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

Examples

Description:

Inserts some HTML before all paragraphs.

Before:
<p>I would like to say: </p>
jQuery Code:
$("p").before("<b>Hello</b>");
Result:
<b>Hello</b><p>I would like to say: </p>
Description:

Inserts an Element before all paragraphs.

Before:
<p>I would like to say: </p><b id="foo">Hello</b>
jQuery Code:
$("p").before( $("#foo")[0] );
Result:
<b id="foo">Hello</b><p>I would like to say: </p>
Description:

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

Before:
<p>I would like to say: </p><b>Hello</b>
jQuery Code:
$("p").before( $("b") );
Result:
<b>Hello</b><p>I would like to say: </p>


**********************************************************


clone()

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

Examples

Description:

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

Before:
<b>Hello</b><p>, how are you?</p>
jQuery Code:
$("b").clone().prependTo("p");
Result:
<b>Hello</b><p><b>Hello</b>, how are you?</p>


***********************************************************


empty()

Removes all child nodes from the set of matched elements.

Returns

jQuery

Examples

Before:
<p>Hello, <span>Person</span> <a href="#">and person</a></p>
jQuery Code:
$("p").empty()
Result:
[ <p></p> ]


*************************************************


insertAfter(expr)

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

  • expr (String): A jQuery expression of elements to match.

Examples

Description:

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

Before:
<p>I would like to say: </p><div id="foo">Hello</div>
jQuery Code:
$("p").insertAfter("#foo");
Result:
<div id="foo">Hello</div><p>I would like to say: </p>


*********************************************************


insertBefore(expr)

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

  • expr (String): A jQuery expression of elements to match.

Examples

Description:

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

Before:
<div id="foo">Hello</div><p>I would like to say: </p>
jQuery Code:
$("p").insertBefore("#foo");
Result:
<p>I would like to say: </p><div id="foo">Hello</div>

*****************************************


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.

Examples

Description:

Prepends some HTML to all paragraphs.

Before:
<p>I would like to say: </p>
jQuery Code:
$("p").prepend("<b>Hello</b>");
Result:
<p><b>Hello</b>I would like to say: </p>
Description:

Prepends an Element to all paragraphs.

Before:
<p>I would like to say: </p><b id="foo">Hello</b>
jQuery Code:
$("p").prepend( $("#foo")[0] );
Result:
<p><b id="foo">Hello</b>I would like to say: </p>
Description:

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

Before:
<p>I would like to say: </p><b>Hello</b>
jQuery Code:
$("p").prepend( $("b") );
Result:
<p><b>Hello</b>I would like to say: </p>

**********************************************************



prependTo(expr)

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

  • expr (String): A jQuery expression of elements to match.

Examples

Description:

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

Before:
<p>I would like to say: </p><div id="foo"><b>Hello</b></div>
jQuery Code:
$("p").prependTo("#foo");
Result:
<div id="foo"><p>I would like to say: </p><b>Hello</b></div>



******************************************************



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.

Examples

Before:
<p>Hello</p> how are <p>you?</p>
jQuery Code:
$("p").remove();
Result:
how are
Before:
<p class="hello">Hello</p> how are <p>you?</p>
jQuery Code:
$("p").remove(".hello");
Result:
how are <p>you?</p>


********************************************************

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.

Examples

Before:
<p>Test Paragraph.</p>
jQuery Code:
$("p").wrap("<div class='wrap'></div>");
Result:
<div class='wrap'><p>Test Paragraph.</p></div>


****************************************************************


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.

Examples

Before:
<p>Test Paragraph.</p><div id="content"></div>
jQuery Code:
$("p").wrap( document.getElementById('content') );
Result:
<div id="content"><p>Test Paragraph.</p></div>


**********************************************************


3. Traversing


add(expr)

Adds the elements matched by the expression to the jQuery object. This can be used to concatenate the result sets of two expressions.

Returns

jQuery

Parameters

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

Examples

Before:
<p>Hello</p><p><span>Hello Again</span></p>
jQuery Code:
$("p").add("span")
Result:
[ <p>Hello</p>, <span>Hello Again</span> ]


***********************************


add(elements)

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

This is used to add a set of Elements to a jQuery object.

Returns

jQuery

Parameters

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

Examples

Before:
<p>Hello</p><p><span id="a">Hello Again</span></p>
jQuery Code:
$("p").add( document.getElementById("a") )
Result:
[ <p>Hello</p>, <span id="a">Hello Again</span> ]
Before:
<p>Hello</p><p><span id="a">Hello Again</span><span id="b">And Again</span></p>
jQuery Code:
$("p").add([document.getElementById("a"), document.getElementById("b")])
Result:
[ <p>Hello</p>, <span id="a">Hello Again</span>, <span id="b">And Again</span> ]


******************************************************


children(expr)

Get a set of elements containing all of the unique children 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 child Elements with

Examples

Description:

Find all children of each div.

Before:
<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
jQuery Code:
$("div").children()
Result:
[ <span>Hello Again</span> ]
Description:

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

Before:
<div><span>Hello</span><p class="selected">Hello Again</p><p>And Again</p></div>
jQuery Code:
$("div").children(".selected")
Result:
[ <p class="selected">Hello Again</p> ]


***************************************************


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.

Examples

Before:
<p>This is just a test.</p><p>So is this</p>
jQuery Code:
$("p").contains("test")
Result:
[ <p>This is just a test.</p> ]




*******************************************

end()

End the most recent 'destructive' operation, reverting the list of matched elements back to its previous state. After an end operation, the list of matched elements will revert to the last state of matched elements.

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

Returns

jQuery

Examples

Description:

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

Before:
<p><span>Hello</span>, how are you?</p>
jQuery Code:
$("p").find("span").end();
Result:
[ <p>...</p> ]


********************************************

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 String array of expressions to apply multiple filters at once.

Returns

jQuery

Parameters

  • expression (String|Array<String>): Expression(s) to search with.

Examples

Description:

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

Before:
<p class="selected">Hello</p><p>How are you?</p>
jQuery Code:
$("p").filter(".selected")
Result:
[ <p class="selected">Hello</p> ]
Description:

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

Before:
<p>Hello</p><p>Hello Again</p><p class="selected">And Again</p>
jQuery Code:
$("p").filter([".selected", ":first"])
Result:
[ <p>Hello</p>, <p class="selected">And Again</p> ]



**********************************************

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

Examples

Description:

Remove all elements that have a child ol element

Before:
<p><ol><li>Hello</li></ol></p><p>How are you?</p>
jQuery Code:
$("p").filter(function(index) { return $("ol", this).length == 0; })
Result:
[ <p>How are you?</p> ]



********************************************************


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.

Examples

Description:

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

Before:
<p><span>Hello</span>, how are you?</p>
jQuery Code:
$("p").find("span");
Result:
[ <span>Hello</span> ]


****************************************************


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

Examples

Description:

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

Before:
<form><input type="checkbox" /></form>
jQuery Code:
$("input[@type='checkbox']").parent().is("form")
Result:
true
Description:

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

Before:
<form><p><input type="checkbox" /></p></form>
jQuery Code:
$("input[@type='checkbox']").parent().is("form")
Result:
false



***********************************************************




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, not all next siblings.

Can be filtered with an optional expressions.

Returns

jQuery

Parameters

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

Examples

Description:

Find the very next sibling of each paragraph.

Before:
<p>Hello</p><p>Hello Again</p><div><span>And Again</span></div>
jQuery Code:
$("p").next()
Result:
[ <p>Hello Again</p>, <div><span>And Again</span></div> ]
Description:

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

Before:
<p>Hello</p><p class="selected">Hello Again</p><div><span>And Again</span></div>
jQuery Code:
$("p").next(".selected")
Result:
[ <p class="selected">Hello Again</p> ]



**************************************************************


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

Examples

Description:

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

Before:
<p>Hello</p><p id="selected">Hello Again</p>
jQuery Code:
$("p").not( $("#selected")[0] )
Result:
[ <p>Hello</p> ]


***********************************************************


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

Examples

Description:

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

Before:
<p>Hello</p><p id="selected">Hello Again</p>
jQuery Code:
$("p").not("#selected")
Result:
[ <p>Hello</p> ]


************************************


parent(expr)

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

Can be filtered with an optional expressions.

Returns

jQuery

Parameters

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

Examples

Description:

Find the parent element of each paragraph.

Before:
<div><p>Hello</p><p>Hello</p></div>
jQuery Code:
$("p").parent()
Result:
[ <div><p>Hello</p><p>Hello</p></div> ]
Description:

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

Before:
<div><p>Hello</p></div><div class="selected"><p>Hello Again</p></div>
jQuery Code:
$("p").parent(".selected")
Result:
[ <div class="selected"><p>Hello Again</p></div> ]


**********************************************

parents(expr)

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

Can be filtered with an optional expressions.

Returns

jQuery

Parameters

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

Examples

Description:

Find all parent elements of each span.

Before:
<html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html>
jQuery Code:
$("span").parents()
Result:
[ <body>...</body>, <div>...</div>, <p><span>Hello</span></p> ]
Description:

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

Before:
<html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html>
jQuery Code:
$("span").parents("p")
Result:
[ <p><span>Hello</span></p> ]

*******************************************************




prev(expr)

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

Can be filtered with an optional expressions.

It only returns the immediately previous sibling, not all previous siblings.

Returns

jQuery

Parameters

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

Examples

Description:

Find the very previous sibling of each paragraph.

Before:
<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
jQuery Code:
$("p").prev()
Result:
[ <div><span>Hello Again</span></div> ]
Description:

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

Before:
<div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p>
jQuery Code:
$("p").prev(".selected")
Result:
[ <div><span>Hello</span></div> ]



***********************************************************


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

Examples

Description:

Find all siblings of each div.

Before:
<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
jQuery Code:
$("div").siblings()
Result:
[ <p>Hello</p>, <p>And Again</p> ]
Description:

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

Before:
<div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p>
jQuery Code:
$("div").siblings(".selected")
Result:
[ <p class="selected">Hello Again</p> ]





Chapter 3 - CSS




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.

Examples

Description:

Retrieves the color style of the first paragraph

Before:
<p style="color:red;">Test Paragraph.</p>
jQuery Code:
$("p").css("color");
Result:
"red"
Description:

Retrieves the font-weight style of the first paragraph.

Before:
<p style="font-weight: bold;">Test Paragraph.</p>
jQuery Code:
$("p").css("font-weight");
Result:
"bold"

*******************************************


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.

Examples

Description:

Sets color and background styles to all p elements.

Before:
<p>Test Paragraph.</p>
jQuery Code:
$("p").css({ color: "red", background: "blue" });
Result:
<p style="color:red; background:blue;">Test Paragraph.</p>


*********************************************


css(key, value)

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

Returns

jQuery

Parameters

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

Examples

Description:

Changes the color of all paragraphs to red

Before:
<p>Test Paragraph.</p>
jQuery Code:
$("p").css("color","red");
Result:
<p style="color:red;">Test Paragraph.</p>


*************************************





Chapter 4 - Javascript


$.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

Examples

Description:

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

jQuery Code:
$.browser.msie
Description:

Alerts "this is safari!" only for safari browsers

jQuery Code:
if($.browser.safari) { $( function() { alert("this is safari!"); } ); }










$.each(obj, fn)

A generic iterator function, which can be used to seemlessly 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.

Examples

Description:

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 ); });
Description:

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 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

Examples

Description:

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" }
Description:

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)

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.

Examples

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



$.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.

Examples

Description:

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]
Description:

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]
Description:

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 two arrays together, removing all duplicates.

The new array is: All the results from the first array, followed by the unique results from the second array.

Returns

Array

Parameters

  • first (Array): The first array to merge.
  • second (Array): The second array to merge.

Examples

Description:

Merges two arrays, removing the duplicate 2

jQuery Code:
$.merge( [0,1,2], [2,3,4] )
Result:
[0,1,2,3,4]
Description:

Merges two arrays, removing the duplicates 3 and 2

jQuery Code:
$.merge( [3,2,1], [4,3,2] )
Result:
[3,2,1,4]



$.trim(str)

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

Returns

String

Parameters

  • str (String): The string to trim.

Examples

jQuery Code:
$.trim(" hello, how are you? ");
Result:
"hello, how are you?"





Chapter 5 - Effects


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").

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. Oterwise 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.

Examples

jQuery Code:
$("p").animate({ height: 'toggle', opacity: 'toggle' }, "slow");
jQuery Code:
$("p").animate({ left: 50, opacity: 'show' }, 500);
Description:

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)

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.

Examples

jQuery Code:
$("p").fadeIn("slow");
jQuery Code:
$("p").fadeIn("slow",function(){ alert("Animation Done."); });





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.

Examples

jQuery Code:
$("p").fadeOut("slow");
jQuery Code:
$("p").fadeOut("slow",function(){ alert("Animation Done."); });



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.

Examples

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


hide()

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

Returns

jQuery

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").hide()
Result:
[ <p style="display: none">Hello</p> ]

var pass = true, div = $("div"); div.hide().each(function(){ if ( this.style.display != "none" ) pass = false; }); ok( pass, "Hide" );



hide()

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

Returns

jQuery

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").hide()
Result:
[ <p style="display: none">Hello</p> ]



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.

Examples

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


show()

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

Returns

jQuery

Examples

Before:
<p style="display: none">Hello</p>
jQuery Code:
$("p").show()
Result:
[ <p style="display: block">Hello</p> ]


show()

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

Returns

jQuery

Examples

Before:
<p style="display: none">Hello</p>
jQuery Code:
$("p").show()
Result:
[ <p style="display: block">Hello</p> ]



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.

Examples

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





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.

Examples

jQuery Code:
$("p").slideDown("slow");
jQuery Code:
$("p").slideDown("slow",function(){ alert("Animation Done."); });


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.

Examples

jQuery Code:
$("p").slideToggle("slow");
jQuery Code:
$("p").slideToggle("slow",function(){ alert("Animation Done."); });


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.

Examples

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



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

Examples

Before:
<p>Hello</p><p style="display: none">Hello Again</p>
jQuery Code:
$("p").toggle()
Result:
[ <p style="display: none">Hello</p>, <p style="display: block">Hello Again</p> ]


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

Examples

Before:
<p>Hello</p><p style="display: none">Hello Again</p>
jQuery Code:
$("p").toggle()
Result:
[ <p style="display: none">Hello</p>, <p style="display: block">Hello Again</p> ]






Chapter 6 - Events









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 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

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").bind("click", function(){ alert( $(this).text() ); });
Result:
alert("Hello")
Description:

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")
Description:

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

jQuery Code:
$("form").bind("submit", function() { return false; })
Description:

Cancel only the default action by using the preventDefault method.

jQuery Code:
$("form").bind("submit", function(event){ event.preventDefault(); });
Description:

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

jQuery Code:
$("form").bind("submit", function(event){ event.stopPropagation(); });



blur()

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

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

Examples

Before:
<p onblur="alert('Hello');">Hello</p>
jQuery Code:
$("p").blur();
Result:
alert('Hello');


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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").blur( function() { alert("Hello"); } );
Result:
<p onblur="alert('Hello');">Hello</p>



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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").change( function() { alert("Hello"); } );
Result:
<p onchange="alert('Hello');">Hello</p>



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

Examples

Before:
<p onclick="alert('Hello');">Hello</p>
jQuery Code:
$("p").click();
Result:
alert('Hello');



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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").click( function() { alert("Hello"); } );
Result:
<p onclick="alert('Hello');">Hello</p>


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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").dblclick( function() { alert("Hello"); } );
Result:
<p ondblclick="alert('Hello');">Hello</p>

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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").error( function() { alert("Hello"); } );
Result:
<p onerror="alert('Hello');">Hello</p>


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

Examples

Before:
<p onfocus="alert('Hello');">Hello</p>
jQuery Code:
$("p").focus();
Result:
alert('Hello');

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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").focus( function() { alert("Hello"); } );
Result:
<p onfocus="alert('Hello');">Hello</p>



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.

Examples

jQuery Code:
$("p").hover(function(){ $(this).addClass("over"); },function(){ $(this).addClass("out"); });



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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").keydown( function() { alert("Hello"); } );
Result:
<p onkeydown="alert('Hello');">Hello</p>



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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").keypress( function() { alert("Hello"); } );
Result:
<p onkeypress="alert('Hello');">Hello</p>


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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").keyup( function() { alert("Hello"); } );
Result:
<p onkeyup="alert('Hello');">Hello</p>








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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").load( function() { alert("Hello"); } );
Result:
<p onload="alert('Hello');">Hello</p>



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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").mousedown( function() { alert("Hello"); } );
Result:
<p onmousedown="alert('Hello');">Hello</p>


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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").mousemove( function() { alert("Hello"); } );
Result:
<p onmousemove="alert('Hello');">Hello</p>

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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").mouseout( function() { alert("Hello"); } );
Result:
<p onmouseout="alert('Hello');">Hello</p>



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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").mouseover( function() { alert("Hello"); } );
Result:
<p onmouseover="alert('Hello');">Hello</p>



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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").mouseup( function() { alert("Hello"); } );
Result:
<p onmouseup="alert('Hello');">Hello</p>





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

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").one("click", function(){ alert( $(this).text() ); });
Result:
alert("Hello")




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 exactly what 99.99% of all Javascript code needs to run.

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.

Examples

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


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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").resize( function() { alert("Hello"); } );
Result:
<p onresize="alert('Hello');">Hello</p>

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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").scroll( function() { alert("Hello"); } );
Result:
<p onscroll="alert('Hello');">Hello</p>




select()

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

Returns

jQuery

Examples

Before:
<p onselect="alert('Hello');">Hello</p>
jQuery Code:
$("p").select();
Result:
alert('Hello');



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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").select( function() { alert("Hello"); } );
Result:
<p onselect="alert('Hello');">Hello</p>


submit()

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

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

Examples

Description:

Triggers all submit events registered for forms, but does not submit the form

jQuery Code:
$("form").submit();


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.

Examples

Description:

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

Before:
<form id="myform"><input /></form>
jQuery Code:
$("#myform").submit( function() { return $("input", this).val().length > 0; } );



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.

Examples

jQuery Code:
$("p").toggle(function(){ $(this).addClass("selected"); },function(){ $(this).removeClass("selected"); });



trigger(type)

Trigger a type of event on every matched element.

Returns

jQuery

Parameters

  • type (String): An event type to trigger.

Examples

Before:
<p click="alert('hello')">Hello</p>
jQuery Code:
$("p").trigger("click")
Result:
alert('hello')


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

Examples

Before:
<p onclick="alert('Hello');">Hello</p>
jQuery Code:
$("p").unbind()
Result:
[ <p>Hello</p> ]
Before:
<p onclick="alert('Hello');">Hello</p>
jQuery Code:
$("p").unbind( "click" )
Result:
[ <p>Hello</p> ]
Before:
<p onclick="alert('Hello');">Hello</p>
jQuery Code:
$("p").unbind( "click", function() { alert("Hello"); } )
Result:
[ <p>Hello</p> ]


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.

Examples

Before:
<p>Hello</p>
jQuery Code:
$("p").unload( function() { alert("Hello"); } );
Result:
<p onunload="alert('Hello');">Hello</p>







Chapter 7 - Ajax






$.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.

$.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: Make sure the server sends the right mimetype (eg. xml as "text/xml"). Sending the wrong mimetype will get you into serious trouble that jQuery can't solve.

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 send 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.

Examples

Description:

Load and execute a JavaScript file.

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

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 ); } });
Description:

Loads data synchronously. Blocks the browser while the requests is active. It is better to block user interaction with others means when synchronization is necessary, instead to block the complete browser.

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

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 });


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.

Examples

Description:

Show a message when an AJAX request completes.

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


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.

Examples

Description:

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)

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

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

Returns

jQuery

Parameters

  • callback (Function): The function to execute.

Examples

Description:

Show a message before an AJAX request is send.

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


$.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

Examples

Description:

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 });


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.

Examples

Description:

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

jQuery Code:
$("#loading").ajaxStart(function(){ $(this).show(); });


ajaxStop(callback)

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

Returns

jQuery

Parameters

  • callback (Function): The function to execute.

Examples

Description:

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

jQuery Code:
$("#loading").ajaxStop(function(){ $(this).hide(); });


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.

Examples

Description:

Show a message when an AJAX request completes successfully.

jQuery Code:
$("#msg").ajaxSuccess(function(request, settings){ $(this).append("<li>Successful Request!</li>"); });


$.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.

Examples

Description:

Make all AJAX requests timeout after 5 seconds.

jQuery Code:
$.ajaxTimeout( 5000 );


$.get(url, params, callback)

Load a remote page 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): (optional) A function to be executed whenever the data is loaded.

Examples

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


$.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.

Examples

jQuery Code:
$.getIfModified("test.html");
jQuery Code:
$.getIfModified("test.html", { name: "John", time: "2pm" } );
jQuery Code:
$.getIfModified("test.cgi", function(data){ alert("Data Loaded: " + data); });
jQuery Code:
$.getifModified("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); } );

$.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.

Examples

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


$.getScript(url, callback)

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

Warning: Safari <= 2.0.x is unable to evalulate 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.

Examples

jQuery Code:
$.getScript("test.js");
jQuery Code:
$.getScript("test.js", function(){ alert("Script loaded and executed."); });


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).

Examples

Before:
<div id="feeds"></div>
jQuery Code:
$("#feeds").load("feeds.html");
Result:
<div id="feeds"><b>45</b> feeds found.</div>
Description:

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)

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).

Examples

Before:
<div id="feeds"></div>
jQuery Code:
$("#feeds").loadIfModified("feeds.html");
Result:
<div id="feeds"><b>45</b> feeds found.</div>



$.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.

Examples

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


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 form plugin. It also takes multiple-selects into account, while this method recognizes only a single option.

Returns

String

Examples

Description:

Serialize a selection of input elements to a string

Before:
<input type='text' name='name' value='John'/> <input type='text' name='location' value='Boston'/>
jQuery Code:
$("input[@type=text]").serialize();



________________________________________________________________________________________

Amjith PS, dated : 1/8/2008

amjithps@prominentlabs.com

Prominent Systems and Technologies
Ruby on Rails, PHP, Javascript

For Consulting Assistance : amjithps@gmail.com, Skype : amjithps , Yahoo : amjith56_ps

Blogs : Googleknol talks

Comments

Amjith PS
Amjith PS
Software Engg
India
Article rating:
Your rating:
Moderated collaboration
All signed in users can suggest edits to the knol, but these need approval from an author before being published
Version: 8
Versions
Last edited: Jun 26, 2009 1:46 AM.

Reviews

    Similar Content on the Web

    Knol translations

    Activity for this knol

    This week:

    27pageviews

    Totals:

    889pageviews
    2comments