Friday, October 7, 2011

keypress(Function)

keypress(Function fn) returns jQuery

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

Example:

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

HTML:
<p>Hello</p>

Result:
<p onkeypress="alert('Hello');">Hello</p>

dblclick(Function)

dblclick(Function fn) returns jQuery

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

Example:

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

HTML:
<p>Hello</p>

Result:
<p ondblclick="alert('Hello');">Hello</p>

focus(Function)

focus(Function fn) returns jQuery

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

Example:

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

HTML:
<p>Hello</p>

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

submit()

submit() returns jQuery

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.

Example:

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

submit(Function)

submit(Function fn) returns jQuery

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

Example:

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

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

HTML:

<form id="myform"><input /></form>

scroll(Function)

scroll(Function fn) returns jQuery
Bind a function to the scroll event of each matched element.

Example:

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

HTML:
<p>Hello</p>

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

Sunday, October 2, 2011

ready()

ready(Function fn) returns jQuery

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 onload event handler, otherwise $(document).ready() may not fire.

Example:

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

hover()

hover(Function over, Function out) returns jQuery

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

Example:

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

toggle()

toggle(Function even, Function odd) returns jQuery
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.

Example:


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

trigger()

trigger(String type, Array data) returns jQuery
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.

Example:

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

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

Result:
alert('hello')

unbind()

unbind(String type, Function fn) returns jQuery
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.

Example:

$("p").unbind()

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

Result:
[ <p>Hello</p> ]

one()

one(String type, Object data, Function fn) returns jQuery

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.

Example:


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

HTML:
<p>Hello</p>

Result:
alert("Hello")

bind()

bind(String type, Object data, Function fn) returns jQuery

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.
Calling bind with an event type of "unload" will automatically use the one method instead of bind to prevent memory leaks.

Example:

<div class="codeview">
$("p").bind("click", function(){
alert( $(this).text() );
});

HTML:
<p>Hello</p>

Result:
alert("Hello")
</div>

$.browser()

$.browser() returns Boolean
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.

Example:

Returns true if the current useragent is some version of microsoft's internet explorer
$.browser.msie

Example:
Alerts "this is safari!" only for safari browsers
if($.browser.safari) { $( function() { alert("this is safari!"); } ); }

$.map(Array,Function)

$.map(Array array, Function fn) returns Array
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.

Example:

Maps the original array to a new one and adds 4 to each value.
$.map( [0,1,2], function(i){
return i + 4;
});

Result:
[4, 5, 6]

$.unique(Array)

$.unique(Array array) returns Array
Reduce an array (of jQuery objects only) to its unique elements.

Example:

Reduces the arrays of jQuery objects to unique elements by removing the duplicates of x2 and x3
$.unique( [x1, x2, x3, x2, x3] )

Result:
[x1, x2, x3]

$.merge(Array,Array)

$.merge(Array first, Array second) returns Array
Merge two arrays together by concatenating them.

Example:

Merges two arrays.
$.merge( [0,1,2], [2,3,4] )
Result:
[0,1,2,2,3,4]

$.trim(String)

$.trim(String str) returns String
Remove the whitespace from the beginning and end of a string.

Example:

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

Result:
"hello, how are you?"

$.each(Object,Function)

$.each(Object obj, Function fn) returns Object
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.

Example:

This is an example of iterating over the items in an array, accessing both the current item and its
index.
$.each( [0,1,2], function(i, n){
alert( "Item #" + i + ": " + n );
});

$.extend(Object,Object,Object)

$.extend(Object target, Object prop1, Object propN) returns Object
Extend one object with one or more others, returning the original, modified, object. This is a great utility for simple inheritance.

Example:

Merge settings and options, modifying settings
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" }

Saturday, October 1, 2011

css(String key, String|Number value)

css(String key, String|Number value) returns jQuery
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.

Example:

Changes the color of all paragraphs to red
$("p").css("color","red");

HTML:
<p>Test Paragraph.</p>

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

css(Map)

css(Map properties) returns jQuery
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.

Example:

Sets color and background styles to all p elements.
$("p").css({ color: "red", background: "blue" });

HTML:
<p>Test Paragraph.</p>

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

css(String)

css(String name) returns String

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.

Example:

Retrieves the color style of the first paragraph
$("p").css("color");

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

Result:
"red"

Friday, September 30, 2011

empty()

empty() returns jQuery

Removes all child nodes from the set of matched elements.

Example:

$("p").empty()

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

Result:
[ <p></p> ]

remove(String)

remove(String expr) returns jQuery
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.

Example:


$("p").remove();

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

Result:
how are

prependTo(<Content>)

prependTo(<Content> content) returns jQuery
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.

Example:

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

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

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

appendTo(<Content>)

appendTo(<Content> content) returns jQuery
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.

Example:


Appends all paragraphs to the element with the ID "foo"
$("p").appendTo("#foo");

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

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

prepend(<Content>)

prepend(<Content> content) returns jQuery

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.

Example:


Prepends some HTML to all paragraphs.
$("p").prepend("<b>Hello</b>");

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

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

append(<Content>)

append(<Content> content) returns jQuery

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.

Example:


Appends some HTML to all paragraphs.
$("p").append("<b>Hello</b>");

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

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

wrap(Element)

wrap(Element elem) returns jQuery

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.

Example:


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

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

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

wrap(String)

wrap(String html) returns jQuery
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.

Example:

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

HTML:
<p>Test Paragraph.</p>

Result:
<div class='wrap'><p>Test Paragraph.</p></div>

Thursday, September 29, 2011

toggleClass(String)

toggleClass(String class) returns jQuery

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

Example:


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

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

Result:
[ <p class="selected">Hello</p>, <p>Hello Again</p> ]

removeClass(String)

removeClass(String class) returns jQuery
Removes all or the specified class(es) from the set of matched elements.

Example:

<div class="codeview">
$(&quot;p&quot;).removeClass()

HTML:
&lt;p class=&quot;selected&quot;&gt;Hello&lt;/p&gt;

Result:
[ &lt;p&gt;Hello&lt;/p&gt; ]
</div>

addClass(String)

addClass(String class) returns jQuery
Adds the specified class(es) to each of the set of matched elements.

Example:

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

HTML:
<p>Hello</p>

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

removeAttr(String)

removeAttr(String name) returns jQuery
Remove an attribute from each of the matched elements.

Example:

$("input").removeAttr("disabled")
HTML:
<input disabled="disabled"/>
Result:
<input/>

html(String)

html(String val) returns jQuery

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

Example:

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

html()

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

Example:

$("div").html();
HTML:
<div><input/></div>
Result:
<input/>

val(String)

val(String val) returns jQuery
Set the value attribute of every matched element.

Example:

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

val()

val() returns String
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.

Example:


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

attr(String,Function)

attr(String key, Function value) returns jQuery
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.

Example:

Sets title attribute from src attribute.

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

attr(String,Object)

attr(String key, Object value) returns jQuery
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.

Example:

Sets src attribute to all images.
$("img").attr("src","test.jpg");
HTML:
<img/>
Result:
<img src="test.jpg"/>

attr(Map)

attr(Map properties) returns jQuery
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.

Example:

Sets src and alt attributes to all images.
$("img").attr({ src: "test.jpg", alt: "Test Image" });
HTML:

Result:
Test Image

attr(String)

attr(String name) returns Object

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.


Example:

Returns the src attribute from the first image in the document.
$("img").attr("src");
HTML:
<img src="test.jpg"/>
Result:
test.jpg

eq(Number)

eq(Number pos) returns jQuery
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.
Example:

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

$.noConflict()

$.noConflict() returns undefined
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").
Example:

Maps the original object that was referenced by $ back to $
jQuery.noConflict();
// Do something with jQuery
jQuery("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';

$.extend(Object)

$.extend(Object prop) returns Object
Extends the jQuery object itself. Can be used to add functions into the jQuery namespace and to [[Plugins/Authoring|add plugin methods]] (plugins).
Example:
Adds two plugin methods.

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

Wednesday, September 28, 2011

index(Element)

index(Element subject) returns Number
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.
Example:
Returns the index for the element with ID foobar
$("*").index( $('#foobar')[0] )

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

Result:
0

each(Function)

each(Function fn) returns jQuery
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).
Example:
Iterates over two images and sets their src property
$("img").each(function(i){
this.src = "test" + i + ".jpg";
});

HTML:
<img/><img/>

Result:
<img src="test0.jpg"/><img src="test1.jpg"/>

get(Number)

get(Number num) returns Element
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.
Example:
Selects all images in the document and returns the first one
$("img").get(0);

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

Result:
<img src="test1.jpg"/>

length()

length() returns Number
The number of elements currently matched. The size function will return the same value.
Example:
$("img").length;

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

Result:
2

$(Function)

$(Function fn) returns jQuery
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.

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

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

$(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(function($) {
// Your code using failsafe $ alias here...
});

$(String)

$(String html) returns jQuery

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

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.

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

$(String,Element|jQuery)

$(String expr, Element|jQuery context) returns jQuery

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

Example:
Finds all p elements that are children of a div element.
$("div > p")

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

Result:
<pre>[ <p>two</p> ]</pre>