JQuery API – jQuery API

jQuery: Write Less, Do More.

jQuery API

  • jQuery .ajaxComplete( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

    Register a handler to be called when Ajax requests complete. This is an .

  • jQuery .ajaxSuccess( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

    Attach a function to be executed whenever an Ajax request completes successfully. This is an .

  • jQuery .ajaxStop( [ Function ] handler() )

    New in 1.0 !

    Register a handler to be called when all Ajax requests have completed. This is an .

  • jQuery .ajaxStart( [ Function ] handler() )

    New in 1.0 !

    Register a handler to be called when the first Ajax request begins. This is an .

  • jQuery .ajaxSend( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

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

  • jQuery .ajaxError( [ Function ] handler(event, jqXHR, ajaxSettings, thrownError) )

    New in 1.0 !

    Register a handler to be called when Ajax requests complete with an error. This is an .

  • Array .serializeArray( )

    New in 1.2 !

    Encode a set of form elements as an array of names and values.

  • String .serialize( )

    New in 1.0 !

    Encode a set of form elements as a string for submission.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

  • undefined jQuery.ajaxPrefilter( [ String ] dataTypes, [ Function ] handler(options, originalOptions, jqXHR) )

    New in 1.5 !

    Handle custom Ajax options or modify existing options before each request is sent and before they are processed by .

  • jQuery.ajaxSetup( [ Options ] options )

    New in 1.1 !

    Set default values for future Ajax requests.

  • jqXHR jQuery.ajax( [ Map ] settings )

    New in 1.0 !

    Perform an asynchronous HTTP (Ajax) request.

  • jqXHR jQuery.post( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP POST request.

  • XMLHttpRequest jQuery.getScript( [ String ] url, [ Function ] success(data, textStatus) )

    New in 1.0 !

    Load a JavaScript file from the server using a GET HTTP request, then execute it.

  • jqXHR jQuery.getJSON( [ String ] url, [ Map ] data, [ Function ] success(data, textStatus, jqXHR) )

    New in 1.0 !

    Load JSON-encoded data from the server using a GET HTTP request.

  • jqXHR jQuery.get( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP GET request.

  • jQuery .load( [ String ] url, [ Map | String ] data, [ Function ] complete(responseText, textStatus, XMLHttpRequest) )

    New in 1.0 !

    Load data from the server and place the returned HTML into the matched element.

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.

  • jQuery .html( [ Function ] function(index, oldhtml) )

    New in 1.4 !

    Set the HTML contents of each element in the set of matched elements.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • Boolean .hasClass( [ String ] className )

    New in 1.2 !

    Determine whether any of the matched elements are assigned the given class.

  • jQuery .removeAttr( [ String ] attributeName )

    New in 1.0 !

    Remove an attribute from each element in the set of matched elements.

  • jQuery .attr( [ String ] attributeName, [ Function ] function(index, attr) )

    New in 1.1 !

    Set one or more attributes for the set of matched elements.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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

  • Promise jQuery.when( [ Deferred ] deferreds )

    New in 1.5 !

    Provides a way to execute callback functions based on one or more objects, usually objects that represent asynchronous events.

  • jQuery jQuery.sub( )

    New in 1.5 !

    Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.

  • Object jQuery.noConflict( [ Boolean ] removeAll )

    New in 1.0 !

    Relinquish jQuery's control of the variable.

  • jQuery jQuery( [ Function ] callback )

    New in 1.0 !

    Binds a function to be executed when the DOM has finished loading.

  • Object jQuery.cssHooks

    New in 1.4.3 !

    Provides a way to hook directly into jQuery to override how particular CSS properties are retrieved or set. Amongst other uses, cssHooks can be used to create custom, browser-normalized properties for CSS3 features such as box-shadows and gradients.

  • Integer .outerWidth( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding and border.

  • Integer .outerHeight( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.

  • Integer .innerWidth( )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding but not border.

  • Integer .innerHeight( )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding but not border.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.

  • jQuery .scrollLeft( [ Number ] value )

    New in 1.2.6 !

    Set the current horizontal position of the scroll bar for each of the set of matched elements.

  • jQuery .scrollTop( [ Number ] value )

    New in 1.2.6 !

    Set the current vertical position of the scroll bar for each of the set of matched elements.

  • Object .position( )

    New in 1.2 !

    Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.

  • jQuery .css( [ Map ] map )

    New in 1.0 !

    Set one or more CSS properties for the set of matched elements.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • Boolean .hasClass( [ String ] className )

    New in 1.2 !

    Determine whether any of the matched elements are assigned the given class.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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

  • Boolean jQuery.hasData( [ Element ] element )

    New in 1.5 !

    Determine whether an element has any jQuery data associated with it.

  • jQuery jQuery.removeData( [ Element ] element, [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery jQuery.dequeue( [ Element ] element, [ String ] queueName )

    New in 1.3 !

    Execute the next function on the queue for the matched element.

  • jQuery jQuery.queue( [ Element ] element, [ String ] queueName, [ Function ] callback() )

    New in 1.3 !

    Manipulate the queue of functions to be executed on the matched element.

  • jQuery .clearQueue( [ String ] queueName )

    New in 1.4 !

    Remove from the queue all items that have not yet been run.

  • jQuery .removeData( [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • jQuery .dequeue( [ String ] queueName )

    New in 1.2 !

    Execute the next function on the queue for the matched elements.

  • jQuery .queue( [ String ] queueName, [ Function ] callback( next ) )

    New in 1.2 !

    Manipulate the queue of functions to be executed on the matched elements.

  • Promise .deferred.promise( )

    New in 1.5 !

    Return a Deferred's Promise object.

  • Deferred .deferred.resolveWith( [ Object ] context, [ Array ] args )

    New in 1.5 !

    Resolve a Deferred object and call any doneCallbacks with the given and .

  • Deferred .deferred.rejectWith( [ Object ] context, [ Array ] args )

    New in 1.5 !

    Reject a Deferred object and call any failCallbacks with the given and .

  • Deferred .deferred.fail( [ Function ] failCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is rejected.

  • Deferred .deferred.done( [ Function ] doneCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is resolved.

  • Deferred .deferred.then( [ Function ] doneCallbacks, [ Function ] failCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is resolved or rejected.

  • Deferred .deferred.reject( [ Object ] args )

    New in 1.5 !

    Reject a Deferred object and call any failCallbacks with the given .

  • Boolean .deferred.isRejected( )

    New in 1.5 !

    Determine whether a Deferred object has been rejected.

  • Boolean .deferred.isResolved( )

    New in 1.5 !

    Determine whether a Deferred object has been resolved.

  • Deferred .deferred.resolve( [ Object ] args )

    New in 1.5 !

    Resolve a Deferred object and call any doneCallbacks with the given .

  • Integer .outerWidth( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding and border.

  • Integer .outerHeight( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.

  • Integer .innerWidth( )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding but not border.

  • Integer .innerHeight( )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding but not border.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.

  • jQuery .toggle( [ Boolean ] showOrHide )

    New in 1.3 !

    Display or hide the matched elements.

  • jQuery .hide( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements.

  • jQuery .show( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements.

  • Number jQuery.fx.interval

    New in 1.4.3 !

    The rate (in milliseconds) at which animations fire.

  • jQuery .delay( [ Integer ] duration, [ String ] queueName )

    New in 1.4 !

    Set a timer to delay execution of subsequent items in the queue.

  • Boolean jQuery.fx.off

    New in 1.3 !

    Globally disable all animations.

  • jQuery .clearQueue( [ String ] queueName )

    New in 1.4 !

    Remove from the queue all items that have not yet been run.

  • jQuery .dequeue( [ String ] queueName )

    New in 1.2 !

    Execute the next function on the queue for the matched elements.

  • jQuery .queue( [ String ] queueName, [ Function ] callback( next ) )

    New in 1.2 !

    Manipulate the queue of functions to be executed on the matched elements.

  • jQuery .stop( [ Boolean ] clearQueue, [ Boolean ] jumpToEnd )

    New in 1.2 !

    Stop the currently-running animation on the matched elements.

  • jQuery .animate( [ Map ] properties, [ Map ] options )

    New in 1.0 !

    Perform a custom animation of a set of CSS properties.

  • jQuery .fadeToggle( [ String,Number ] duration, [ String ] easing, [ Function ] callback )

    New in 1.4.4 !

    Display or hide the matched elements by animating their opacity.

  • jQuery .fadeTo( [ String,Number ] duration, [ Number ] opacity, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Adjust the opacity of the matched elements.

  • jQuery .fadeOut( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements by fading them to transparent.

  • jQuery .fadeIn( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements by fading them to opaque.

  • jQuery .slideToggle( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display or hide the matched elements with a sliding motion.

  • jQuery .slideUp( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements with a sliding motion.

  • jQuery .slideDown( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements with a sliding motion.

  • jQuery .fadeToggle( [ String,Number ] duration, [ String ] easing, [ Function ] callback )

    New in 1.4.4 !

    Display or hide the matched elements by animating their opacity.

  • jQuery .scroll( )

    New in 1.0 !

    Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.

  • jQuery .resize( )

    New in 1.0 !

    Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.

  • jQuery .error( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "error" JavaScript event.

  • jQuery .unload( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "unload" JavaScript event.

  • jQuery .load( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "load" JavaScript event.

  • jQuery .ready( [ Function ] handler )

    New in 1.0 !

    Specify a function to execute when the DOM is fully loaded.

  • jQuery .undelegate( [ String ] namespace )

    New in 1.6 !

    Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.

  • jQuery .delegate( [ String ] selector, [ Map ] events )

    New in 1.4.3 !

    Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

  • Function jQuery.proxy( [ Object ] context, [ String ] name )

    New in 1.4 !

    Takes a function and returns a new one that will always have a particular context.

  • jQuery .die( [ Map ] eventTypes )

    New in 1.4.3 !

    Remove an event handler previously attached using from the elements.

  • jQuery .live( [ Object ] events )

    New in 1.4.3 !

    Attach a handler to the event for all elements which match the current selector, now and in the future.

  • Object .triggerHandler( [ String ] eventType, [ Array ] extraParameters )

    New in 1.2 !

    Execute all handlers attached to an element for an event.

  • jQuery .trigger( [ Event ] event )

    New in 1.3 !

    Execute all handlers and behaviors attached to the matched elements for the given event type.

  • jQuery .one( [ String ] eventType, [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.1 !

    Attach a handler to an event for the elements. The handler is executed at most once per element.

  • jQuery .unbind( [ Object ] event )

    New in 1.0 !

    Remove a previously-attached event handler from the elements.

  • jQuery .bind( [ Object ] events )

    New in 1.4 !

    Attach a handler to an event for the elements.

  • String event.namespace

    New in 1.4.3 !

    The namespace specified when the event was triggered.

  • Boolean event.isImmediatePropagationStopped( )

    New in 1.3 !

    Returns whether event.stopImmediatePropagation() was ever called on this event object.

  • event.stopImmediatePropagation( )

    New in 1.3 !

    Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.

  • Boolean event.isPropagationStopped( )

    New in 1.3 !

    Returns whether was ever called on this event object.

  • event.stopPropagation( )

    New in 1.0 !

    Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

  • Boolean event.isDefaultPrevented( )

    New in 1.3 !

    Returns whether was ever called on this event object.

  • undefined event.preventDefault( )

    New in 1.0 !

    If this method is called, the default action of the event will not be triggered.

  • Number event.timeStamp

    New in 1.2.6 !

    The difference in milliseconds between the time an event is triggered and January 1, 1970.

  • Object event.result

    New in 1.3 !

    The last value returned by an event handler that was triggered by this event, unless the value was .

  • Number event.which

    New in 1.1.3 !

    For key or button events, this attribute indicates the specific button or key that was pressed.

  • Number event.pageY

    New in 1.0.4 !

    The mouse position relative to the top edge of the document.

  • Number event.pageX

    New in 1.0.4 !

    The mouse position relative to the left edge of the document.

  • Element event.currentTarget

    New in 1.3 !

    The current DOM element within the event bubbling phase.

  • Element event.relatedTarget

    New in 1.1.4 !

    The other DOM element involved in the event, if any.

  • Anything event.data

    New in 1.1 !

    The optional data passed to jQuery.fn.bind when the current executing handler was bound.

  • Element event.target

    New in 1.0 !

    The DOM element that initiated the event.

  • String event.type

    New in 1.0 !

    Describes the nature of the event.

  • jQuery .submit( )

    New in 1.0 !

    Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

  • jQuery .select( )

    New in 1.0 !

    Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

  • jQuery .change( )

    New in 1.0 !

    Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

  • jQuery .blur( )

    New in 1.0 !

    Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.

  • jQuery .focus( )

    New in 1.0 !

    Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.

  • jQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusout" JavaScript event.

  • jQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusin" JavaScript event.

  • jQuery .keydown( )

    New in 1.0 !

    Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.

  • jQuery .keyup( )

    New in 1.0 !

    Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.

  • jQuery .keypress( )

    New in 1.0 !

    Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.

  • jQuery .toggle( [ Function ] handler(eventObject), [ Function ] handler(eventObject), [ Function ] handler(eventObject) )

    New in 1.0 !

    Bind two or more handlers to the matched elements, to be executed on alternate clicks.

  • jQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusout" JavaScript event.

  • jQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusin" JavaScript event.

  • jQuery .mousemove( )

    New in 1.0 !

    Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.

  • jQuery .hover( [ Function ] handlerInOut(eventObject) )

    New in 1.4 !

    Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.

  • jQuery .mouseleave( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.

  • jQuery .mouseenter( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

  • jQuery .mouseout( )

    New in 1.0 !

    Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.

  • jQuery .mouseover( )

    New in 1.0 !

    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • jQuery .dblclick( )

    New in 1.0 !

    Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.

  • jQuery .click( )

    New in 1.0 !

    Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

  • jQuery .mouseup( )

    New in 1.0 !

    Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.

  • jQuery .mousedown( )

    New in 1.0 !

    Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.

  • jQuery .submit( )

    New in 1.0 !

    Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

  • jQuery .select( )

    New in 1.0 !

    Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

  • jQuery .change( )

    New in 1.0 !

    Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

  • jQuery .blur( )

    New in 1.0 !

    Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.

  • jQuery .focus( )

    New in 1.0 !

    Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.

  • Array .serializeArray( )

    New in 1.2 !

    Encode a set of form elements as an array of names and values.

  • String .serialize( )

    New in 1.0 !

    Encode a set of form elements as a string for submission.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • Boolean .hasClass( [ String ] className )

    New in 1.2 !

    Determine whether any of the matched elements are assigned the given class.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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

  • jQuery .clone( [ Boolean ] withDataAndEvents, [ Boolean ] deepWithDataAndEvents )

    New in 1.5 !

    Create a deep copy of the set of matched elements.

  • jQuery .unwrap( )

    New in 1.4 !

    Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

  • jQuery .wrapInner( [ Function ] wrappingFunction )

    New in 1.4 !

    Wrap an HTML structure around the content of each element in the set of matched elements.

  • jQuery .wrapAll( [ String | Selector | Element | jQuery ] wrappingElement )

    New in 1.2 !

    Wrap an HTML structure around all elements in the set of matched elements.

  • jQuery .wrap( [ Function ] function(index) )

    New in 1.4 !

    Wrap an HTML structure around each element in the set of matched elements.

  • jQuery .prependTo( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements to the beginning of the target.

  • jQuery .prepend( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

  • jQuery .appendTo( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements to the end of the target.

  • jQuery .append( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the end of each element in the set of matched elements.

  • jQuery .text( [ Function ] function(index, text) )

    New in 1.4 !

    Set the content of each element in the set of matched elements to the specified text.

  • jQuery .html( [ Function ] function(index, oldhtml) )

    New in 1.4 !

    Set the HTML contents of each element in the set of matched elements.

  • jQuery .insertBefore( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements before the target.

  • jQuery .before( [ Function ] function )

    New in 1.4 !

    Insert content, specified by the parameter, before each element in the set of matched elements.

  • jQuery .insertAfter( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements after the target.

  • jQuery .after( [ Function ] function(index) )

    New in 1.4 !

    Insert content, specified by the parameter, after each element in the set of matched elements.

  • jQuery .unwrap( )

    New in 1.4 !

    Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

  • jQuery .detach( [ Selector ] selector )

    New in 1.4 !

    Remove the set of matched elements from the DOM.

  • jQuery .remove( [ String ] selector )

    New in 1.0 !

    Remove the set of matched elements from the DOM.

  • jQuery .empty( )

    New in 1.0 !

    Remove all child nodes of the set of matched elements from the DOM.

  • jQuery .replaceAll( [ Selector ] target )

    New in 1.2 !

    Replace each target element with the set of matched elements.

  • jQuery .replaceWith( [ Function ] function )

    New in 1.4 !

    Replace each element in the set of matched elements with the provided new content.

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.

  • jQuery .removeAttr( [ String ] attributeName )

    New in 1.0 !

    Remove an attribute from each element in the set of matched elements.

  • jQuery .attr( [ String ] attributeName, [ Function ] function(index, attr) )

    New in 1.1 !

    Set one or more attributes for the set of matched elements.

  • Integer .outerWidth( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding and border.

  • Integer .outerHeight( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.

  • Integer .innerWidth( )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding but not border.

  • Integer .innerHeight( )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding but not border.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.

  • jQuery .scrollLeft( [ Number ] value )

    New in 1.2.6 !

    Set the current horizontal position of the scroll bar for each of the set of matched elements.

  • jQuery .scrollTop( [ Number ] value )

    New in 1.2.6 !

    Set the current vertical position of the scroll bar for each of the set of matched elements.

  • Object .position( )

    New in 1.2 !

    Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.

  • jQuery .css( [ Map ] map )

    New in 1.0 !

    Set one or more CSS properties for the set of matched elements.

  • jQuery .each( [ Function ] function(index, Element) )

    New in 1.0 !

    Iterate over a jQuery object, executing a function for each matched element.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

  • jQuery .removeData( [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • Array .toArray( )

    New in 1.4 !

    Retrieve all the DOM elements contained in the jQuery set, as an array.

  • Number .index( [ Element | jQuery ] element )

    New in 1.0 !

    Search for a given element from among the matched elements.

  • Element, Array .get( [ Number ] index )

    New in 1.0 !

    Retrieve the DOM elements matched by the jQuery object.

  • Number .size( )

    New in 1.0 !

    Return the number of elements in the jQuery object.

  • Object jQuery.noConflict( [ Boolean ] removeAll )

    New in 1.0 !

    Relinquish jQuery's control of the variable.

  • jQuery .offsetParent( )

    New in 1.2.6 !

    Get the closest ancestor element that is positioned.

  • jQuery .scrollLeft( [ Number ] value )

    New in 1.2.6 !

    Set the current horizontal position of the scroll bar for each of the set of matched elements.

  • jQuery .scrollTop( [ Number ] value )

    New in 1.2.6 !

    Set the current vertical position of the scroll bar for each of the set of matched elements.

  • Object .position( )

    New in 1.2 !

    Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.

  • String jquery

    New in 1.0 !

    A string containing the jQuery version number.

  • Number length

    New in 1.0 !

    The number of elements in the jQuery object.

  • String selector

    New in 1.3 !

    A selector representing selector originally passed to jQuery().

  • Element context

    New in 1.3 !

    The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document.

  • Number jQuery.fx.interval

    New in 1.4.3 !

    The rate (in milliseconds) at which animations fire.

  • Boolean jQuery.fx.off

    New in 1.3 !

    Globally disable all animations.

  • Map jQuery.browser

    New in 1.0 !

    Contains flags for the useragent, read from navigator.userAgent.

  • String jQuery.browser.version

    New in 1.1.3 !

    The version number of the rendering engine for the user's browser.

  • Object jQuery.support

    New in 1.3 !

    A collection of properties that represent the presence of different browser features or bugs.

  • JQuery("[attribute|="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).

  • JQuery("[attribute~="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

  • JQuery("[attributeFilter1][attributeFilter2][attributeFilterN]")

    New in 1.0 !

    Matches elements that match all of the specified attribute filters.

  • JQuery("[attribute*="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value containing the a given substring.

  • JQuery("[attribute$="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.

  • JQuery("[attribute^="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value beginning exactly with a given string.

  • JQuery("[attribute!="value"]")

    New in 1.0 !

    Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.

  • JQuery("[attribute="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value exactly equal to a certain value.

  • JQuery("[attribute]")

    New in 1.0 !

    Selects elements that have the specified attribute, with any value.

  • JQuery("selector1, selector2, selectorN")

    New in 1.0 !

    Selects the combined results of all the specified selectors.

  • JQuery("*")

    New in 1.0 !

    Selects all elements.

  • JQuery(".class")

    New in 1.0 !

    Selects all elements with the given class.

  • JQuery("element")

    New in 1.0 !

    Selects all elements with the given tag name.

  • JQuery("#id")

    New in 1.0 !

    Selects a single element with the given id attribute.

  • JQuery(":animated")

    New in 1.2 !

    Select all elements that are in the progress of an animation at the time the selector is run.

  • JQuery(":header")

    New in 1.2 !

    Selects all elements that are headers, like h1, h2, h3 and so on.

  • JQuery(":lt(index)")

    New in 1.0 !

    Select all elements at an index less than within the matched set.

  • JQuery(":gt(index)")

    New in 1.0 !

    Select all elements at an index greater than within the matched set.

  • JQuery(":eq(index)")

    New in 1.0 !

    Select the element at index within the matched set.

  • JQuery(":odd")

    New in 1.0 !

    Selects odd elements, zero-indexed. See also .

  • JQuery(":even")

    New in 1.0 !

    Selects even elements, zero-indexed. See also .

  • JQuery(":not(selector)")

    New in 1.0 !

    Selects all elements that do not match the given selector.

  • JQuery(":last")

    New in 1.0 !

    Selects the last matched element.

  • JQuery(":first")

    New in 1.0 !

    Selects the first matched element.

  • JQuery(":only-child")

    New in 1.1.4 !

    Selects all elements that are the only child of their parent.

  • JQuery(":last-child")

    New in 1.1.4 !

    Selects all elements that are the last child of their parent.

  • JQuery(":first-child")

    New in 1.1.4 !

    Selects all elements that are the first child of their parent.

  • JQuery(":nth-child(index/even/odd/equation)")

    New in 1.1.4 !

    Selects all elements that are the nth-child of their parent.

  • JQuery(":parent")

    New in 1.0 !

    Select all elements that are the parent of another element, including text nodes.

  • JQuery(":has(selector)")

    New in 1.1.4 !

    Selects elements which contain at least one element that matches the specified selector.

  • JQuery(":empty")

    New in 1.0 !

    Select all elements that have no children (including text nodes).

  • JQuery(":contains(text)")

    New in 1.1.4 !

    Select all elements that contain the specified text.

  • JQuery(":selected")

    New in 1.0 !

    Selects all elements that are selected.

  • JQuery(":checked")

    New in 1.0 !

    Matches all elements that are checked.

  • JQuery(":disabled")

    New in 1.0 !

    Selects all elements that are disabled.

  • JQuery(":enabled")

    New in 1.0 !

    Selects all elements that are enabled.

  • JQuery(":file")

    New in 1.0 !

    Selects all elements of type file.

  • JQuery(":button")

    New in 1.0 !

    Selects all button elements and elements of type button.

  • JQuery(":reset")

    New in 1.0 !

    Selects all elements of type reset.

  • JQuery(":image")

    New in 1.0 !

    Selects all elements of type image.

  • JQuery(":submit")

    New in 1.0 !

    Selects all elements of type submit.

  • JQuery(":checkbox")

    New in 1.0 !

    Selects all elements of type checkbox.

  • JQuery(":radio")

    New in 1.0 !

    Selects all elements of type radio.

  • JQuery(":password")

    New in 1.0 !

    Selects all elements of type password.

  • JQuery(":text")

    New in 1.0 !

    Selects all elements of type text.

  • JQuery(":input")

    New in 1.0 !

    Selects all input, textarea, select and button elements.

  • JQuery("prev ~ siblings")

    New in 1.0 !

    Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.

  • JQuery("prev + next")

    New in 1.0 !

    Selects all next elements matching "next" that are immediately preceded by a sibling "prev".

  • child")" rel="bookmark">JQuery("parent > child")

    New in 1.0 !

    Selects all direct child elements specified by "child" of elements specified by "parent".

  • JQuery("ancestor descendant")

    New in 1.0 !

    Selects all elements that are descendants of a given ancestor.

  • JQuery(":visible")

    New in 1.0 !

    Selects all elements that are visible.

  • JQuery(":hidden")

    New in 1.0 !

    Selects all elements that are hidden.

  • jQuery .has( [ Element ] contained )

    New in 1.4 !

    Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

  • jQuery .first( )

    New in 1.4 !

    Reduce the set of matched elements to the first in the set.

  • jQuery .last( )

    New in 1.4 !

    Reduce the set of matched elements to the final one in the set.

  • jQuery .slice( [ Integer ] start, [ Integer ] end )

    New in 1.1.4 !

    Reduce the set of matched elements to a subset specified by a range of indices.

  • jQuery .not( [ Function ] function(index) )

    New in 1.4 !

    Remove elements from the set of matched elements.

  • jQuery .map( [ Function ] callback(index, domElement) )

    New in 1.2 !

    Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

  • Boolean .is( [ Selector ] selector )

    New in 1.0 !

    Check the current matched set of elements against a selector and return true if at least one of these elements matches the selector.

  • jQuery .eq( [ Integer ] -index )

    New in 1.4 !

    Reduce the set of matched elements to the one at the specified index.

  • jQuery .filter( [ Object ] jQuery object )

    New in 1.4 !

    Reduce the set of matched elements to those that match the selector or pass the function's test.

  • jQuery .end( )

    New in 1.0 !

    End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.

  • jQuery .andSelf( )

    New in 1.2 !

    Add the previous set of elements on the stack to the current set.

  • jQuery .contents( )

    New in 1.2 !

    Get the children of each element in the set of matched elements, including text and comment nodes.

  • jQuery .add( [ Selector ] selector, [ Element ] context )

    New in 1.4 !

    Add elements to the set of matched elements.

  • jQuery .parentsUntil( [ Selector ] selector )

    New in 1.4 !

    Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.

  • jQuery .prevUntil( [ Selector ] selector )

    New in 1.4 !

    Get all preceding siblings of each element up to but not including the element matched by the selector.

  • jQuery .nextUntil( [ Selector ] selector )

    New in 1.4 !

    Get all following siblings of each element up to but not including the element matched by the selector.

  • jQuery .siblings( [ Selector ] selector )

    New in 1.0 !

    Get the siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .prevAll( [ Selector ] selector )

    New in 1.2 !

    Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .prev( [ Selector ] selector )

    New in 1.0 !

    Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .parents( [ Selector ] selector )

    New in 1.0 !

    Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

  • jQuery .parent( [ Selector ] selector )

    New in 1.0 !

    Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

  • jQuery .offsetParent( )

    New in 1.2.6 !

    Get the closest ancestor element that is positioned.

  • jQuery .nextAll( [ String ] selector )

    New in 1.2 !

    Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .next( [ Selector ] selector )

    New in 1.0 !

    Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

  • jQuery .find( [ Selector ] selector )

    New in 1.0 !

    Get the descendants of each element in the current set of matched elements, filtered by a selector.

  • Array .closest( [ Array ] selectors, [ Element ] context )

    New in 1.4 !

    Gets an array of all the elements and selectors matched against the current element up through the DOM tree.

  • jQuery .children( [ Selector ] selector )

    New in 1.0 !

    Get the children of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .each( [ Function ] function(index, Element) )

    New in 1.0 !

    Iterate over a jQuery object, executing a function for each matched element.

  • Number jQuery.now( )

    New in 1.4.3 !

    Return a number representing the current time.

  • XMLDocument jQuery.parseXML( [ String ] data )

    New in 1.5 !

    Parses a string into an XML document.

  • String jQuery.type( [ Object ] obj )

    New in 1.4.3 !

    Determine the internal JavaScript [[Class]] of an object.

  • boolean jQuery.isWindow( [ Object ] obj )

    New in 1.4.3 !

    Determine whether the argument is a window.

  • Object jQuery.parseJSON( [ String ] json )

    New in 1.4.1 !

    Takes a well-formed JSON string and returns the resulting JavaScript object.

  • Function jQuery.proxy( [ Object ] context, [ String ] name )

    New in 1.4 !

    Takes a function and returns a new one that will always have a particular context.

  • Boolean jQuery.contains( [ Element ] container, [ Element ] contained )

    New in 1.4 !

    Check to see if a DOM node is within another DOM node.

  • Function jQuery.noop( )

    New in 1.4 !

    An empty function.

  • jQuery.globalEval( [ String ] code )

    New in 1.0.4 !

    Execute some JavaScript code globally.

  • Boolean jQuery.isXMLDoc( [ Element ] node )

    New in 1.1.4 !

    Check to see if a DOM node is within an XML document (or is an XML document).

  • jQuery jQuery.removeData( [ Element ] element, [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery jQuery.dequeue( [ Element ] element, [ String ] queueName )

    New in 1.3 !

    Execute the next function on the queue for the matched element.

  • jQuery jQuery.queue( [ Element ] element, [ String ] queueName, [ Function ] callback() )

    New in 1.3 !

    Manipulate the queue of functions to be executed on the matched element.

  • jQuery .clearQueue( [ String ] queueName )

    New in 1.4 !

    Remove from the queue all items that have not yet been run.

  • Boolean jQuery.isEmptyObject( [ Object ] object )

    New in 1.4 !

    Check to see if an object is empty (contains no properties).

  • Boolean jQuery.isPlainObject( [ Object ] object )

    New in 1.4 !

    Check to see if an object is a plain object (created using "{}" or "new Object").

  • jQuery .dequeue( [ String ] queueName )

    New in 1.2 !

    Execute the next function on the queue for the matched elements.

  • jQuery .queue( [ String ] queueName, [ Function ] callback( next ) )

    New in 1.2 !

    Manipulate the queue of functions to be executed on the matched elements.

  • Map jQuery.browser

    New in 1.0 !

    Contains flags for the useragent, read from navigator.userAgent.

  • String jQuery.browser.version

    New in 1.1.3 !

    The version number of the rendering engine for the user's browser.

  • String jQuery.trim( [ String ] str )

    New in 1.0 !

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

  • boolean jQuery.isFunction( [ Object ] obj )

    New in 1.2 !

    Determine if the argument passed is a Javascript function object.

  • boolean jQuery.isArray( [ Object ] obj )

    New in 1.3 !

    Determine whether the argument is an array.

  • Array jQuery.unique( [ Array ] array )

    New in 1.1.3 !

    Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.

  • Array jQuery.merge( [ Array ] first, [ Array ] second )

    New in 1.0 !

    Merge the contents of two arrays together into the first array.

  • Number jQuery.inArray( [ Any ] value, [ Array ] array )

    New in 1.2 !

    Search for a specified value within an array and return its index (or -1 if not found).

  • Array jQuery.map( [ Array ] array, [ Function ] callback(elementOfArray, indexInArray) )

    New in 1.0 !

    Translate all items in an array or array-like object to another array of items.

  • Array jQuery.makeArray( [ Object ] obj )

    New in 1.2 !

    Convert an array-like object into a true JavaScript array.

  • Array jQuery.grep( [ Array ] array, [ Function ] function(elementOfArray, indexInArray), [ Boolean ] invert )

    New in 1.0 !

    Finds the elements of an array which satisfy a filter function. The original array is not affected.

  • Object jQuery.extend( [ Boolean ] deep, [ Object ] target, [ Object ] object1, [ Object ] objectN )

    New in 1.1.4 !

    Merge the contents of two or more objects together into the first object.

  • Object jQuery.each( [ Object ] collection, [ Function ] callback(indexInArray, valueOfElement) )

    New in 1.0 !

    A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

  • Boolean jQuery.boxModel

    New in 1.0 !

    . States if the current page, in the user's browser, is being rendered using the .

  • Object jQuery.support

    New in 1.3 !

    A collection of properties that represent the presence of different browser features or bugs.

  • jQuery .toggle( [ Boolean ] showOrHide )

    New in 1.3 !

    Display or hide the matched elements.

  • event.stopPropagation( )

    New in 1.0 !

    Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

  • undefined event.preventDefault( )

    New in 1.0 !

    If this method is called, the default action of the event will not be triggered.

  • Element event.target

    New in 1.0 !

    The DOM element that initiated the event.

  • String event.type

    New in 1.0 !

    Describes the nature of the event.

  • jQuery .each( [ Function ] function(index, Element) )

    New in 1.0 !

    Iterate over a jQuery object, executing a function for each matched element.

  • jQuery .pushStack( [ Array ] elements, [ String ] name, [ Array ] arguments )

    New in 1.3 !

    Add a collection of DOM elements onto the jQuery stack.

  • jQuery .keydown( )

    New in 1.0 !

    Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.

  • Number .index( [ Element | jQuery ] element )

    New in 1.0 !

    Search for a given element from among the matched elements.

  • Element, Array .get( [ Number ] index )

    New in 1.0 !

    Retrieve the DOM elements matched by the jQuery object.

  • Number .size( )

    New in 1.0 !

    Return the number of elements in the jQuery object.

  • Object jQuery.noConflict( [ Boolean ] removeAll )

    New in 1.0 !

    Relinquish jQuery's control of the variable.

  • JQuery(":selected")

    New in 1.0 !

    Selects all elements that are selected.

  • JQuery(":checked")

    New in 1.0 !

    Matches all elements that are checked.

  • JQuery(":disabled")

    New in 1.0 !

    Selects all elements that are disabled.

  • JQuery(":enabled")

    New in 1.0 !

    Selects all elements that are enabled.

  • JQuery(":file")

    New in 1.0 !

    Selects all elements of type file.

  • JQuery(":button")

    New in 1.0 !

    Selects all button elements and elements of type button.

  • JQuery(":reset")

    New in 1.0 !

    Selects all elements of type reset.

  • JQuery(":image")

    New in 1.0 !

    Selects all elements of type image.

  • jQuery .submit( )

    New in 1.0 !

    Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

  • JQuery(":checkbox")

    New in 1.0 !

    Selects all elements of type checkbox.

  • JQuery(":radio")

    New in 1.0 !

    Selects all elements of type radio.

  • JQuery(":password")

    New in 1.0 !

    Selects all elements of type password.

  • jQuery .text( [ Function ] function(index, text) )

    New in 1.4 !

    Set the content of each element in the set of matched elements to the specified text.

  • JQuery(":input")

    New in 1.0 !

    Selects all input, textarea, select and button elements.

  • JQuery("[attribute|="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).

  • JQuery("[attribute~="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

  • JQuery("[attributeFilter1][attributeFilter2][attributeFilterN]")

    New in 1.0 !

    Matches elements that match all of the specified attribute filters.

  • JQuery("[attribute*="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value containing the a given substring.

  • JQuery("[attribute$="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.

  • JQuery("[attribute^="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value beginning exactly with a given string.

  • JQuery("[attribute!="value"]")

    New in 1.0 !

    Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.

  • JQuery("[attribute="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value exactly equal to a certain value.

  • JQuery("[attribute]")

    New in 1.0 !

    Selects elements that have the specified attribute, with any value.

  • JQuery(":visible")

    New in 1.0 !

    Selects all elements that are visible.

  • JQuery(":hidden")

    New in 1.0 !

    Selects all elements that are hidden.

  • jQuery .parent( [ Selector ] selector )

    New in 1.0 !

    Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

  • jQuery .empty( )

    New in 1.0 !

    Remove all child nodes of the set of matched elements from the DOM.

  • JQuery(":lt(index)")

    New in 1.0 !

    Select all elements at an index less than within the matched set.

  • JQuery(":gt(index)")

    New in 1.0 !

    Select all elements at an index greater than within the matched set.

  • JQuery(":eq(index)")

    New in 1.0 !

    Select the element at index within the matched set.

  • JQuery(":odd")

    New in 1.0 !

    Selects odd elements, zero-indexed. See also .

  • JQuery(":even")

    New in 1.0 !

    Selects even elements, zero-indexed. See also .

  • jQuery .not( [ Function ] function(index) )

    New in 1.4 !

    Remove elements from the set of matched elements.

  • JQuery(":last")

    New in 1.0 !

    Selects the last matched element.

  • JQuery(":first")

    New in 1.0 !

    Selects the first matched element.

  • JQuery("prev ~ siblings")

    New in 1.0 !

    Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.

  • JQuery("prev + next")

    New in 1.0 !

    Selects all next elements matching "next" that are immediately preceded by a sibling "prev".

  • child")" rel="bookmark">JQuery("parent > child")

    New in 1.0 !

    Selects all direct child elements specified by "child" of elements specified by "parent".

  • JQuery("ancestor descendant")

    New in 1.0 !

    Selects all elements that are descendants of a given ancestor.

  • JQuery("selector1, selector2, selectorN")

    New in 1.0 !

    Selects the combined results of all the specified selectors.

  • JQuery("*")

    New in 1.0 !

    Selects all elements.

  • JQuery(".class")

    New in 1.0 !

    Selects all elements with the given class.

  • JQuery("element")

    New in 1.0 !

    Selects all elements with the given tag name.

  • JQuery("#id")

    New in 1.0 !

    Selects a single element with the given id attribute.

  • jQuery .scroll( )

    New in 1.0 !

    Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.

  • jQuery .resize( )

    New in 1.0 !

    Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.

  • jQuery .keyup( )

    New in 1.0 !

    Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.

  • jQuery .keypress( )

    New in 1.0 !

    Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.

  • jQuery .select( )

    New in 1.0 !

    Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

  • jQuery .change( )

    New in 1.0 !

    Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

  • jQuery .blur( )

    New in 1.0 !

    Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.

  • jQuery .focus( )

    New in 1.0 !

    Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.

  • jQuery .mousemove( )

    New in 1.0 !

    Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.

  • jQuery .hover( [ Function ] handlerInOut(eventObject) )

    New in 1.4 !

    Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.

  • jQuery .mouseleave( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.

  • jQuery .mouseenter( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

  • jQuery .mouseout( )

    New in 1.0 !

    Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.

  • jQuery .mouseover( )

    New in 1.0 !

    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • jQuery .dblclick( )

    New in 1.0 !

    Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.

  • jQuery .click( )

    New in 1.0 !

    Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

  • jQuery .mouseup( )

    New in 1.0 !

    Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.

  • jQuery .mousedown( )

    New in 1.0 !

    Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.

  • jQuery .error( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "error" JavaScript event.

  • jQuery .unload( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "unload" JavaScript event.

  • jQuery .load( [ String ] url, [ Map | String ] data, [ Function ] complete(responseText, textStatus, XMLHttpRequest) )

    New in 1.0 !

    Load data from the server and place the returned HTML into the matched element.

  • jQuery .ready( [ Function ] handler )

    New in 1.0 !

    Specify a function to execute when the DOM is fully loaded.

  • Map jQuery.browser

    New in 1.0 !

    Contains flags for the useragent, read from navigator.userAgent.

  • String jQuery.browser.version

    New in 1.1.3 !

    The version number of the rendering engine for the user's browser.

  • jQuery .trigger( [ Event ] event )

    New in 1.3 !

    Execute all handlers and behaviors attached to the matched elements for the given event type.

  • jQuery .ajaxComplete( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

    Register a handler to be called when Ajax requests complete. This is an .

  • String .serialize( )

    New in 1.0 !

    Encode a set of form elements as a string for submission.

  • jQuery .ajaxSuccess( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

    Attach a function to be executed whenever an Ajax request completes successfully. This is an .

  • jQuery .ajaxStop( [ Function ] handler() )

    New in 1.0 !

    Register a handler to be called when all Ajax requests have completed. This is an .

  • jQuery .ajaxStart( [ Function ] handler() )

    New in 1.0 !

    Register a handler to be called when the first Ajax request begins. This is an .

  • jQuery .ajaxSend( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

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

  • jQuery .ajaxError( [ Function ] handler(event, jqXHR, ajaxSettings, thrownError) )

    New in 1.0 !

    Register a handler to be called when Ajax requests complete with an error. This is an .

  • jQuery .unbind( [ Object ] event )

    New in 1.0 !

    Remove a previously-attached event handler from the elements.

  • jQuery .bind( [ Object ] events )

    New in 1.4 !

    Attach a handler to an event for the elements.

  • jQuery jQuery( [ Function ] callback )

    New in 1.0 !

    Binds a function to be executed when the DOM has finished loading.

  • jQuery .end( )

    New in 1.0 !

    End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.

  • jQuery .siblings( [ Selector ] selector )

    New in 1.0 !

    Get the siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .animate( [ Map ] properties, [ Map ] options )

    New in 1.0 !

    Perform a custom animation of a set of CSS properties.

  • jQuery .prev( [ Selector ] selector )

    New in 1.0 !

    Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .fadeTo( [ String,Number ] duration, [ Number ] opacity, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Adjust the opacity of the matched elements.

  • jQuery .fadeOut( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements by fading them to transparent.

  • jQuery .parents( [ Selector ] selector )

    New in 1.0 !

    Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

  • jQuery .fadeIn( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements by fading them to opaque.

  • jQuery .slideToggle( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display or hide the matched elements with a sliding motion.

  • jqXHR jQuery.post( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP POST request.

  • jQuery .slideUp( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements with a sliding motion.

  • jQuery .next( [ Selector ] selector )

    New in 1.0 !

    Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

  • jQuery .slideDown( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements with a sliding motion.

  • jQuery .find( [ Selector ] selector )

    New in 1.0 !

    Get the descendants of each element in the current set of matched elements, filtered by a selector.

  • XMLHttpRequest jQuery.getScript( [ String ] url, [ Function ] success(data, textStatus) )

    New in 1.0 !

    Load a JavaScript file from the server using a GET HTTP request, then execute it.

  • jqXHR jQuery.getJSON( [ String ] url, [ Map ] data, [ Function ] success(data, textStatus, jqXHR) )

    New in 1.0 !

    Load JSON-encoded data from the server using a GET HTTP request.

  • jqXHR jQuery.get( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP GET request.

  • jqXHR jQuery.ajax( [ Map ] settings )

    New in 1.0 !

    Perform an asynchronous HTTP (Ajax) request.

  • Number length

    New in 1.0 !

    The number of elements in the jQuery object.

  • jQuery .children( [ Selector ] selector )

    New in 1.0 !

    Get the children of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .add( [ Selector ] selector, [ Element ] context )

    New in 1.4 !

    Add elements to the set of matched elements.

  • jQuery .hide( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.

  • jQuery .show( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements.

  • String jQuery.trim( [ String ] str )

    New in 1.0 !

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

  • Array jQuery.merge( [ Array ] first, [ Array ] second )

    New in 1.0 !

    Merge the contents of two arrays together into the first array.

  • Array jQuery.map( [ Array ] array, [ Function ] callback(elementOfArray, indexInArray) )

    New in 1.0 !

    Translate all items in an array or array-like object to another array of items.

  • Array jQuery.grep( [ Array ] array, [ Function ] function(elementOfArray, indexInArray), [ Boolean ] invert )

    New in 1.0 !

    Finds the elements of an array which satisfy a filter function. The original array is not affected.

  • Object jQuery.extend( [ Boolean ] deep, [ Object ] target, [ Object ] object1, [ Object ] objectN )

    New in 1.1.4 !

    Merge the contents of two or more objects together into the first object.

  • Object jQuery.each( [ Object ] collection, [ Function ] callback(indexInArray, valueOfElement) )

    New in 1.0 !

    A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

  • Boolean jQuery.boxModel

    New in 1.0 !

    . States if the current page, in the user's browser, is being rendered using the .

  • jQuery .css( [ Map ] map )

    New in 1.0 !

    Set one or more CSS properties for the set of matched elements.

  • jQuery .clone( [ Boolean ] withDataAndEvents, [ Boolean ] deepWithDataAndEvents )

    New in 1.5 !

    Create a deep copy of the set of matched elements.

  • jQuery .remove( [ String ] selector )

    New in 1.0 !

    Remove the set of matched elements from the DOM.

  • jQuery .wrap( [ Function ] function(index) )

    New in 1.4 !

    Wrap an HTML structure around each element in the set of matched elements.

  • jQuery .insertBefore( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements before the target.

  • jQuery .before( [ Function ] function )

    New in 1.4 !

    Insert content, specified by the parameter, before each element in the set of matched elements.

  • jQuery .insertAfter( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements after the target.

  • jQuery .after( [ Function ] function(index) )

    New in 1.4 !

    Insert content, specified by the parameter, after each element in the set of matched elements.

  • jQuery .prependTo( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements to the beginning of the target.

  • jQuery .prepend( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

  • jQuery .appendTo( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements to the end of the target.

  • jQuery .append( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the end of each element in the set of matched elements.

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.

  • jQuery .html( [ Function ] function(index, oldhtml) )

    New in 1.4 !

    Set the HTML contents of each element in the set of matched elements.

  • Boolean .is( [ Selector ] selector )

    New in 1.0 !

    Check the current matched set of elements against a selector and return true if at least one of these elements matches the selector.

  • jQuery .filter( [ Object ] jQuery object )

    New in 1.4 !

    Reduce the set of matched elements to those that match the selector or pass the function's test.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • jQuery .removeAttr( [ String ] attributeName )

    New in 1.0 !

    Remove an attribute from each element in the set of matched elements.

  • jQuery .attr( [ String ] attributeName, [ Function ] function(index, attr) )

    New in 1.1 !

    Set one or more attributes for the set of matched elements.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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

  • Number event.pageY

    New in 1.0.4 !

    The mouse position relative to the top edge of the document.

  • Number event.pageX

    New in 1.0.4 !

    The mouse position relative to the left edge of the document.

  • jQuery.globalEval( [ String ] code )

    New in 1.0.4 !

    Execute some JavaScript code globally.

  • Anything event.data

    New in 1.1 !

    The optional data passed to jQuery.fn.bind when the current executing handler was bound.

  • jQuery .one( [ String ] eventType, [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.1 !

    Attach a handler to an event for the elements. The handler is executed at most once per element.

  • jQuery.ajaxSetup( [ Options ] options )

    New in 1.1 !

    Set default values for future Ajax requests.

  • jQuery .attr( [ String ] attributeName, [ Function ] function(index, attr) )

    New in 1.1 !

    Set one or more attributes for the set of matched elements.

  • jQuery .eq( [ Integer ] -index )

    New in 1.4 !

    Reduce the set of matched elements to the one at the specified index.

  • Number event.which

    New in 1.1.3 !

    For key or button events, this attribute indicates the specific button or key that was pressed.

  • Map jQuery.browser

    New in 1.0 !

    Contains flags for the useragent, read from navigator.userAgent.

  • String jQuery.browser.version

    New in 1.1.3 !

    The version number of the rendering engine for the user's browser.

  • Array jQuery.unique( [ Array ] array )

    New in 1.1.3 !

    Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.

  • Element event.relatedTarget

    New in 1.1.4 !

    The other DOM element involved in the event, if any.

  • Boolean jQuery.isXMLDoc( [ Element ] node )

    New in 1.1.4 !

    Check to see if a DOM node is within an XML document (or is an XML document).

  • JQuery(":only-child")

    New in 1.1.4 !

    Selects all elements that are the only child of their parent.

  • JQuery(":last-child")

    New in 1.1.4 !

    Selects all elements that are the last child of their parent.

  • JQuery(":first-child")

    New in 1.1.4 !

    Selects all elements that are the first child of their parent.

  • JQuery(":nth-child(index/even/odd/equation)")

    New in 1.1.4 !

    Selects all elements that are the nth-child of their parent.

  • JQuery(":has(selector)")

    New in 1.1.4 !

    Selects elements which contain at least one element that matches the specified selector.

  • JQuery(":contains(text)")

    New in 1.1.4 !

    Select all elements that contain the specified text.

  • jQuery .slice( [ Integer ] start, [ Integer ] end )

    New in 1.1.4 !

    Reduce the set of matched elements to a subset specified by a range of indices.

  • JQuery(":animated")

    New in 1.2 !

    Select all elements that are in the progress of an animation at the time the selector is run.

  • JQuery(":header")

    New in 1.2 !

    Selects all elements that are headers, like h1, h2, h3 and so on.

  • jQuery .dequeue( [ String ] queueName )

    New in 1.2 !

    Execute the next function on the queue for the matched elements.

  • jQuery .queue( [ String ] queueName, [ Function ] callback( next ) )

    New in 1.2 !

    Manipulate the queue of functions to be executed on the matched elements.

  • Object .triggerHandler( [ String ] eventType, [ Array ] extraParameters )

    New in 1.2 !

    Execute all handlers attached to an element for an event.

  • Array .serializeArray( )

    New in 1.2 !

    Encode a set of form elements as an array of names and values.

  • jQuery .stop( [ Boolean ] clearQueue, [ Boolean ] jumpToEnd )

    New in 1.2 !

    Stop the currently-running animation on the matched elements.

  • jQuery .andSelf( )

    New in 1.2 !

    Add the previous set of elements on the stack to the current set.

  • jQuery .prevAll( [ Selector ] selector )

    New in 1.2 !

    Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .nextAll( [ String ] selector )

    New in 1.2 !

    Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .contents( )

    New in 1.2 !

    Get the children of each element in the set of matched elements, including text and comment nodes.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

  • boolean jQuery.isFunction( [ Object ] obj )

    New in 1.2 !

    Determine if the argument passed is a Javascript function object.

  • Number jQuery.inArray( [ Any ] value, [ Array ] array )

    New in 1.2 !

    Search for a specified value within an array and return its index (or -1 if not found).

  • Array jQuery.makeArray( [ Object ] obj )

    New in 1.2 !

    Convert an array-like object into a true JavaScript array.

  • Object .position( )

    New in 1.2 !

    Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.

  • jQuery .replaceAll( [ Selector ] target )

    New in 1.2 !

    Replace each target element with the set of matched elements.

  • jQuery .replaceWith( [ Function ] function )

    New in 1.4 !

    Replace each element in the set of matched elements with the provided new content.

  • jQuery .wrapInner( [ Function ] wrappingFunction )

    New in 1.4 !

    Wrap an HTML structure around the content of each element in the set of matched elements.

  • jQuery .wrapAll( [ String | Selector | Element | jQuery ] wrappingElement )

    New in 1.2 !

    Wrap an HTML structure around all elements in the set of matched elements.

  • jQuery .map( [ Function ] callback(index, domElement) )

    New in 1.2 !

    Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

  • Boolean .hasClass( [ String ] className )

    New in 1.2 !

    Determine whether any of the matched elements are assigned the given class.

  • jQuery jQuery.removeData( [ Element ] element, [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery .removeData( [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • Number event.timeStamp

    New in 1.2.6 !

    The difference in milliseconds between the time an event is triggered and January 1, 1970.

  • Integer .outerWidth( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding and border.

  • Integer .outerHeight( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.

  • Integer .innerWidth( )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding but not border.

  • Integer .innerHeight( )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding but not border.

  • jQuery .scrollLeft( [ Number ] value )

    New in 1.2.6 !

    Set the current horizontal position of the scroll bar for each of the set of matched elements.

  • jQuery .scrollTop( [ Number ] value )

    New in 1.2.6 !

    Set the current vertical position of the scroll bar for each of the set of matched elements.

  • Boolean event.isImmediatePropagationStopped( )

    New in 1.3 !

    Returns whether event.stopImmediatePropagation() was ever called on this event object.

  • event.stopImmediatePropagation( )

    New in 1.3 !

    Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.

  • Boolean event.isPropagationStopped( )

    New in 1.3 !

    Returns whether was ever called on this event object.

  • Boolean event.isDefaultPrevented( )

    New in 1.3 !

    Returns whether was ever called on this event object.

  • Object event.result

    New in 1.3 !

    The last value returned by an event handler that was triggered by this event, unless the value was .

  • Element event.currentTarget

    New in 1.3 !

    The current DOM element within the event bubbling phase.

  • Boolean jQuery.fx.off

    New in 1.3 !

    Globally disable all animations.

  • jQuery .pushStack( [ Array ] elements, [ String ] name, [ Array ] arguments )

    New in 1.3 !

    Add a collection of DOM elements onto the jQuery stack.

  • jQuery jQuery.dequeue( [ Element ] element, [ String ] queueName )

    New in 1.3 !

    Execute the next function on the queue for the matched element.

  • jQuery jQuery.queue( [ Element ] element, [ String ] queueName, [ Function ] callback() )

    New in 1.3 !

    Manipulate the queue of functions to be executed on the matched element.

  • jQuery .die( [ Map ] eventTypes )

    New in 1.4.3 !

    Remove an event handler previously attached using from the elements.

  • jQuery .live( [ Object ] events )

    New in 1.4.3 !

    Attach a handler to the event for all elements which match the current selector, now and in the future.

  • Array .closest( [ Array ] selectors, [ Element ] context )

    New in 1.4 !

    Gets an array of all the elements and selectors matched against the current element up through the DOM tree.

  • String selector

    New in 1.3 !

    A selector representing selector originally passed to jQuery().

  • Element context

    New in 1.3 !

    The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document.

  • jQuery .toggle( [ Boolean ] showOrHide )

    New in 1.3 !

    Display or hide the matched elements.

  • boolean jQuery.isArray( [ Object ] obj )

    New in 1.3 !

    Determine whether the argument is an array.

  • Object jQuery.support

    New in 1.3 !

    A collection of properties that represent the presence of different browser features or bugs.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • Function jQuery.proxy( [ Object ] context, [ String ] name )

    New in 1.4 !

    Takes a function and returns a new one that will always have a particular context.

  • jQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusout" JavaScript event.

  • jQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusin" JavaScript event.

  • jQuery .has( [ Element ] contained )

    New in 1.4 !

    Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

  • Boolean jQuery.contains( [ Element ] container, [ Element ] contained )

    New in 1.4 !

    Check to see if a DOM node is within another DOM node.

  • Function jQuery.noop( )

    New in 1.4 !

    An empty function.

  • jQuery .delay( [ Integer ] duration, [ String ] queueName )

    New in 1.4 !

    Set a timer to delay execution of subsequent items in the queue.

  • jQuery .parentsUntil( [ Selector ] selector )

    New in 1.4 !

    Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.

  • jQuery .prevUntil( [ Selector ] selector )

    New in 1.4 !

    Get all preceding siblings of each element up to but not including the element matched by the selector.

  • jQuery .nextUntil( [ Selector ] selector )

    New in 1.4 !

    Get all following siblings of each element up to but not including the element matched by the selector.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery .clearQueue( [ String ] queueName )

    New in 1.4 !

    Remove from the queue all items that have not yet been run.

  • Array .toArray( )

    New in 1.4 !

    Retrieve all the DOM elements contained in the jQuery set, as an array.

  • Boolean jQuery.isEmptyObject( [ Object ] object )

    New in 1.4 !

    Check to see if an object is empty (contains no properties).

  • Boolean jQuery.isPlainObject( [ Object ] object )

    New in 1.4 !

    Check to see if an object is a plain object (created using "{}" or "new Object").

  • Number .index( [ Element | jQuery ] element )

    New in 1.0 !

    Search for a given element from among the matched elements.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • jQuery .bind( [ Object ] events )

    New in 1.4 !

    Attach a handler to an event for the elements.

  • jQuery .first( )

    New in 1.4 !

    Reduce the set of matched elements to the first in the set.

  • jQuery .last( )

    New in 1.4 !

    Reduce the set of matched elements to the final one in the set.

  • jQuery jQuery( [ Function ] callback )

    New in 1.0 !

    Binds a function to be executed when the DOM has finished loading.

  • Array .closest( [ Array ] selectors, [ Element ] context )

    New in 1.4 !

    Gets an array of all the elements and selectors matched against the current element up through the DOM tree.

  • jQuery .add( [ Selector ] selector, [ Element ] context )

    New in 1.4 !

    Add elements to the set of matched elements.

  • jQuery .not( [ Function ] function(index) )

    New in 1.4 !

    Remove elements from the set of matched elements.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.

  • jQuery .css( [ Map ] map )

    New in 1.0 !

    Set one or more CSS properties for the set of matched elements.

  • jQuery .unwrap( )

    New in 1.4 !

    Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

  • jQuery .detach( [ Selector ] selector )

    New in 1.4 !

    Remove the set of matched elements from the DOM.

  • jQuery .replaceWith( [ Function ] function )

    New in 1.4 !

    Replace each element in the set of matched elements with the provided new content.

  • jQuery .wrapInner( [ Function ] wrappingFunction )

    New in 1.4 !

    Wrap an HTML structure around the content of each element in the set of matched elements.

  • jQuery .wrapAll( [ String | Selector | Element | jQuery ] wrappingElement )

    New in 1.2 !

    Wrap an HTML structure around all elements in the set of matched elements.

  • jQuery .wrap( [ Function ] function(index) )

    New in 1.4 !

    Wrap an HTML structure around each element in the set of matched elements.

  • jQuery .before( [ Function ] function )

    New in 1.4 !

    Insert content, specified by the parameter, before each element in the set of matched elements.

  • jQuery .after( [ Function ] function(index) )

    New in 1.4 !

    Insert content, specified by the parameter, after each element in the set of matched elements.

  • jQuery .prepend( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

  • jQuery .append( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the end of each element in the set of matched elements.

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.

  • jQuery .text( [ Function ] function(index, text) )

    New in 1.4 !

    Set the content of each element in the set of matched elements to the specified text.

  • jQuery .html( [ Function ] function(index, oldhtml) )

    New in 1.4 !

    Set the HTML contents of each element in the set of matched elements.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • jQuery .removeAttr( [ String ] attributeName )

    New in 1.0 !

    Remove an attribute from each element in the set of matched elements.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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

  • jQuery.error( [ String ] message )

    New in 1.4.1 !

    Takes a string and throws an exception containing it.

  • Object jQuery.parseJSON( [ String ] json )

    New in 1.4.1 !

    Takes a well-formed JSON string and returns the resulting JavaScript object.

  • jQuery .die( [ Map ] eventTypes )

    New in 1.4.3 !

    Remove an event handler previously attached using from the elements.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.

  • jQuery .undelegate( [ String ] namespace )

    New in 1.6 !

    Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.

  • jQuery .delegate( [ String ] selector, [ Map ] events )

    New in 1.4.3 !

    Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

  • Number jQuery.now( )

    New in 1.4.3 !

    Return a number representing the current time.

  • Object jQuery.cssHooks

    New in 1.4.3 !

    Provides a way to hook directly into jQuery to override how particular CSS properties are retrieved or set. Amongst other uses, cssHooks can be used to create custom, browser-normalized properties for CSS3 features such as box-shadows and gradients.

  • String jQuery.type( [ Object ] obj )

    New in 1.4.3 !

    Determine the internal JavaScript [[Class]] of an object.

  • boolean jQuery.isWindow( [ Object ] obj )

    New in 1.4.3 !

    Determine whether the argument is a window.

  • Number jQuery.fx.interval

    New in 1.4.3 !

    The rate (in milliseconds) at which animations fire.

  • String event.namespace

    New in 1.4.3 !

    The namespace specified when the event was triggered.

  • jQuery .undelegate( [ String ] namespace )

    New in 1.6 !

    Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.

  • jQuery .delegate( [ String ] selector, [ Map ] events )

    New in 1.4.3 !

    Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

  • jQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusout" JavaScript event.

  • jQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusin" JavaScript event.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery .keydown( )

    New in 1.0 !

    Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • jQuery .scroll( )

    New in 1.0 !

    Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.

  • jQuery .resize( )

    New in 1.0 !

    Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.

  • jQuery .keyup( )

    New in 1.0 !

    Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.

  • jQuery .keypress( )

    New in 1.0 !

    Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.

  • jQuery .submit( )

    New in 1.0 !

    Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

  • jQuery .select( )

    New in 1.0 !

    Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

  • jQuery .change( )

    New in 1.0 !

    Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

  • jQuery .blur( )

    New in 1.0 !

    Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.

  • jQuery .focus( )

    New in 1.0 !

    Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.

  • jQuery .mousemove( )

    New in 1.0 !

    Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.

  • jQuery .mouseleave( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.

  • jQuery .mouseenter( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

  • jQuery .mouseout( )

    New in 1.0 !

    Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.

  • jQuery .mouseover( )

    New in 1.0 !

    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • jQuery .dblclick( )

    New in 1.0 !

    Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.

  • jQuery .click( )

    New in 1.0 !

    Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

  • jQuery .mouseup( )

    New in 1.0 !

    Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.

  • jQuery .mousedown( )

    New in 1.0 !

    Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.

  • jQuery .error( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "error" JavaScript event.

  • jQuery .unload( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "unload" JavaScript event.

  • jQuery .load( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "load" JavaScript event.

  • jQuery .die( [ Map ] eventTypes )

    New in 1.4.3 !

    Remove an event handler previously attached using from the elements.

  • jQuery .unbind( [ Object ] event )

    New in 1.0 !

    Remove a previously-attached event handler from the elements.

  • jQuery .bind( [ Object ] events )

    New in 1.4 !

    Attach a handler to an event for the elements.

  • jQuery .fadeTo( [ String,Number ] duration, [ Number ] opacity, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Adjust the opacity of the matched elements.

  • jQuery .fadeOut( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements by fading them to transparent.

  • jQuery .fadeIn( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements by fading them to opaque.

  • jQuery .slideToggle( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display or hide the matched elements with a sliding motion.

  • jQuery .slideUp( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements with a sliding motion.

  • jQuery .slideDown( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements with a sliding motion.

  • jQuery .toggle( [ Boolean ] showOrHide )

    New in 1.3 !

    Display or hide the matched elements.

  • jQuery .hide( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements.

  • jQuery .show( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements.

  • jQuery .fadeToggle( [ String,Number ] duration, [ String ] easing, [ Function ] callback )

    New in 1.4.4 !

    Display or hide the matched elements by animating their opacity.

  • undefined jQuery.ajaxPrefilter( [ String ] dataTypes, [ Function ] handler(options, originalOptions, jqXHR) )

    New in 1.5 !

    Handle custom Ajax options or modify existing options before each request is sent and before they are processed by .

  • Boolean jQuery.hasData( [ Element ] element )

    New in 1.5 !

    Determine whether an element has any jQuery data associated with it.

  • Promise .deferred.promise( )

    New in 1.5 !

    Return a Deferred's Promise object.

  • XMLDocument jQuery.parseXML( [ String ] data )

    New in 1.5 !

    Parses a string into an XML document.

  • Promise jQuery.when( [ Deferred ] deferreds )

    New in 1.5 !

    Provides a way to execute callback functions based on one or more objects, usually objects that represent asynchronous events.

  • Deferred .deferred.resolveWith( [ Object ] context, [ Array ] args )

    New in 1.5 !

    Resolve a Deferred object and call any doneCallbacks with the given and .

  • Deferred .deferred.rejectWith( [ Object ] context, [ Array ] args )

    New in 1.5 !

    Reject a Deferred object and call any failCallbacks with the given and .

  • Deferred .deferred.fail( [ Function ] failCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is rejected.

  • Deferred .deferred.done( [ Function ] doneCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is resolved.

  • Deferred .deferred.then( [ Function ] doneCallbacks, [ Function ] failCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is resolved or rejected.

  • Deferred .deferred.reject( [ Object ] args )

    New in 1.5 !

    Reject a Deferred object and call any failCallbacks with the given .

  • Boolean .deferred.isRejected( )

    New in 1.5 !

    Determine whether a Deferred object has been rejected.

  • Boolean .deferred.isResolved( )

    New in 1.5 !

    Determine whether a Deferred object has been resolved.

  • Deferred .deferred.resolve( [ Object ] args )

    New in 1.5 !

    Resolve a Deferred object and call any doneCallbacks with the given .

  • jQuery jQuery.sub( )

    New in 1.5 !

    Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.

  • jqXHR jQuery.post( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP POST request.

  • XMLHttpRequest jQuery.getScript( [ String ] url, [ Function ] success(data, textStatus) )

    New in 1.0 !

    Load a JavaScript file from the server using a GET HTTP request, then execute it.

  • jqXHR jQuery.getJSON( [ String ] url, [ Map ] data, [ Function ] success(data, textStatus, jqXHR) )

    New in 1.0 !

    Load JSON-encoded data from the server using a GET HTTP request.

  • jqXHR jQuery.get( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP GET request.

  • jqXHR jQuery.ajax( [ Map ] settings )

    New in 1.0 !

    Perform an asynchronous HTTP (Ajax) request.

  • jQuery .clone( [ Boolean ] withDataAndEvents, [ Boolean ] deepWithDataAndEvents )

    New in 1.5 !

    Create a deep copy of the set of matched elements.

  • jqXHR jQuery.ajax( [ Map ] settings )

    New in 1.0 !

    Perform an asynchronous HTTP (Ajax) request.

  • Object jQuery.support

    New in 1.3 !

    A collection of properties that represent the presence of different browser features or bugs.

© 2010 The jQuery Project

  • Download
  • Documentation
  • Tutorials
  • Bug Tracker
  • Discussion


Types – jQuery API

JavaScript provides several built-in datatypes. In addition to those, this page documents virtual types like Selectors, enhanced pseudo-types like Events and all and everything you wanted to know about Functions.

You should be able to try out most of the examples below by just copying them to the Firebug console (note: Firebug requires Firefox).

Whenever an example mentions that a type defaults to a boolean value, the result is good to know when using that type in a boolean context:

 var x = ""
 if ( x )
   console.log("x defaulted to true")
 else
   console.log("x defaulted to false")

In this case, "x defaulted to false" is printed.

To keep the examples short, the invert-operator is used to show a boolean context:

 !x // true

On to the actual types.

Contents

  • 1 String
    • 1.1 Quoting
    • 1.2 Built-in Methods
    • 1.3 Length Property
    • 1.4 Boolean Default
  • 2 Number
    • 2.1 Boolean Default
    • 2.2 Math
    • 2.3 Parsing Numbers
    • 2.4 Numbers to Strings
    • 2.5 NaN and Infinity
    • 2.6 Integer
    • 2.7 Float
  • 3 Boolean
  • 4 Object
    • 4.1 Dot Notation
    • 4.2 Array Notation
    • 4.3 Iteration
    • 4.4 Boolean default
    • 4.5 Prototype
  • 5 Options
  • 6 Array
    • 6.1 Iteration
    • 6.2 Boolean Default
    • 6.3 Array<Type> Notation
  • 7 Map
  • 8 Function
    • 8.1 Arguments
    • 8.2 Context, Call and Apply
    • 8.3 Scope
    • 8.4 Closures
    • 8.5 Proxy Pattern
  • 9 Callback
  • 10 Selector
  • 11 Event
  • 12 Element
  • 13 jQuery
  • 14 XMLHttpRequest
[edit]

String

 "I'm a String in JavaScript!"
 'So am I!'

A string in JavaScript is an immutable object that contains none, one or many characters.

The type of a string is "string".

 typeof "some string"; // "string"
[edit]

Quoting

A string can be defined using single or double quotes. You can nest single quotes inside of double quotes, and the other way round. To mix double quotes with double quotes, the nested ones have to be escaped with a backslash.

 "You make 'me' sad."
 'Holy "cranking" moses!'
 "<a href=\"home\">Home</a>"
[edit]

Built-in Methods

A string in JavaScript has some built-in methods to manipulate the string, though the result is always a new string - or something else, eg. split returns an array.

 "hello".charAt(0) // "h"
 "hello".toUpperCase() // "HELLO"
 "Hello".toLowerCase() // "hello"
 "hello".replace(/e|o/g, "x") // "hxllx"
 "1,2,3".split(",") // ["1", "2", "3"]
[edit]

Length Property

All strings have a length property.

 "Hello".length // 5
 "".length // 0
[edit]

Boolean Default

An empty string defaults to false:

 !"" // true
 !"hello" // false
 !"true" // false
 !new Boolean(false) // false
[edit]

Number

 12
 3.543

Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable, just as strings. All operators common in c-based languages are available to work with numbers (+, -, *, /, %, =, +=, -=, *=, /=, ++, --).

The type of a number is "number".

 typeof 12 // "number"
 typeof 3.543 // "number"
[edit]

Boolean Default

If a number is zero, it defaults to false:

 !0 // true
 !1 // false
 !-1 // false

Due to the implementation of numbers as double-precision values, the following result is not an error:

 0.1 + 0.2 // 0.30000000000000004

[edit]

Math

JavaScript provides utilities to work with numbers in the Math object:

 Math.PI // 3.141592653589793
 Math.cos(Math.PI) // -1
[edit]

Parsing Numbers

parseInt and parseFloat help parsing strings into numbers. Both do some implicit conversion if the base isn't specified:

 parseInt("123") = 123 (implicit decimal)
 parseInt("010") = 8 (implicit octal)
 parseInt("0xCAFE") = 51966 (implicit hexadecimal)
 parseInt("010", 10) = 10 (explicit decimal)
 parseInt("11", 2) = 3 (explicit binary)
 parseFloat("10.10") = 10.1
[edit]

Numbers to Strings

When appending numbers to string, the result is always a string. The operator is the same, so be careful: If you want to add numbers and then append them to a string, put parentheses around them:

 "" + 1 + 2; // "12"
 "" + (1 + 2); // "3"
 "" + 0.0000001; // "1e-7"
 parseInt(0.0000001); // 1 (!)

Or you use the String class provided by javascript, which try to parse a value as string:

 String(1) + String(2); //"12"
 String(1 + 2); //"3"
[edit]

NaN and Infinity

Parsing something that isn't a number results in NaN. isNaN helps to detect those cases:

 parseInt("hello", 10) // NaN
 isNaN(parseInt("hello", 10)) // true

Division by zero results in Infinity:

 1 / 0 // Infinity

Both NaN and Infinity are of type "number":

 typeof NaN // "number"
 typeof Infinity // "number"

Note that NaN compares in a strange way:

 NaN == NaN // false (!)

But:

 Infinity == Infinity // true
[edit]

Integer

An integer is a plain Number type, but whenever explicitly mentioned, indicates that a non-floating-point number is expected.

[edit]

Float

A float is a plain Number type, just as Integer, but whenever explicitly mentioned, indicates that a floating-point number is expected.

[edit]

Boolean

A boolean in JavaScript can be either true or false:

 if ( true ) console.log("always!")
 if ( false ) console.log("never!")

When an option is specified as a boolean, it often looks like this:

$("...").somePlugin({
  hideOnStartup: true,
  onlyOnce: false
});
[edit]

Object

Everything in JavaScript is an object, though some are more objective (haha). The easiest way to create an object is the object literal:

 var x = {};
 var y = {
   name: "Pete",
   age: 15
 };

The type of an object is "object":

 typeof {} // "object"
[edit]

Dot Notation

You can write and read properties of an object using the dot notation:

 y.name // "Pete"
 y.age // 15
 x.name = y.name + " Pan" // "Pete Pan"
 x.age = y.age + 1 // 16
[edit]

Array Notation

Or you write and read properties using the array notation, which allows you to dynamically choose the property:

 var operations = {
   increase: "++",
   decrease: "--"
 }
 var operation = "increase";
 operations[operation] // "++";
 operations["multiply"] = "*"; // "*"
[edit]

Iteration

Iterating over objects is easy with the for-in-loop:

var obj = {
  name: "Pete",
  age: 15
};
for(key in obj) {
 alert("key is "+[key]+", value is "+obj[key]);
}

Note that for-in-loop can be spoiled by extending Object.prototype (see Object.prototype is verboten) so take care when using other libraries.

jQuery provides a generic each-function to iterate over properties of objects, as well as elements of arrays:

 jQuery.each(obj, function(key, value) {
   console.log("key", key, "value", value);
 });

The drawback is that the callback is called in the context of each value, therefore you lose the context of your own object if applicable. More on this below at Functions.

[edit]

Boolean default

An object, no matter if it has properties or not, never defaults to false:

 !{} // false
[edit]

Prototype

All objects have a prototype property. Whenever the interpreter looks for a property, it also checks the prototype. jQuery uses that extensively to add methods to jQuery instances.

 var form = $("#myform");
 form.clearForm; // undefined
 form.fn.clearForm = function() {
   return this.find(":input").each(function() {
     this.value = "";
   }).end();
 };
 form.clearForm() // works for all instances of jQuery objects, because the new method was added to the prototype

(This example needs clarification: how does it modify the prototype when the word "prototype" doesn't appear anywhere? The implication is that form.fn is simply an alias for form.prototype, but if that's the case then it should be explained. :-?)

In javascript:the definitive guide 5 edition,dont add attibute to Object.prototype

[edit]

Options

Options in jQuery are plain JavaScript objects. Whenever Options is mentioned as a type, that object and also all of its properties should be optional. There are exceptions where at least one option is required. jQuery's most prominent use of Options is its AJAX-method. Nearly all jQuery plugins provide an Options-based API: They work without any configuration, but allow users to specify whatever customization they need.

Let's look at an example from the form plugin. It allows you to submit a form via AJAX with this simple line of code:

 $("#myform").ajaxForm();

In that mode, it uses the form's action-attribute as the AJAX-URL and the form's method-attribute to determine whether to GET or POST the form. You can override both defaults by specifying them as options:

 $("#myform").ajaxForm({
   url: "mypage.php",
   type: "POST"
 });
[edit]

Array

Arrays in JavaScript are mutable lists with a few built-in methods. You can define arrays using the array literal:

 var x = [];
 var y = [1, 2, 3];

The type of an array is "object":

 typeof []; // "object"
 typeof [1, 2, 3]; // "object"

Reading and writing elements to an array uses the array-notation:

 x[0] = 1;
 y[2] // 3
[edit]

Iteration

An array has a length property that is useful for iteration:

 for (var i = 0; i < a.length; i++) {
   // Do something with a[i]
 }

When performance is critical, reading the length property only once can help to speed things up. This should be used only when a performance bottleneck was discovered:

 for (var i = 0, j = a.length; i < j; i++) {
   // Do something with a[i]
 }

Another variation defines a variable that is filled for each iteration, removing the array-notation from the loop-body. It does not work when the array contains 0 or empty strings!

 for (var i = 0, item; item = a[i]; i++) {
   // Do something with item
 }

jQuery provides a generic each-function to iterate over element of arrays, as well as properties of objects:

 var x = [1, 2, 3];
 jQuery.each(x, function(index, value) {
   console.log("index", index, "value", value);
 });

The drawback is that the callback is called in the context of each value, therefore you lose the context of your own object if applicable. More on this below at Functions.

The length property can also be used to add elements to the end of an array. That is equivalent to using the push-method:

 var x = [];
 x.push(1);
 x[x.length] = 2;
 x // 1, 2

You'll see both variations a lot when looking through JavaScript library code.

Other built-in methods are reverse, join, shift, unshift, pop, slice, splice and sort:

 var x = [0, 3, 1, 2];
 x.reverse() // [2, 1, 3, 0]
 x.join(" – ") // "2 - 1 - 3 - 0"
 x.pop() // [2, 1, 3]
 x.unshift(-1) // [-1, 2, 1, 3]
 x.shift() // [2, 1, 3]
 x.sort() // [1, 2, 3]
 x.splice(1, 2) // [2, 3]

Note: .unshift() method does not return a length property in Internet Explorer.

[edit]

Boolean Default

An array, no matter if it has elements or not, never defaults to false:

 ![] // false
[edit]

Array<Type> Notation

In the jQuery API you'll often find the notation of Array<Type>:

dragPrevention    Array<String>

This indicates that the method doesn't only expect an array as the argument, but also specifies the expected type. The notation is borrowed from Java 5's generics notation (or C++ templates).

[edit]

Map

The map type is used by the AJAX function to hold the data of a request. This type could be a string, an array<form elements>, a jQuery object with form elements or an object with key/value pairs. In the last case, it is possible to assign multiple values to one key by assigning an array.

{'key[]':['valuea','valueb']}

becomes on the server-side (in PHP):

$_REQUEST['key'][0]="valuea";
$_REQUEST['key'][1]="valueb";

in Rails or Merb:

 params[:key] = ["valuea", "valueb"]
[edit]

Function

A function in JavaScript can be either named or anonymous. Any function can be assigned to a variable or passed to a method, but passing member functions this way can cause them to be called in the context of another object (i.e. with a different "this" object).

function named() {}
var handler = function() {}

You see a lot of anonymous functions in jQuery code:

 $(document).ready(function() {});
 $("a").click(function() {});
 $.ajax({
   url: "someurl.php",
   success: function() {}
 });

The type of a function is "function".

[edit]

Arguments

Inside a function a special variable "arguments" is always available. It's similar to an array in that it has a length property, but it lacks the built-in methods of an array. The elements of the pseudo-array are the argument of the function call.

function log(x) {
  console.log(typeof x, arguments.length);
}
log(); // "undefined", 0
log(1); // "number", 1
log("1", "2", "3"); // "string", 3

The arguments object also has a callee property, which refers to the function you're inside of. For instance:

 var awesome = function() { return arguments.callee }
 awesome() == awesome // true
[edit]

Context, Call and Apply

In JavaScript, the variable "this" always refers to the current context. By default, "this" refers to the window object. Within a function this context can change, depending on how the function is called.

All event handlers in jQuery are called with the handling element as the context.

$(document).ready(function() {
  // this refers to window.document
});
$("a").click(function() {
  // this refers to an anchor DOM element
});

You can specify the context for a function call using the function-built-in methods call and apply. The difference between them is how they pass arguments. Call passes all arguments through as arguments to the function, while apply accepts an array as the arguments.

function scope() {
  console.log(this, arguments.length);
}
scope() // window, 0
scope.call("foobar", [1,2]); // "foobar", 1
scope.apply("foobar", [1,2]); // "foobar", 2
[edit]

Scope

In JavaScript, all variables defined inside a function are only visible inside that function scope. Consider the following example:

 // global
 var x = 0;
 (function() {
   // private
   var x = 1;
   console.log(x); // 1
 })();
 console.log(x); // 0

It defines a variable x in the global scope, then defines an anonymous function and executes it immediately (the additional parentheses are required for immediate execution). Inside the function another variable x is defined with a different value. It is only visible within that function and doesn't overwrite the global variable.

[edit]

Closures

Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope. In the following example, the variable counter is visible within the create, increment, and print functions, but not outside of them.

function create() {
  var counter = 0;
  return {
    increment: function() {
      counter++;
    },
    print: function() {
      console.log(counter);
    }
  }
}
var c = create();
c.increment();
c.print(); // 1

The pattern allows you to create objects with methods that operate on data that isn't visible to the outside—the very basis of object-oriented programming.

[edit]

Proxy Pattern

Combining the above knowledge gives you as a JavaScript developer quite a lot of power. One way to combine that is to implement a proxy pattern in JavaScript, enabling the basics of aspect-oriented programming (AOP):

(function() {
  // log all calls to setArray
  var proxied = jQuery.fn.setArray;
  jQuery.fn.setArray = function() {
    console.log(this, arguments);
    return proxied.apply(this, arguments);
  };
})();

The above wraps its code in a function to hide the "proxied"-variable. It saves jQuery's setArray-method in a closure and overwrites it. The proxy then logs all calls to the method and delegates the call to the original. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method.

[edit]

Callback

A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered. jQuery's event system uses such callbacks everywhere:

 $("body").click(function(event) {
   console.log("clicked: " + event.target);
 });

Most callbacks provide arguments and a context. In the event-handler example, the callback is called with one argument, an Event. The context is set to the handling element, in the above example, document.body.

Some callbacks are required to return something, others make that return value optional. To prevent a form submission, a submit event handler can return false:

 $("#myform").submit(function() {
   return false;
 });

Instead of always returning false, the callback could check fields of the form for validity, and return false only when the form is invalid.

[edit]

Selector

A selector is used in jQuery to select DOM elements from a DOM document. That document is, in most cases, the DOM document present in all browsers, but can also be a XML document received via AJAX.

The selectors are a composition of CSS and custom additions. XPath selectors are available as a plugin.

All selectors available in jQuery are documented on the Selectors API page.

There are lot of plugins that leverage jQuery's selectors in other ways. The validation plugin accepts a selector to specify a dependency, whether an input is required or not:

 emailrules: {
   required: "#email:filled"
 }

This would make a checkbox with name "emailrules" required only if the user entered an email address in the email field, selected via its id, filtered via a custom selector ":filled" that the validation plugin provides.

If Selector is specified as the type of an argument, it accepts everything that the jQuery constructor accepts, eg. Strings, Elements, Lists of Elements.

[edit]

Event

jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods.

Those properties are all documented, and accompanied by examples, on the Event page.

The standard events in the Document Object Model are: blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, and keyup. Since the DOM event names have predefined meanings for some elements, using them for other purposes is not recommended. jQuery's event model can trigger an event by any name on an element, and it is propagated up the DOM tree to which that element belongs, if any.

[edit]

Element

An element in the Document Object Model (DOM) has attributes, text and children. It provides methods to traverse the parent and children and to get access to its attributes. Due to a lot of flaws in DOM API specifications and implementations, those methods are no fun to use. jQuery provides a wrapper around those elements to help interacting with the DOM. But often enough you will be working directly with DOM elements, or see methods that (also) accept DOM elements as arguments.

Whenever you use jQuery's each-method, the context of your callback is set to a DOM element. That is also the case for event handlers.

Some properties of DOM elements are quite consistent among browsers. Consider this example of a simple on-blur-validation:

$(":text").blur(function() {
  if(!this.value) {
   alert("Please enter some text!");
  }
});

You could replace this.value with $(this).val() to access the value of the text input via jQuery, but in that case you don't gain anything.

[edit]

jQuery

A jQuery object contains a collection of Document Object Model (DOM) elements that have been created from an HTML string or selected from a document. Since jQuery methods often use CSS selectors to match elements from a document, the set of elements in a jQuery object is often called a set of "matched elements" or "selected elements".

The jQuery object itself behaves much like an array; it has a length property and the elements in the object can be accessed by their numeric indices [0] to [length-1]. Note that a jQuery object is not actually a Javascript Array object, so it does not have all the methods of a true Array object such as join().

Most frequently, you will use the jQuery() function to create a jQuery object. jQuery() can also be accessed by its familiar single-character alias of $(), unless you have called jQuery.noConflict() to disable this option. Many jQuery methods return the jQuery object itself, so that method calls can be chained:

$("p").css("color", "red").find(".special").css("color", "green");

Whenever you use a "destructive" jQuery method that potentially changes the set of elements in the jQuery object, such as .filter() or .find(), that method actually returns a new jQuery object with the resulting elements. To return to the previous jQuery object, you use the .end() method.

A jQuery object may be empty, containing no DOM elements. You can create an empty jQuery object with $() (that is, passing no arguments at all). A jQuery object may also be empty if a selector doesn't select any elements, or if a chained method filters out all the elements. It is not an error; any further methods called on that jQuery object simply have no effect since they have no elements to act upon. So, in this example if there are no bad entries on the page then no elements will be colored red:

$(".badEntry").css({color: "red"});
[edit]

XMLHttpRequest

Some of jQuery's AJAX functions return the native XMLHttpRequest (XHR) object, or pass it as an argument to success/error/complete handlers, so that you can do additional processing or monitoring on the request. Note that AJAX functions only return or pass an XHR object when an XHR object is actually used in the request. For example, JSONP requests and cross-domain GET requests use a script element rather than an XHR object.

Although the XHR object is a standard, there are variations in its behavior on different browsers. Refer to the W3C site and browsers' documentation for more information:

  • W3C standard
  • Apple (Safari)
  • Mozilla (Firefox)
  • Microsoft (Internet Explorer)
  • Opera

Google does not appear to have an official page for their XHR documentation for Chrome. As of version 5, Chrome does not support the use of the file protocol for XHR requests.

© 2010 The jQuery Project


Ajax – jQuery API

Ajax

  • jQuery .ajaxComplete( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

    Register a handler to be called when Ajax requests complete. This is an .

  • jQuery .ajaxSuccess( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

    Attach a function to be executed whenever an Ajax request completes successfully. This is an .

  • jQuery .ajaxStop( [ Function ] handler() )

    New in 1.0 !

    Register a handler to be called when all Ajax requests have completed. This is an .

  • jQuery .ajaxStart( [ Function ] handler() )

    New in 1.0 !

    Register a handler to be called when the first Ajax request begins. This is an .

  • jQuery .ajaxSend( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

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

  • jQuery .ajaxError( [ Function ] handler(event, jqXHR, ajaxSettings, thrownError) )

    New in 1.0 !

    Register a handler to be called when Ajax requests complete with an error. This is an .

  • Array .serializeArray( )

    New in 1.2 !

    Encode a set of form elements as an array of names and values.

  • String .serialize( )

    New in 1.0 !

    Encode a set of form elements as a string for submission.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

  • undefined jQuery.ajaxPrefilter( [ String ] dataTypes, [ Function ] handler(options, originalOptions, jqXHR) )

    New in 1.5 !

    Handle custom Ajax options or modify existing options before each request is sent and before they are processed by .

  • jQuery.ajaxSetup( [ Options ] options )

    New in 1.1 !

    Set default values for future Ajax requests.

  • jqXHR jQuery.ajax( [ Map ] settings )

    New in 1.0 !

    Perform an asynchronous HTTP (Ajax) request.

  • jqXHR jQuery.post( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP POST request.

  • XMLHttpRequest jQuery.getScript( [ String ] url, [ Function ] success(data, textStatus) )

    New in 1.0 !

    Load a JavaScript file from the server using a GET HTTP request, then execute it.

  • jqXHR jQuery.getJSON( [ String ] url, [ Map ] data, [ Function ] success(data, textStatus, jqXHR) )

    New in 1.0 !

    Load JSON-encoded data from the server using a GET HTTP request.

  • jqXHR jQuery.get( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP GET request.

  • jQuery .load( [ String ] url, [ Map | String ] data, [ Function ] complete(responseText, textStatus, XMLHttpRequest) )

    New in 1.0 !

    Load data from the server and place the returned HTML into the matched element.


Global Ajax Event Handlers – jQuery API

Global Ajax Event Handlers

  • jQuery .ajaxComplete( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

    Register a handler to be called when Ajax requests complete. This is an .

  • jQuery .ajaxSuccess( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

    Attach a function to be executed whenever an Ajax request completes successfully. This is an .

  • jQuery .ajaxStop( [ Function ] handler() )

    New in 1.0 !

    Register a handler to be called when all Ajax requests have completed. This is an .

  • jQuery .ajaxStart( [ Function ] handler() )

    New in 1.0 !

    Register a handler to be called when the first Ajax request begins. This is an .

  • jQuery .ajaxSend( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

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

  • jQuery .ajaxError( [ Function ] handler(event, jqXHR, ajaxSettings, thrownError) )

    New in 1.0 !

    Register a handler to be called when Ajax requests complete with an error. This is an .


ajaxComplete – jQuery API

Returns: jQueryjQuery .ajaxComplete( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

Categories: Global Ajax Event Handlers, Version 1.0
Description: Register a handler to be called when Ajax requests complete. This is an .
  • version added: 1.0
  • .ajaxComplete( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )
  • handler(event, XMLHttpRequest, ajaxOptions) The function to be invoked.

Whenever an Ajax request completes, jQuery triggers the event. Any and all handlers that have been registered with the method are executed at this time.

To observe this method in action, we can set up a basic Ajax load request:

<div class="trigger">Trigger</div>
<div class="result"></div>
<div class="log"></div>

We can attach our event handler to any element:

$('.log').ajaxComplete(function() {
  $(this).text('Triggered ajaxComplete handler.');
});

Now, we can make an Ajax request using any jQuery method:

$('.trigger').click(function() {
  $('.result').load('ajax/test.html');
});

When the user clicks the button and the Ajax request completes, the log message is displayed.

Because is implemented as a method of jQuery object instances, we can use the keyword as we do here to refer to the selected elements within the callback function.

All handlers are invoked, regardless of what Ajax request was completed. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an handler is executed, it is passed the event object, the object, and the settings object that was used in the creation of the request. For example, we can restrict our callback to only handling events dealing with a particular URL:

You can get the returned ajax contents by looking at or for xml and html respectively.

$('.log').ajaxComplete(function(e, xhr, settings) {
  if (settings.url == 'ajax/test.html') {
    $(this).text('Triggered ajaxComplete handler. The result is ' +
                     xhr.responseHTML);
  }
});

Examples:

Example:

Show a message when an Ajax request completes.
$("#msg").ajaxComplete(function(event,request, settings){
   $(this).append("<li>Request Complete.</li>");
 });


ajaxSuccess – jQuery API

Returns: jQueryjQuery .ajaxSuccess( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

Categories: Global Ajax Event Handlers, Version 1.0
Description: Attach a function to be executed whenever an Ajax request completes successfully. This is an .
  • version added: 1.0
  • .ajaxSuccess( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )
  • handler(event, XMLHttpRequest, ajaxOptions) The function to be invoked.

Whenever an Ajax request completes successfully, jQuery triggers the event. Any and all handlers that have been registered with the method are executed at this time.

To observe this method in action, we can set up a basic Ajax load request:

<div class="trigger">Trigger</div>
<div class="result"></div>
<div class="log"></div>

We can attach our event handler to any element:

$('.log').ajaxSuccess(function() {
  $(this).text('Triggered ajaxSuccess handler.');
});

Now, we can make an Ajax request using any jQuery method:

$('.trigger').click(function() {
  $('.result').load('ajax/test.html');
});

When the user clicks the button and the Ajax request completes successfully, the log message is displayed.

Because is implemented as a method of jQuery object instances, we can use the keyword as we do here to refer to the selected elements within the callback function.

All handlers are invoked, regardless of what Ajax request was completed. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an handler is executed, it is passed the event object, the object, and the settings object that was used in the creation of the request. For example, we can restrict our callback to only handling events dealing with a particular URL:

You can get the returned ajax contents by looking at or for xml and html respectively.

$('.log').ajaxSuccess(function(e, xhr, settings) {
  if (settings.url == 'ajax/test.html') {
    $(this).text('Triggered ajaxSuccess handler. The ajax response was:'
                     + xhr.responseHTML );
  }
});

Examples:

Example:

Show a message when an Ajax request completes successfully.
$("#msg").ajaxSuccess(function(evt, request, settings){
      $(this).append("<li>Successful Request!</li>");
      });


ajaxStop – jQuery API

Returns: jQueryjQuery .ajaxStop( [ Function ] handler() )

Categories: Global Ajax Event Handlers, Version 1.0
Description: Register a handler to be called when all Ajax requests have completed. This is an .
  • version added: 1.0
  • .ajaxStop( [ Function ] handler() )
  • handler() The function to be invoked.

Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the event. Any and all handlers that have been registered with the method are executed at this time. The event is also triggered if the last outstanding Ajax request is cancelled by returning false within the callback function.

To observe this method in action, we can set up a basic Ajax load request:

<div class="trigger">Trigger</div>
<div class="result"></div>
<div class="log"></div>

We can attach our event handler to any element:

$('.log').ajaxStop(function() {
  $(this).text('Triggered ajaxStop handler.');
});

Now, we can make an Ajax request using any jQuery method:

$('.trigger').click(function() {
  $('.result').load('ajax/test.html');
});

When the user clicks the button and the Ajax request completes, the log message is displayed.

Because is implemented as a method of jQuery object instances, we can use the keyword as we do here to refer to the selected elements within the callback function.

Examples:

Example:

Hide a loading message after all the Ajax requests have stopped.
$("#loading").ajaxStop(function(){
      $(this).hide();
      });


ajaxStart – jQuery API

Returns: jQueryjQuery .ajaxStart( [ Function ] handler() )

Categories: Global Ajax Event Handlers, Version 1.0
Description: Register a handler to be called when the first Ajax request begins. This is an .
  • version added: 1.0
  • .ajaxStart( [ Function ] handler() )
  • handler() The function to be invoked.

Whenever an Ajax request is about to be sent, jQuery checks whether there are any other outstanding Ajax requests. If none are in progress, jQuery triggers the event. Any and all handlers that have been registered with the method are executed at this time.

To observe this method in action, we can set up a basic Ajax load request:

<div class="trigger">Trigger</div>
<div class="result"></div>
<div class="log"></div>

We can attach our event handler to any element:

$('.log').ajaxStart(function() {
  $(this).text('Triggered ajaxStart handler.');
});

Now, we can make an Ajax request using any jQuery method:

$('.trigger').click(function() {
  $('.result').load('ajax/test.html');
});

When the user clicks the button and the Ajax request is sent, the log message is displayed.

Because is implemented as a method of jQuery object instances, we can use the keyword as we do here to refer to the selected elements within the callback function.

Examples:

Example:

Show a loading message whenever an Ajax request starts (and none is already active).
$("#loading").ajaxStart(function(){
   $(this).show();
 });


ajaxSend – jQuery API

Returns: jQueryjQuery .ajaxSend( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

Categories: Global Ajax Event Handlers, Version 1.0
Description: Attach a function to be executed before an Ajax request is sent. This is an .
  • version added: 1.0
  • .ajaxSend( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )
  • handler(event, XMLHttpRequest, ajaxOptions) The function to be invoked.

Whenever an Ajax request is about to be sent, jQuery triggers the event. Any and all handlers that have been registered with the method are executed at this time.

To observe this method in action, we can set up a basic Ajax load request:

<div class="trigger">Trigger</div>
<div class="result"></div>
<div class="log"></div>

We can attach our event handler to any element:

$('.log').ajaxSend(function() {
  $(this).text('Triggered ajaxSend handler.');
});

Now, we can make an Ajax request using any jQuery method:

$('.trigger').click(function() {
  $('.result').load('ajax/test.html');
});

When the user clicks the button and the Ajax request is about to begin, the log message is displayed.

Because is implemented as a method of jQuery instances, we can use the keyword as we do here to refer to the selected elements within the callback function.

All handlers are invoked, regardless of what Ajax request is to be sent. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an handler is executed, it is passed the event object, the object, and the that was used in the creation of the Ajax request. For example, we can restrict our callback to only handling events dealing with a particular URL:

$('.log').ajaxSend(function(e, xhr, settings) {
  if (settings.url == 'ajax/test.html') {
    $(this).text('Triggered ajaxSend handler.');
  }
});

Examples:

Example:

Show a message before an Ajax request is sent.
$("#msg").ajaxSend(function(evt, request, settings){
        $(this).append("<li>Starting request at " + settings.url + "</li>");
      });


ajaxError – jQuery API

Returns: jQueryjQuery .ajaxError( [ Function ] handler(event, jqXHR, ajaxSettings, thrownError) )

Categories: Global Ajax Event Handlers, Version 1.0
Description: Register a handler to be called when Ajax requests complete with an error. This is an .
  • version added: 1.0
  • .ajaxError( [ Function ] handler(event, jqXHR, ajaxSettings, thrownError) )
  • handler(event, jqXHR, ajaxSettings, thrownError) The function to be invoked.

Whenever an Ajax request completes with an error, jQuery triggers the event. Any and all handlers that have been registered with the method are executed at this time.

To observe this method in action, set up a basic Ajax load request.

<button class="trigger">Trigger</button>
<div class="result"></div>
<div class="log"></div>

Attach the event handler to any element:

$("div.log").ajaxError(function() {
  $(this).text( "Triggered ajaxError handler." );
});

Now, make an Ajax request using any jQuery method:

$("button.trigger").click(function() {
  $("div.result").load( "ajax/missing.html" );
});

When the user clicks the button and the Ajax request fails, because the requested file is missing, the log message is displayed.

Because is implemented as a method of jQuery object instances, you can use the keyword within the callback function to refer to the selected elements.

All handlers are invoked, regardless of what Ajax request was completed. To differentiate between the requests, you can use the parameters passed to the handler. Each time an handler is executed, it is passed the event object, the object (prior to jQuery 1.5, the object), and the settings object that was used in the creation of the request. If the request failed because JavaScript raised an exception, the exception object is passed to the handler as a fourth parameter. For example, to restrict the error callback to only handling events dealing with a particular URL:

$( "div.log" ).ajaxError(function(e, jqxhr, settings, exception) {
  if ( settings.url == "ajax/missing.html" ) {
    $(this).text( "Triggered ajaxError handler." );
  }
});

Examples:

Example:

Show a message when an Ajax request fails.
$("#msg").ajaxError(function(event, request, settings){
  $(this).append("<li>Error requesting page " + settings.url + "</li>");
});


Helper Functions – jQuery API

Helper Functions

  • Array .serializeArray( )

    New in 1.2 !

    Encode a set of form elements as an array of names and values.

  • String .serialize( )

    New in 1.0 !

    Encode a set of form elements as a string for submission.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.


serializeArray – jQuery API

Returns: ArrayArray .serializeArray( )

Categories: Forms, Helper Functions, Version 1.2
Description: Encode a set of form elements as an array of names and values.
  • version added: 1.2
  • .serializeArray( )

The method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:

<form>
  <div><input type="text" name="a" value="1" id="a" /></div>
  <div><input type="text" name="b" value="2" id="b" /></div>
  <div><input type="hidden" name="c" value="3" id="c" /></div>
  <div>
    <textarea name="d" rows="8" cols="40">4</textarea>
  </div>
  <div><select name="e">
    <option value="5" selected="selected">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
  </select></div>
  <div>
    <input type="checkbox" name="f" value="8" id="f" />
  </div>
  <div>
    <input type="submit" name="g" value="Submit" id="g" />
  </div>
</form>

The method uses the standard W3C rules for to determine which elements it should include; in particular the element cannot be disabled and must contain a attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized.

This method can act on a jQuery object that has selected individual form elements, such as , , and . However, it is typically easier to select the tag itself for serialization:

$('form').submit(function() {
  console.log($(this).serializeArray());
  return false;
});

This produces the following data structure (provided that the browser supports ):

[
  {
    name: a
    value: 1
  },
  {
    name: b
    value: 2
  },
  {
    name: c
    value: 3
  },
  {
    name: d
    value: 4
  },
  {
    name: e
    value: 5
  }
]

Examples:

Example:

Get the values from a form, iterate through them, and append them to a results display.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body, select { font-size:14px; }
  form { margin:5px; }
  p { color:red; margin:5px; }
  b { color:blue; }</style>
</head>
<body>
  <p><b>Results:</b> <span id="results"></span></p>

  <form>
    <select name="single">
      <option>Single</option>
      <option>Single2</option>

    </select>
    <select name="multiple" multiple="multiple">
      <option selected="selected">Multiple</option>
      <option>Multiple2</option>

      <option selected="selected">Multiple3</option>
    </select><br/>
    <input type="checkbox" name="check" value="check1" id="ch1"/>

    <label for="ch1">check1</label>
    <input type="checkbox" name="check" value="check2" checked="checked" id="ch2"/>

    <label for="ch2">check2</label>
    <input type="radio" name="radio" value="radio1" checked="checked" id="r1"/>

    <label for="r1">radio1</label>
    <input type="radio" name="radio" value="radio2" id="r2"/>

    <label for="r2">radio2</label>
  </form>
  <script>function showValues() {
      var fields = $(":input").serializeArray();
      $("#results").empty();
      jQuery.each(fields, function(i, field){
        $("#results").append(field.value + " ");
      });
    }

    $(":checkbox, :radio").click(showValues);
    $("select").change(showValues);
    showValues();</script>
</body>
</html>

Demo:


serialize – jQuery API

Returns: StringString .serialize( )

Categories: Forms, Helper Functions, Version 1.0
Description: Encode a set of form elements as a string for submission.
  • version added: 1.0
  • .serialize( )

The method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:

<form>
  <div><input type="text" name="a" value="1" id="a" /></div>
  <div><input type="text" name="b" value="2" id="b" /></div>
  <div><input type="hidden" name="c" value="3" id="c" /></div>
  <div>
    <textarea name="d" rows="8" cols="40">4</textarea>
  </div>
  <div><select name="e">
    <option value="5" selected="selected">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
  </select></div>
  <div>
    <input type="checkbox" name="f" value="8" id="f" />
  </div>
  <div>
    <input type="submit" name="g" value="Submit" id="g" />
  </div>
</form>

The method can act on a jQuery object that has selected individual form elements, such as , , and . However, it is typically easier to select the tag itself for serialization:

$('form').submit(function() {
  alert($(this).serialize());
  return false;
});

This produces a standard-looking query string:

a=1&b=2&c=3&d=4&e=5

selecting both the form and its children will cause duplicates in the serialized string.

Note: Only are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a attribute. Data from file select elements is not serialized.

Examples:

Example:

Serialize a form to a query string, that could be sent to a server in an Ajax request.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body, select { font-size:12px; }
  form { margin:5px; }
  p { color:red; margin:5px; font-size:14px; }
  b { color:blue; }</style>
</head>
<body>

<form>
    <select name="single">
      <option>Single</option>
      <option>Single2</option>
    </select>

<br />
    <select name="multiple" multiple="multiple">
      <option selected="selected">Multiple</option>
      <option>Multiple2</option>

      <option selected="selected">Multiple3</option>
    </select>
<br/>
    <input type="checkbox" name="check" value="check1" id="ch1"/>

    <label for="ch1">check1</label>

    <input type="checkbox" name="check" value="check2" checked="checked" id="ch2"/>

    <label for="ch2">check2</label>
<br />
    <input type="radio" name="radio" value="radio1" checked="checked" id="r1"/>

    <label for="r1">radio1</label>
    <input type="radio" name="radio" value="radio2" id="r2"/>

    <label for="r2">radio2</label>
  </form>
  <p><tt id="results"></tt></p>
  <script>function showValues() {
      var str = $("form").serialize();
      $("#results").text(str);
    }
    $(":checkbox, :radio").click(showValues);
    $("select").change(showValues);
    showValues();</script>
</body>
</html>

Demo:


jQuery.param – jQuery API

Returns: StringString jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

Categories: Collection Manipulation, Forms, Helper Functions, Version 1.2, Version 1.4
Description: Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.
  • version added: 1.2
  • jQuery.param( [ Array | Object ] obj )
  • obj An array or object to serialize.
  • version added: 1.4
  • jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )
  • obj An array or object to serialize.
  • traditional A Boolean indicating whether to perform a traditional "shallow" serialization.

This function is used internally to convert form element values into a serialized string representation (See for more information).

As of jQuery 1.3, the return value of a function is used instead of the function as a String.

As of jQuery 1.4, the method serializes deep objects recursively to accommodate modern scripting languages and frameworks such as PHP and Ruby on Rails. You can disable this functionality globally by setting .

If the object passed is in an Array, it must be an array of objects in the format returned by

[{name:"first",value:"Rick"},
{name:"last",value:"Astley"},
{name:"job",value:"Rock Star"}]

Note: Because some frameworks have limited ability to parse serialized arrays, we should exercise caution when passing an argument that contains objects or arrays nested within another array.

In jQuery 1.4 HTML5 input elements are serialized, as well.

We can display a query string representation of an object and a URI-decoded version of the same as follows:

var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [1,2,3]
};
var recursiveEncoded = $.param(myObject);
var recursiveDecoded = decodeURIComponent($.param(myObject));

alert(recursiveEncoded);
alert(recursiveDecoded);

The values of and are alerted as follows:

To emulate the behavior of prior to jQuery 1.4, we can set the argument to :

var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [1,2,3]
};
var shallowEncoded = $.param(myObject, true);
var shallowDecoded = decodeURIComponent(shallowEncoded);

alert(shallowEncoded);
alert(shallowDecoded);

The values of and are alerted as follows:

Examples:

Example:

Serialize a key/value object.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:red; }</style>
</head>
<body>
  <div id="results"></div>
  <script>var params = { width:1680, height:1050 };
    var str = jQuery.param(params);
    $("#results").text(str);</script>
</body>
</html>

Demo:

Example:

Serialize a few complex objects
// <=1.3.2:
$.param({ a: [2,3,4] }) // "a=2&a=3&a=4"
// >=1.4:
$.param({ a: [2,3,4] }) // "a[]=2&a[]=3&a[]=4"

// <=1.3.2:
$.param({ a: { b:1,c:2 }, d: [3,4,{ e:5 }] }) // "a=[object+Object]&d=3&d=4&d=[object+Object]"
// >=1.4:
$.param({ a: { b:1,c:2 }, d: [3,4,{ e:5 }] }) // "a[b]=1&a[c]=2&d[]=3&d[]=4&d[2][e]=5"


Low-Level Interface – jQuery API

Low-Level Interface

  • undefined jQuery.ajaxPrefilter( [ String ] dataTypes, [ Function ] handler(options, originalOptions, jqXHR) )

    New in 1.5 !

    Handle custom Ajax options or modify existing options before each request is sent and before they are processed by .

  • jQuery.ajaxSetup( [ Options ] options )

    New in 1.1 !

    Set default values for future Ajax requests.

  • jqXHR jQuery.ajax( [ Map ] settings )

    New in 1.0 !

    Perform an asynchronous HTTP (Ajax) request.


jQuery.ajaxPrefilter – jQuery API

Returns: undefinedundefined jQuery.ajaxPrefilter( [ String ] dataTypes, [ Function ] handler(options, originalOptions, jqXHR) )

Categories: Low-Level Interface, Version 1.5
Description: Handle custom Ajax options or modify existing options before each request is sent and before they are processed by .
  • version added: 1.5
  • jQuery.ajaxPrefilter( [ String ] dataTypes, [ Function ] handler(options, originalOptions, jqXHR) )
  • dataTypes An optional string containing one or more space-separated dataTypes
  • handler(options, originalOptions, jqXHR) A handler to set default values for future Ajax requests.

A typical prefilter registration using looks like this:

$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
  // Modify options, control originalOptions, store jqXHR, etc
});

where:

Prefilters are a perfect fit when custom options need to be handled. Given the following code, for example, a call to would automatically abort a request to the same URL if the custom option is set to :

var currentRequests = {};

$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
  if ( options.abortOnRetry ) {
    if ( currentRequests[ options.url ] ) {
      currentRequests[ options.url ].abort();
    }
    currentRequests[ options.url ] = jqXHR;
  }
});

Prefilters can also be used to modify existing options. For example, the following proxies cross-domain requests through http://mydomain.net/proxy/:

$.ajaxPrefilter( function( options ) {
  if ( options.crossDomain ) {
    options.url = "http://mydomain.net/proxy/" + encodeURIComponent( options.url );
    options.crossDomain = false;
  }
});

If the optional argument is supplied, the prefilter will be only be applied to requests with the indicated dataTypes. For example, the following only applies the given prefilter to JSON and script requests:

$.ajaxPrefilter( "json script", function( options, originalOptions, jqXHR ) {
  // Modify options, control originalOptions, store jqXHR, etc
});

The method can also redirect a request to another dataType by returning that dataType. For example, the following sets a request as "script" if the URL has some specific properties defined in a custom function:

$.ajaxPrefilter(function( options ) {
  if ( isActuallyScript( options.url ) ) {
    return "script";
  }
});

This would ensure not only that the request is considered "script" but also that all the prefilters specifically attached to the script dataType would be applied to it.

Examples:


jQuery.ajaxSetup – jQuery API

Returns: jQuery.ajaxSetup( [ Options ] options )

Categories: Low-Level Interface, Version 1.1
Description: Set default values for future Ajax requests.
  • version added: 1.1
  • jQuery.ajaxSetup( [ Options ] options )
  • options A set of key/value pairs that configure the default Ajax request. All options are optional.

For details on the settings available for , see .

All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of .

For example, the following sets a default for the parameter before pinging the server repeatedly:

$.ajaxSetup({
  url: 'ping.php'
});

Now each time an Ajax request is made, the "ping.php" URL will be used automatically:

$.ajax({
  // url not set here; uses ping.php
  data: {'name': 'Dan'}
});

Examples:

Example:

Sets the defaults for Ajax requests to the url "/xmlhttp/", disables global handlers and uses POST instead of GET. The following Ajax requests then sends some data without having to set anything else.
$.ajaxSetup({
   url: "/xmlhttp/",
   global: false,
   type: "POST"

 });
 $.ajax({ data: myData });


jQuery.ajax – jQuery API

Returns: jqXHRjqXHR jQuery.ajax( [ Map ] settings )

Categories: Low-Level Interface, Version 1.0, Version 1.5, Version 1.5.1
Description: Perform an asynchronous HTTP (Ajax) request.
  • version added: 1.5
  • jQuery.ajax( [ String ] url, [ Map ] settings )
  • url A string containing the URL to which the request is sent.
  • settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with . See below for a complete list of all settings.
  • version added: 1.0
  • jQuery.ajax( [ Map ] settings )
  • settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with .

The function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like and are available and are easier to use. If less common options are required, though, can be used more flexibly.

At its simplest, the function can be called with no arguments:

$.ajax();

Default settings can be set globally by using the function.

This example, using no options, loads the contents of the current page, but does nothing with the result. To use the result, we can implement one of the callback functions.

The jqXHR Object

The jQuery XMLHttpRequest (jqXHR) object returned by is a superset of the browser's native XMLHttpRequest object. For example, it contains and properties, as well as a method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the object simulates native XHR functionality where possible.

, the object also contains the method.

The jqXHR objects returned by implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see for more information). For convenience and consistency with the callback names used by , jqXHR also provides , , and methods. These methods take a function argument that is called when the request terminates, and the function receives the same arguments as the correspondingly-named callback. In jQuery 1.5 this allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.)

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax({ url: "example.php" })
    .success(function() { alert("success"); })
    .error(function() { alert("error"); })
    .complete(function() { alert("complete"); });

// perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });

For backward compatibility with , a object will expose the following properties and methods:

No mechanism is provided, however, since , , and cover all conceivable requirements.

Callback Function Queues

The , , , and options all accept callback functions that are invoked at the appropriate times.

, the , , and callback hooks are first-in, first-out managed queues. This means you can assign more than one callback for each hook. See , which are implemented internally for these callback hooks.

The reference within all callbacks is the object in the option passed to in the settings; if is not specified, is a reference to the Ajax settings themselves.

Some types of Ajax requests, such as JSONP and cross-domain GET requests, do not use XHR; in those cases the and parameters passed to the callback are .

Here are the callback hooks provided by :

For example, to make use of the returned HTML, we can implement a handler:

$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});

Data Types

The function relies on the server to provide information about the retrieved data. If the server reports the return data as XML, the result can be traversed using normal XML methods or jQuery's selectors. If another type is detected, such as HTML in the example above, the data is treated as text.

Different data handling can be achieved by using the option. Besides plain , the can be , , , , or .

The and types return the data with no processing. The data is simply passed on to the success handler, either through the or property of the object, respectively.

We must ensure that the MIME type reported by the web server matches our choice of . In particular, XML must be declared by the server as or for consistent results.

If is specified, any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string. Similarly, will execute the JavaScript that is pulled back from the server, then return nothing.

The type parses the fetched data file as a JavaScript object and returns the constructed object as the result data. To do so, it uses when the browser supports it; otherwise it uses a . Malformed JSON data will throw a parse error (see for more information). JSON data is convenient for communicating structured data in a way that is concise and easy for JavaScript to parse. If the fetched data file exists on a remote server, specify the type instead.

The type appends a query string parameter of to the URL. The server should prepend the JSON data with the callback name to form a valid JSONP response. We can specify a parameter name other than with the option to .

JSONP is an extension of the JSON format, requiring some server-side code to detect and handle the query string parameter. More information about it can be found in the .

When data is retrieved from remote servers (which is only possible using the or data types), the callbacks and global events will never be fired.

Sending Data to the Server

By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the option. This option affects how the contents of the option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.

The option can contain either a query string of the form , or a map of the form . If the latter form is used, the data is converted into a query string using before it is sent. This processing can be circumvented by setting to . The processing might be undesirable if you wish to send an XML object to the server; in this case, change the option from to a more appropriate MIME type.

Advanced Options

The option prevents handlers registered using , , and similar methods from firing when this request would trigger them. This can be useful to, for example, suppress a loading indicator that was implemented with if the requests are frequent and brief. With cross-domain script and JSONP requests, the global option is automatically set to . See the descriptions of these methods below for more details. See the descriptions of these methods below for more details.

If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the and options.

Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using rather than being overridden for specific requests with the option.

By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set to . To cause the request to report failure if the asset has not been modified since the last request, set to .

The allows the character set to be explicitly specified for requests that use a tag (that is, a type of or ). This is useful if the script and host page have differing character sets.

The first letter in Ajax stands for "asynchronous," meaning that the operation occurs in parallel and the order of completion is not guaranteed. The option to defaults to , indicating that code execution can continue after the request is made. Setting this option to (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.

The function returns the object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the option. The returned object can generally be discarded, but does provide a lower-level interface for observing and manipulating the request. In particular, calling on the object will halt the request before it completes.

Extending Ajax

, jQuery's Ajax implementation includes prefilters, converters, and transports that allow you to extend Ajax with a great deal of flexibility. For more information about these advanced features, see the page.

Examples:

Example:

Load and execute a JavaScript file.
$.ajax({
   type: "GET",
   url: "test.js",
   dataType: "script"
 });

Example:

Save some data to the server and notify the user once it's complete.
$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });

Example:

Retrieve the latest version of an HTML page.
$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  }
});

Example:

Loads data synchronously. Blocks the browser while the requests is active. It is better to block user interaction by other means when synchronization is necessary.
var html = $.ajax({
  url: "some.php",
  async: false
 }).responseText;

Example:

Sends an xml document as data to the server. By setting the processData option to , the automatic conversion of data to strings is prevented.
var xmlDocument = [create xml document];
 $.ajax({
   url: "page.php",
   processData: false,
   data: xmlDocument,
   success: handleResponse
 });

Example:

Sends an id as data to the server, save some data to the server and notify the user once it's complete.
bodyContent = $.ajax({
      url: "script.php",
      global: false,
      type: "POST",
      data: ({id : this.getAttribute('id')}),
      dataType: "html",
      async:false,
      success: function(msg){
         alert(msg);
      }
   }
).responseText;


Shorthand Methods – jQuery API

Shorthand Methods

  • jqXHR jQuery.post( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP POST request.

  • XMLHttpRequest jQuery.getScript( [ String ] url, [ Function ] success(data, textStatus) )

    New in 1.0 !

    Load a JavaScript file from the server using a GET HTTP request, then execute it.

  • jqXHR jQuery.getJSON( [ String ] url, [ Map ] data, [ Function ] success(data, textStatus, jqXHR) )

    New in 1.0 !

    Load JSON-encoded data from the server using a GET HTTP request.

  • jqXHR jQuery.get( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP GET request.

  • jQuery .load( [ String ] url, [ Map | String ] data, [ Function ] complete(responseText, textStatus, XMLHttpRequest) )

    New in 1.0 !

    Load data from the server and place the returned HTML into the matched element.


jQuery.post – jQuery API

Returns: jqXHRjqXHR jQuery.post( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

Categories: Shorthand Methods, Version 1.0, Version 1.5
Description: Load data from the server using a HTTP POST request.
  • version added: 1.0
  • jQuery.post( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )
  • url A string containing the URL to which the request is sent.
  • data A map or string that is sent to the server with the request.
  • success(data, textStatus, jqXHR) A callback function that is executed if the request succeeds.
  • dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  type: 'POST',
  url: ,
  data: ,
  success:
  dataType:
});

The callback function is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response. It is also passed the text status of the response.

, the callback function is also passed a (in , it was passed the object).

Most implementations will specify a success handler:

$.post('ajax/test.html', function(data) {
  $('.result').html(data);
});

This example fetches the requested HTML snippet and inserts it on the page.

Pages fetched with are never cached, so the and options in have no effect on these requests.

The jqXHR Object

, all of jQuery's Ajax methods return a superset of the object. This jQuery XHR object, or "jqXHR," returned by implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see for more information). For convenience and consistency with the callback names used by , it provides , , and methods. These methods take a function argument that is called when the request terminates, and the function receives the same arguments as the correspondingly-named callback.

The Promise interface in jQuery 1.5 also allows jQuery's Ajax methods, including , to chain multiple , , and callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

// Assign handlers immediately after making the request,
    // and remember the jqxhr object for this request
    var jqxhr = $.post("example.php", function() {
      alert("success");
    })
    .success(function() { alert("second success"); })
    .error(function() { alert("error"); })
    .complete(function() { alert("complete"); });

    // perform other work here ...

    // Set another completion function for the request above
    jqxhr.complete(function(){ alert("second complete"); });

Examples:

Example:

Request the test.php page, but ignore the return results.
$.post("test.php");

Example:

Request the test.php page and send some additional data along (while still ignoring the return results).
$.post("test.php", { name: "John", time: "2pm" } );

Example:

pass arrays of data to the server (while still ignoring the return results).
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

Example:

send form data using ajax requests
$.post("test.php", $("#testform").serialize());

Example:

Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.post("test.php", function(data) {
   alert("Data Loaded: " + data);
 });

Example:

Alert out the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).
$.post("test.php", { name: "John", time: "2pm" },
   function(data) {
     alert("Data Loaded: " + data);
   });

Example:

Gets the test.php page content, store it in a XMLHttpResponse object and applies the process() JavaScript function.
$.post("test.php", { name: "John", time: "2pm" },
 function(data) {
   process(data);
 },
 "xml"
);

Example:

Posts to the test.php page and gets contents which has been returned in json format ("John","time"=>"2pm")); ?>).
$.post("test.php", { "func": "getNameAndTime" },
 function(data){
   alert(data.name); // John
   console.log(data.time); //  2pm
 }, "json");

Example:

Post a form using ajax and put results in a div
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <form action="/" id="searchForm">
   <input type="text" name="s" placeholder="Search..." />
   <input type="submit" value="Search" />
  </form>
  <!-- the result of the search will be rendered inside this div -->
  <div id="result"></div>

  <script>// attach a submit handler to the form
  $("#searchForm").submit(function(event) {

    // stop form from submitting normally
    event.preventDefault();

    // get some values from elements on the page:
    var $form = $( this ),
        term = $form.find( 'input[name="s"]' ).val(),
        url = $form.attr( 'action' );

    // Send the data using post and put the results in a div
    $.post( url, { s: term } ,
      function( data ) {
          var content = $( data ).find( '#content' );
          $( "#result" ).html( content );
      }
    );
  });</script>
</body>
</html>

Demo:


jQuery.getScript – jQuery API

Returns: XMLHttpRequestXMLHttpRequest jQuery.getScript( [ String ] url, [ Function ] success(data, textStatus) )

Categories: Shorthand Methods, Version 1.0, Version 1.5
Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.
  • version added: 1.0
  • jQuery.getScript( [ String ] url, [ Function ] success(data, textStatus) )
  • url A string containing the URL to which the request is sent.
  • success(data, textStatus) A callback function that is executed if the request succeeds.

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: ,
  dataType: 'script',
  success:
});

The callback is passed the returned JavaScript file. This is generally not useful as the script will already have run at this point.

The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts should have some impact on the current page:

$('.result').html('<p>Lorem ipsum dolor sit amet.</p>');

The script can then be included and run by referencing the file name:

$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});

Examples:

Example:

Load the dynamically and bind some color animations to occur once the new functionality is loaded.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>.block {
   background-color: blue;
   width: 150px;
   height: 70px;
   margin: 10px;
}</style>
</head>
<body>
  <button id="go">&raquo; Run</button>

<div class="block"></div>

  <script>$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: 'pink' }, 1000)
      .animate( { backgroundColor: 'blue' }, 1000);
  });
});</script>
</body>
</html>

Demo:

Example:

Load the test.js JavaScript file and execute it.
$.getScript("test.js");

Example:

Load the test.js JavaScript file and execute it, displaying an alert message when the execution is complete.
$.getScript("test.js", function(){
   alert("Script loaded and executed.");
 });


jQuery.getJSON – jQuery API

Returns: jqXHRjqXHR jQuery.getJSON( [ String ] url, [ Map ] data, [ Function ] success(data, textStatus, jqXHR) )

Categories: Shorthand Methods, Version 1.0, Version 1.5
Description: Load JSON-encoded data from the server using a GET HTTP request.
  • version added: 1.0
  • jQuery.getJSON( [ String ] url, [ Map ] data, [ Function ] success(data, textStatus, jqXHR) )
  • url A string containing the URL to which the request is sent.
  • data A map or string that is sent to the server with the request.
  • success(data, textStatus, jqXHR) A callback function that is executed if the request succeeds.

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: ,
  dataType: 'json',
  data: ,
  success:
});

Data that is sent to the server is appended to the URL as a query string. If the value of the parameter is an object (map), it is converted to a string and url-encoded before it is appended to the URL.

Most implementations will specify a success handler:

$.getJSON('ajax/test.json', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

This example, of course, relies on the structure of the JSON file:

{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}

Using this structure, the example loops through the requested data, builds an unordered list, and appends it to the body.

The callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the method. It is also passed the text status of the response.

, the callback function receives a (in , it received the object). However, since JSONP and cross-domain GET requests do not use , in those cases the and parameters passed to the success callback are undefined.

JSONP

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the data type in for more details.

The jqXHR Object

, all of jQuery's Ajax methods return a superset of the object. This jQuery XHR object, or "jqXHR," returned by implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see for more information). For convenience and consistency with the callback names used by , it provides , , and methods. These methods take a function argument that is called when the request terminates, and the function receives the same arguments as the correspondingly-named callback.

The Promise interface in jQuery 1.5 also allows jQuery's Ajax methods, including , to chain multiple , , and callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

// perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });

Examples:

Example:

Loads the four most recent cat pictures from the Flickr JSONP API.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>img{ height: 100px; float: left; }</style>
</head>
<body>
  <div id="images">

</div>
  <script>$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "cat",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){
      $("<img/>").attr("src", item.media.m).appendTo("#images");
      if ( i == 3 ) return false;
    });
  });</script>
</body>
</html>

Demo:

Example:

Load the JSON data from test.js and access a name from the returned JSON data.
$.getJSON("test.js", function(json) {
   alert("JSON Data: " + json.users[3].name);
 });

Example:

Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data.
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
    alert("JSON Data: " + json.users[3].name);
    });


jQuery.get – jQuery API

Returns: jqXHRjqXHR jQuery.get( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

Categories: Shorthand Methods, Version 1.0, Version 1.5
Description: Load data from the server using a HTTP GET request.
  • version added: 1.0
  • jQuery.get( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )
  • url A string containing the URL to which the request is sent.
  • data A map or string that is sent to the server with the request.
  • success(data, textStatus, jqXHR) A callback function that is executed if the request succeeds.
  • dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: ,
  data: ,
  success: ,
  dataType:
});

The callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.

, the callback function is also passed a (in , it was passed the object). However, since JSONP and cross-domain GET requests do not use , in those cases the and parameters passed to the success callback are undefined.

Most implementations will specify a success handler:

$.get('ajax/test.html', function(data) {
  $('.result').html(data);
  alert('Load was performed.');
});

This example fetches the requested HTML snippet and inserts it on the page.

The jqXHR Object

, all of jQuery's Ajax methods return a superset of the object. This jQuery XHR object, or "jqXHR," returned by implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see for more information). For convenience and consistency with the callback names used by , it provides , , and methods. These methods take a function argument that is called when the request terminates, and the function receives the same arguments as the correspondingly-named callback.

The Promise interface in jQuery 1.5 also allows jQuery's Ajax methods, including , to chain multiple , , and callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

// Assign handlers immediately after making the request,
  // and remember the jqxhr object for this request
  var jqxhr = $.get("example.php", function() {
    alert("success");
  })
  .success(function() { alert("second success"); })
  .error(function() { alert("error"); })
  .complete(function() { alert("complete"); });

  // perform other work here ...

  // Set another completion function for the request above
  jqxhr.complete(function(){ alert("second complete"); });

Examples:

Example:

Request the test.php page, but ignore the return results.
$.get("test.php");

Example:

Request the test.php page and send some additional data along (while still ignoring the return results).
$.get("test.php", { name: "John", time: "2pm" } );

Example:

pass arrays of data to the server (while still ignoring the return results).
$.get("test.php", { 'choices[]': ["Jon", "Susan"]} );

Example:

Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});

Example:

Alert out the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned).
$.get("test.cgi", { name: "John", time: "2pm" },
   function(data){
     alert("Data Loaded: " + data);
   });

Example:

Gets the test.php page contents which has been returned in json format ("John","time"=>"2pm")); ?>).
$.get("test.php", { "func": "getNameAndTime" },
   function(data){
     alert(data.name); // John
     console.log(data.time); //  2pm
   }, "json");


load – jQuery API

  • load ( [ Function ] handler(eventObject) )

    • 1.0load ( [ Function ] handler(eventObject) )
    • 1.4.3load ( [ Object ] eventData, [ Function ] handler(eventObject) )

  • load ( [ String ] url, [ Map | String ] data, [ Function ] complete(responseText, textStatus, XMLHttpRequest) )

    • 1.0load ( [ String ] url, [ Map | String ] data, [ Function ] complete(responseText, textStatus, XMLHttpRequest) )

Returns: jQueryjQuery .load( [ Object ] eventData, [ Function ] handler(eventObject) )

Categories: Document Loading, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "load" JavaScript event.
  • version added: 1.0
  • .load( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute when the event is triggered.
  • version added: 1.4.3
  • .load( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.

This method is a shortcut for .

The event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the object.

For example, consider a page with a simple image:

<img src="book.png" alt="Book" id="book" />

The event handler can be bound to the image:

$('#book').load(function() {
  // Handler for .load() called.
});

As soon as the image has been loaded, the handler is called.

In general, it is not necessary to wait for all images to be fully loaded. If code can be executed earlier, it is usually best to place it in a handler sent to the method.

Examples:

Example:

Run a function when the page is fully loaded including graphics.
$(window).load(function () {
  // run code
});

Example:

Add the class bigImg to all images with height greater then 100 upon each image load.
$('img.userIcon').load(function(){
  if($(this).height() > 100) {
    $(this).addClass('bigImg');
  }
});

Returns: jQueryjQuery .load( [ String ] url, [ Map | String ] data, [ Function ] complete(responseText, textStatus, XMLHttpRequest) )

Categories: Shorthand Methods, Version 1.0
Description: Load data from the server and place the returned HTML into the matched element.
  • version added: 1.0
  • .load( [ String ] url, [ Map | String ] data, [ Function ] complete(responseText, textStatus, XMLHttpRequest) )
  • url A string containing the URL to which the request is sent.
  • data A map or string that is sent to the server with the request.
  • complete(responseText, textStatus, XMLHttpRequest) A callback function that is executed when the request completes.

This method is the simplest way to fetch data from the server. It is roughly equivalent to except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when is "success" or "notmodified"), sets the HTML contents of the matched element to the returned data. This means that most uses of the method can be quite simple:

$('#result').load('ajax/test.html');

The provided callback, if any, is executed after this post-processing has been performed:

$('#result').load('ajax/test.html', function() {
  alert('Load was performed.');
});

In the two examples above, if the current document does not contain an element with an ID of "result," the method is not executed.

The POST method is used if data is provided as an object; otherwise, GET is assumed.

Loading Page Fragments

The method, unlike , allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

$('#result').load('ajax/test.html #container');

When this method executes, it retrieves the content of , but then jQuery parses the returned document to find the element with an ID of . This element, along with its contents, is inserted into the element with an ID of , and the rest of the retrieved document is discarded.

jQuery uses the browser's property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as , , or elements. As a result, the elements retrieved by may not be exactly the same as if the document were retrieved directly by the browser.

Examples:

Example:

Load the main page's footer navigation into an ordered list.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body{ font-size: 12px; font-family: Arial; }</style>
</head>
<body>

<b>Footer navigation:</b>
<ol id="new-nav"></ol>

  <script>$("#new-nav").load("/ #jq-footerNavigation li");</script>
</body>
</html>

Demo:

Example:

Display a notice if the Ajax request encounters an error.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body{ font-size: 12px; font-family: Arial; }</style>
</head>
<body>

<b>Successful Response (should be blank):</b>
<div id="success"></div>
<b>Error Response:</b>
<div id="error"></div>

  <script>$("#success").load("/not-here.php", function(response, status, xhr) {
  if (status == "error") {
    var msg = "Sorry but there was an error: ";
    $("#error").html(msg + xhr.status + " " + xhr.statusText);
  }
});</script>
</body>
</html>

Demo:

Example:

Load the feeds.html file into the div with the ID of feeds.
$("#feeds").load("feeds.html");

Example:

pass arrays of data to the server.
$("#objectID").load("test.php", { 'choices[]': ["Jon", "Susan"] } );

Example:

Same as above, but will POST the additional parameters to the server and a callback that is executed when the server is finished responding.
$("#feeds").load("feeds.php", {limit: 25}, function(){
alert("The last 25 entries in the feed have been loaded");
});


Attributes – jQuery API

Attributes

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.

  • jQuery .html( [ Function ] function(index, oldhtml) )

    New in 1.4 !

    Set the HTML contents of each element in the set of matched elements.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • Boolean .hasClass( [ String ] className )

    New in 1.2 !

    Determine whether any of the matched elements are assigned the given class.

  • jQuery .removeAttr( [ String ] attributeName )

    New in 1.0 !

    Remove an attribute from each element in the set of matched elements.

  • jQuery .attr( [ String ] attributeName, [ Function ] function(index, attr) )

    New in 1.1 !

    Set one or more attributes for the set of matched elements.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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


val – jQuery API

  • val ( )

    • 1.0val ( )

  • val ( [ String ] value )

    • 1.0val ( [ String ] value )
    • 1.4val ( [ Function ] function(index, value) )

Returns: String, ArrayString, Array .val( )

Categories: Attributes, Forms, General Attributes, Version 1.0, Version 1.4
Description: Get the current value of the first element in the set of matched elements.
  • version added: 1.0
  • .val( )

The method is primarily used to get the values of form elements. In the case of elements, the method returns an array containing each selected option.

For selects and checkboxes, you can also use the and selectors to get at values, for example:

$('select.foo option:selected').val();    // get the value from a dropdown select
$('select.foo').val();                    // get the value from a dropdown select even easier
$('input:checkbox:checked').val();        // get the value from a checked checkbox
$('input:radio[name=bar]:checked').val(); // get the value from a set of radio buttons

Examples:

Example:

Get the single value from a single select and an array of values from a multiple select and display their values.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:red; margin:4px; }
  b { color:blue; }</style>
</head>
<body>
  <p></p>
  <select id="single">
    <option>Single</option>
    <option>Single2</option>

  </select>
  <select id="multiple" multiple="multiple">
    <option selected="selected">Multiple</option>
    <option>Multiple2</option>

    <option selected="selected">Multiple3</option>
  </select>
  <script>function displayVals() {
      var singleValues = $("#single").val();
      var multipleValues = $("#multiple").val() || [];
      $("p").html("<b>Single:</b> " +
                  singleValues +
                  " <b>Multiple:</b> " +
                  multipleValues.join(", "));
    }

    $("select").change(displayVals);
    displayVals();</script>
</body>
</html>

Demo:

Example:

Find the value of an input box.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:blue; margin:8px; }</style>
</head>
<body>
  <input type="text" value="some text"/>
  <p></p>
  <script>$("input").keyup(function () {
      var value = $(this).val();
      $("p").text(value);
    }).keyup();</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .val( [ Function ] function(index, value) )

Categories: Attributes, Forms, General Attributes, Version 1.0, Version 1.4
Description: Set the value of each element in the set of matched elements.
  • version added: 1.0
  • .val( [ String ] value )
  • value A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.
  • version added: 1.4
  • .val( [ Function ] function(index, value) )
  • function(index, value) A function returning the value to set.

This method is typically used to set the values of form fields.

Passing an array of element values allows matching , and s inside of n to be selected. In the case of s that are part of a radio group and the other elements will be deselected.

The method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:

$('input:text.items').val(function(index, value) {
  return value + ' ' + this.className;
});

This example appends the string " items" to the text inputs' values.

Examples:

Example:

Set the value of an input box.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>button { margin:4px; cursor:pointer; }
  input { margin:4px; color:blue; }</style>
</head>
<body>
  <div>
    <button>Feed</button>
    <button>the</button>

    <button>Input</button>
  </div>
  <input type="text" value="click a button" />
  <script>$("button").click(function () {
      var text = $(this).text();
      $("input").val(text);
    });</script>
</body>
</html>

Demo:

Example:

Use the function argument to modify the value of an input box.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

  <p>Type something and then click or tab out of the input.</p>
  <input type="text" value="type something" />

  <script>$('input').bind('blur', function() {

    $(this).val(function(i, val) {
      return val.toUpperCase();
    });

  });</script>
</body>
</html>

Demo:

Example:

Set a single select, a multiple select, checkboxes and a radio button .
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { color:blue; }</style>
</head>
<body>
  <select id="single">
    <option>Single</option>
    <option>Single2</option>
  </select>

  <select id="multiple" multiple="multiple">
    <option selected="selected">Multiple</option>
    <option>Multiple2</option>

    <option selected="selected">Multiple3</option>
  </select><br/>
  <input type="checkbox" name="checkboxname" value="check1"/> check1
  <input type="checkbox" name="checkboxname" value="check2"/> check2
  <input type="radio"  name="r" value="radio1"/> radio1
  <input type="radio"  name="r" value="radio2"/> radio2
  <script>$("#single").val("Single2");
    $("#multiple").val(["Multiple2", "Multiple3"]);
    $("input").val(["check1","check2", "radio1" ]);</script>
</body>
</html>

Demo:


html – jQuery API

  • html ( )

    • 1.0html ( )

  • html ( [ String ] htmlString )

    • 1.0html ( [ String ] htmlString )
    • 1.4html ( [ Function ] function(index, oldhtml) )

Returns: StringString .html( )

Categories: Attributes, DOM Insertion, Inside, Version 1.0, Version 1.4
Description: Get the HTML contents of the first element in the set of matched elements.
  • version added: 1.0
  • .html( )

This method is not available on XML documents.

In an HTML document, can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have it's HTML content returned. Consider this code:

$('div.demo-container').html();

In order for the following 's content to be retrieved, it would have to be the first one with in the document:

<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
</div>

The result would look like this:

<div class="demo-box">Demonstration Box</div>

This method uses the browser's property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.

Examples:

Example:

Click a paragraph to convert it from html to text.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin:8px; font-size:20px; color:blue;
      cursor:pointer; }
  b { text-decoration:underline; }
  button { cursor:pointer; }</style>
</head>
<body>
  <p>

    <b>Click</b> to change the <span id="tag">html</span>
  </p>
  <p>

    to a <span id="text">text</span> node.
  </p>
  <p>
    This <button name="nada">button</button> does nothing.
  </p>
  <script>$("p").click(function () {
      var htmlStr = $(this).html();
      $(this).text(htmlStr);
    });</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .html( [ Function ] function(index, oldhtml) )

Categories: Attributes, DOM Insertion, Inside, Version 1.0, Version 1.4
Description: Set the HTML contents of each element in the set of matched elements.
  • version added: 1.0
  • .html( [ String ] htmlString )
  • htmlString A string of HTML to set as the content of each matched element.
  • version added: 1.4
  • .html( [ Function ] function(index, oldhtml) )
  • function(index, oldhtml) A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content.

The method is not available in XML documents.

When is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:

<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
</div>

The content of can be set like this:

$('div.demo-container')
  .html('<p>All new content. <em>You bet!</em></p>');

That line of code will replace everything inside :

<div class="demo-container">
  <p>All new content. <em>You bet!</em></p>
</div>

As of jQuery 1.4, the method allows the HTML content to be set by passing in a function.

$('div.demo-container').html(function() {
  var emph = '<em>' + $('p').length + ' paragraphs!</em>';
  return '<p>All new content for ' + emph + '</p>';
});

Given a document with six paragraphs, this example will set the HTML of to .

This method uses the browser's property. Some browsers may not generate a DOM that exactly replicates the HTML source provided. For example, Internet Explorer prior to version 8 will convert all properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate .

Examples:

Example:

Add some html to each div.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>.red { color:red; }</style>
</head>
<body>
  <span>Hello</span>
  <div></div>
  <div></div>
  <div></div>
  <script>$("div").html("<span class='red'>Hello <b>Again</b></span>");</script>
</body>
</html>

Demo:

Example:

Add some html to each div then immediately do further manipulations to the inserted html.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:blue; font-size:18px; }</style>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>
  <script>$("div").html("<b>Wow!</b> Such excitement...");
    $("div b").append(document.createTextNode("!!!"))
              .css("color", "red");</script>
</body>
</html>

Demo:


toggleClass – jQuery API

Returns: jQueryjQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

Categories: Attributes, Class Attribute, CSS, Version 1.0, Version 1.3, Version 1.4
Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
  • version added: 1.0
  • .toggleClass( [ String ] className )
  • className One or more class names (separated by spaces) to be toggled for each element in the matched set.
  • version added: 1.3
  • .toggleClass( [ String ] className, [ Boolean ] switch )
  • className One or more class names (separated by spaces) to be toggled for each element in the matched set.
  • switch A boolean value to determine whether the class should be added or removed.
  • version added: 1.4
  • .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )
  • function(index, class) A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set and the old class value as arguments.
  • switch A boolean value to determine whether the class should be added or removed.

This method takes one or more class names as its parameter. In the first version, if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added. For example, we can apply to a simple :

<div class="tumble">Some text.</div>

The first time we apply , we get the following:

<div class="tumble bounce">Some text.</div>

The second time we apply , the class is returned to the single value:

<div class="tumble">Some text.</div>

Applying to the same alternates between and .

The second version of uses the second parameter for determining whether the class should be added or removed. If this parameter's value is , then the class is added; if , the class is removed. In essence, the statement:

$('#foo').toggleClass(className, addOrRemove);

is equivalent to:

if (addOrRemove) {
    $('#foo').addClass(className);
  }
  else {
    $('#foo').removeClass(className);
  }

As of jQuery 1.4, the method allows us to indicate the class name to be toggled by passing in a function.

$('div.foo').toggleClass(function() {
  if ($(this).parent().is('.bar')) {
    return 'happy';
  } else {
    return 'sad';
  }
});

This example will toggle the class for elements if their parent element has a class of ; otherwise, it will toggle the class.

Examples:

Example:

Toggle the class 'highlight' when a paragraph is clicked.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin: 4px; font-size:16px; font-weight:bolder;
      cursor:pointer; }
  .blue { color:blue; }
  .highlight { background:yellow; }</style>
</head>
<body>
  <p class="blue">Click to toggle</p>
  <p class="blue highlight">highlight</p>
  <p class="blue">on these</p>
  <p class="blue">paragraphs</p>
  <script>$("p").click(function () {
      $(this).toggleClass("highlight");
    });</script>
</body>
</html>

Demo:

Example:

Add the "highlight" class to the clicked paragraph on every third click of that paragraph, remove it every first and second click.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin: 4px; font-size:16px; font-weight:bolder;
      cursor:pointer; }
  .blue { color:blue; }
  .highlight { background:red; }</style>
</head>
<body>
  <p class="blue">Click to toggle (<span>clicks: 0</span>)</p>
  <p class="blue highlight">highlight (<span>clicks: 0</span>)</p>
  <p class="blue">on these (<span>clicks: 0</span>)</p>

  <p class="blue">paragraphs (<span>clicks: 0</span>)</p>
  <script>var count = 0;
$("p").each(function() {
  var $thisParagraph = $(this);
  var count = 0;
  $thisParagraph.click(function() {
    count++;
    $thisParagraph.find("span").text('clicks: ' + count);
    $thisParagraph.toggleClass("highlight", count % 3 == 0);
  });
});</script>
</body>
</html>

Demo:


removeClass – jQuery API

Returns: jQueryjQuery .removeClass( [ Function ] function(index, class) )

Categories: Attributes, Class Attribute, CSS, Version 1.0, Version 1.4
Description: Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
  • version added: 1.0
  • .removeClass( [ String ] className )
  • className A class name to be removed from the class attribute of each matched element.
  • version added: 1.4
  • .removeClass( [ Function ] function(index, class) )
  • function(index, class) A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments.

If a class name is included as a parameter, then only that class will be removed from the set of matched elements. If no class names are specified in the parameter, all classes will be removed.

More than one class may be removed at a time, separated by a space, from the set of matched elements, like so:

$('p').removeClass('myClass yourClass')

This method is often used with to switch elements' classes from one to another, like so:

$('p').removeClass('myClass noClass').addClass('yourClass');

Here, the and classes are removed from all paragraphs, while is added.

To replace all existing classes with another class, we can use instead.

As of jQuery 1.4, the method allows us to indicate the class to be removed by passing in a function.

$('li:last').removeClass(function() {
          return $(this).prev().attr('class');
        });

This example removes the class name of the penultimate from the last .

Examples:

Example:

Remove the class 'blue' from the matched elements.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin: 4px; font-size:16px; font-weight:bolder; }
  .blue { color:blue; }
  .under { text-decoration:underline; }
  .highlight { background:yellow; }</style>
</head>
<body>
  <p class="blue under">Hello</p>
  <p class="blue under highlight">and</p>
  <p class="blue under">then</p>

  <p class="blue under">Goodbye</p>
  <script>$("p:even").removeClass("blue");</script>
</body>
</html>

Demo:

Example:

Remove the class 'blue' and 'under' from the matched elements.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin: 4px; font-size:16px; font-weight:bolder; }
  .blue { color:blue; }
  .under { text-decoration:underline; }
  .highlight { background:yellow; }</style>
</head>
<body>
  <p class="blue under">Hello</p>

  <p class="blue under highlight">and</p>
  <p class="blue under">then</p>
  <p class="blue under">Goodbye</p>
  <script>$("p:odd").removeClass("blue under");</script>
</body>
</html>

Demo:

Example:

Remove all the classes from the matched elements.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin: 4px; font-size:16px; font-weight:bolder; }
  .blue { color:blue; }
  .under { text-decoration:underline; }
  .highlight { background:yellow; }</style>
</head>
<body>
  <p class="blue under">Hello</p>
  <p class="blue under highlight">and</p>
  <p class="blue under">then</p>

  <p class="blue under">Goodbye</p>
  <script>$("p:eq(1)").removeClass();</script>
</body>
</html>

Demo:


hasClass – jQuery API

Returns: BooleanBoolean .hasClass( [ String ] className )

Categories: Attributes, Class Attribute, CSS, Version 1.2
Description: Determine whether any of the matched elements are assigned the given class.
  • version added: 1.2
  • .hasClass( [ String ] className )
  • className The class name to search for.

Elements may have more than one class assigned to them. In HTML, this is represented by separating the class names with a space:

<div id="mydiv" class="foo bar"></div>

The method will return if the class is assigned to an element, even if other classes also are. For example, given the HTML above, the following will return :

$('#mydiv').hasClass('foo')

As would:

$('#mydiv').hasClass('bar')

While this would return :

$('#mydiv').hasClass('quux')

Examples:

Example:

Looks for the paragraph that contains 'selected' as a class.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin: 8px; font-size:16px; }
  .selected { color:red; }</style>
</head>
<body>

  <p>This paragraph is black and is the first paragraph.</p>
  <p class="selected">This paragraph is red and is the second paragraph.</p>

  <div id="result1">First paragraph has selected class: </div>
  <div id="result2">Second paragraph has selected class: </div>
  <div id="result3">At least one paragraph has selected class: </div>
  <script>$("div#result1").append($("p:first").hasClass("selected").toString());
$("div#result2").append($("p:last").hasClass("selected").toString());
$("div#result3").append($("p").hasClass("selected").toString());</script>
</body>
</html>

Demo:


removeAttr – jQuery API

Returns: jQueryjQuery .removeAttr( [ String ] attributeName )

Categories: Attributes, General Attributes, Version 1.0, Version 1.4
Description: Remove an attribute from each element in the set of matched elements.
  • version added: 1.0
  • .removeAttr( [ String ] attributeName )
  • attributeName An attribute to remove.

The method uses the JavaScript function, but it has the advantage of being able to be called directly on a jQuery object and it accounts for different attribute naming across browsers.

Examples:

Example:

Clicking the button enables the input next to it.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <button>Enable</button>
<input type="text" disabled="disabled" value="can't edit this" />
  <script>$("button").click(function () {
  $(this).next().removeAttr("disabled")
  .focus()
  .val("editable now");
});</script>
</body>
</html>

Demo:


attr – jQuery API

  • attr ( [ String ] attributeName )

    • 1.0attr ( [ String ] attributeName )

  • attr ( [ String ] attributeName, [ String,Number ] value )

    • 1.0attr ( [ String ] attributeName, [ String,Number ] value )
    • 1.0attr ( [ Map ] map )
    • 1.1attr ( [ String ] attributeName, [ Function ] function(index, attr) )

Returns: StringString .attr( [ String ] attributeName )

Categories: Attributes, General Attributes, Version 1.0, Version 1.1
Description: Get the value of an attribute for the first element in the set of matched elements.
  • version added: 1.0
  • .attr( [ String ] attributeName )
  • attributeName The name of the attribute to get.

The method gets the attribute value for only the element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's or method.

Using jQuery's method to get the value of an element's attribute has two main benefits:

The method returns for the value of an attribute that has not been set.

Examples:

Example:

Find the title attribute of the first in the page.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>em { color:blue; font-weight;bold; }
  div { color:red; }</style>
</head>
<body>

<p>
  Once there was a <em title="huge, gigantic">large</em> dinosaur...
</p>

  The title of the emphasis is:<div></div>

  <script>var title = $("em").attr("title");
  $("div").text(title);</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .attr( [ String ] attributeName, [ Function ] function(index, attr) )

Categories: Attributes, General Attributes, Version 1.0, Version 1.1
Description: Set one or more attributes for the set of matched elements.
  • version added: 1.0
  • .attr( [ String ] attributeName, [ String,Number ] value )
  • attributeName The name of the attribute to set.
  • value A value to set for the attribute.
  • version added: 1.0
  • .attr( [ Map ] map )
  • map A map of attribute-value pairs to set.
  • version added: 1.1
  • .attr( [ String ] attributeName, [ Function ] function(index, attr) )
  • attributeName The name of the attribute to set.
  • function(index, attr) A function returning the value to set. is the current element. Receives the index position of the element in the set and the old attribute value as arguments.

The method is a convenient way to set the value of attributes—especially when setting multiple attributes or using values returned by a function. Consider the following image:

<img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />

Setting a simple attribute

To change the attribute, simply pass the name of the attribute and its new value to the method:

$('#greatphoto').attr('alt', 'Beijing Brush Seller');

an attribute the same way:

$('#greatphoto')
.attr('title', 'Photo by Kelly Clark');

Setting several attributes at once

To change the attribute and add the attribute at the same time, pass both sets of names and values into the method at once using a map (JavaScript object literal). Each key-value pair in the map adds or modifies an attribute:

$('#greatphoto').attr({
  alt: 'Beijing Brush Seller',
  title: 'photo by Kelly Clark'
});

When setting multiple attributes, the quotes around attribute names are optional.

: When setting the 'class' attribute, you must always use quotes!

: Internet Explorer does not allow you to change the attribute of an or element.

Computed attribute values

By using a function to set attributes, you can compute the value based on other properties of the element. For example, to concatenate a new value with an existing value:

$('#greatphoto').attr('title', function(i, val) {
  return val + ' - photo by Kelly Clark'
});

This use of a function to compute attribute values can be particularly useful when modifying the attributes of multiple elements at once.

Examples:

Example:

Set some attributes for all [image] s in the page.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>img { padding:10px; }
  div { color:red; font-size:24px; }</style>
</head>
<body>

  <img />
  <img />
  <img />

  <div><B>Attribute of Ajax</B></div>

  <script>$("img").attr({
  src: "/images/hat.gif",
  title: "jQuery",
  alt: "jQuery Logo"
});
$("div").text($("img").attr("alt"));</script>
</body>
</html>

Demo:

Example:

Disable buttons greater than the 1st button.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>button { margin:10px; }</style>
</head>
<body>

  <button>0th Button</button>
  <button>1st Button</button>
  <button>2nd Button</button>

  <script>$("button:gt(1)").attr("disabled","disabled");</script>
</body>
</html>

Demo:

Example:

Set the id for divs based on the position in the page.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:blue; }
  span { color:red; }
  b { font-weight:bolder; }</style>
</head>
<body>

  <div>Zero-th <span></span></div>
  <div>First <span></span></div>
  <div>Second <span></span></div>

  <script>$("div").attr("id", function (arr) {
  return "div-id" + arr;
})
.each(function () {
  $("span", this).html("(ID = '<b>" + this.id + "</b>')");
});</script>
</body>
</html>

Demo:

Example:

Set the src attribute from title attribute on the image.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

<img title="hat.gif"/>

  <script>$("img").attr("src", function() {
    return "/images/" + this.title;
});</script>
</body>
</html>

Demo:


addClass – jQuery API

Returns: jQueryjQuery .addClass( [ Function ] function(index, currentClass) )

Categories: Attributes, Class Attribute, CSS, Version 1.0, Version 1.4
Description: Adds the specified class(es) to each of the set of matched elements.
  • version added: 1.0
  • .addClass( [ String ] className )
  • className One or more class names to be added to the class attribute of each matched element.
  • version added: 1.4
  • .addClass( [ Function ] function(index, currentClass) )
  • function(index, currentClass) A function returning one or more space-separated class names to be added. Receives the index position of the element in the set and the old class value as arguments.

It's important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements.

More than one class may be added at a time, separated by a space, to the set of matched elements, like so:

$("p").addClass("myClass yourClass");

This method is often used with to switch elements' classes from one to another, like so:

$("p").removeClass("myClass noClass").addClass("yourClass");

Here, the and classes are removed from all paragraphs, while is added.

As of jQuery 1.4, the method's argument can receive a function.

$("ul li:last").addClass(function() {
  return "item-" + $(this).index();
});

Given an unordered list with five elements, this example adds the class "item-4" to the last .

Examples:

Example:

Adds the class "selected" to the matched elements.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin: 8px; font-size:16px; }
  .selected { color:blue; }
  .highlight { background:yellow; }</style>
</head>
<body>

  <p>Hello</p>
  <p>and</p>
  <p>Goodbye</p>

  <script>$("p:last").addClass("selected");</script>
</body>
</html>

Demo:

Example:

Adds the classes "selected" and "highlight" to the matched elements.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin: 8px; font-size:16px; }
  .selected { color:red; }
  .highlight { background:yellow; }</style>
</head>
<body>
  <p>Hello</p>
  <p>and</p>
  <p>Goodbye</p>
  <script>$("p:last").addClass("selected highlight");</script>
</body>
</html>

Demo:

Example:

Pass in a function to to add the "green" class to a div that already has a "red" class.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { background: white; }
  .red { background: red; }
  .red.green { background: green; }</style>
</head>
<body>

 <div>This div should be white</div>
 <div class="red">This div will be green because it now has the "green" class.
   It would be red if the addClass function failed.</div>
 <div>This div should be white</div>
 <p>There are zero green divs</p>

  <script>$("div").addClass(function(index, currentClass) {
    var addedClass;

    if ( currentClass === "red" ) {
      addedClass = "green";
      $("p").text("There is one green div");
    }

    return addedClass;
  });</script>
</body>
</html>

Demo:


Core – jQuery API

Core

  • Promise jQuery.when( [ Deferred ] deferreds )

    New in 1.5 !

    Provides a way to execute callback functions based on one or more objects, usually objects that represent asynchronous events.

  • jQuery jQuery.sub( )

    New in 1.5 !

    Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.

  • Object jQuery.noConflict( [ Boolean ] removeAll )

    New in 1.0 !

    Relinquish jQuery's control of the variable.

  • jQuery jQuery( [ Function ] callback )

    New in 1.0 !

    Binds a function to be executed when the DOM has finished loading.


jQuery.when – jQuery API

Returns: PromisePromise jQuery.when( [ Deferred ] deferreds )

Categories: Core, Version 1.5
Description: Provides a way to execute callback functions based on one or more objects, usually objects that represent asynchronous events.
  • version added: 1.5
  • jQuery.when( [ Deferred ] deferreds )
  • deferreds One or more Deferred objects, or plain JavaScript objects.

If a single Deferred is passed to , its Promise object (a subset of the Deferred methods) is returned by the method. Additional methods of the Promise object can be called to attach callbacks, such as . When the Deferred is resolved or rejected, usually by the code that created the Deferred originally, the appropriate callbacks will be called. For example, the jqXHR object returned by is a Deferred and can be used this way:

$.when( $.ajax("test.aspx") ).then(function(ajaxArgs){
     alert(ajaxArgs[1]); /* ajaxArgs is [ "success", statusText, jqXHR ] */
});

If a single argument is passed to and it is not a Deferred, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately. The doneCallbacks are passed the original argument. In this case any failCallbacks you might set are never called since the Deferred is never rejected. For example:

$.when( { testing: 123 } ).done(
   function(x){ alert(x.testing); } /* alerts "123" */
);

In the case where multiple Deferred objects are passed to , the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed. The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of the Deferreds is rejected. If the master Deferred is resolved, it is passed the resolved values of all the Deferreds that were passed to . For example, when the Deferreds are requests, the arguments will be the jqXHR objects for the requests, in the order they were given in the argument list.

In the multiple-Deferreds case where one of the Deferreds is rejected, immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be unresolved at that point. If you need to perform additional processing for this case, such as canceling any unfinished ajax requests, you can keep references to the underlying jqXHR objects in a closure and inspect/cancel them in the failCallback.

Examples:

Example:

Execute a function after two ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request).
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1,  a2){
    /* a1 and a2 are arguments resolved for the
        page1 and page2 ajax requests, respectively */
   var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
   if ( /Whip It/.test(jqXHR.responseText) ) {
      alert("First page has 'Whip It' somewhere.");
   }
});

Example:

Execute the function when both ajax requests are successful, or if either one has an error.
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
  .then(myFunc, myFailure);


jQuery.sub – jQuery API

Returns: jQueryjQuery jQuery.sub( )

Categories: Core, Version 1.5
Description: Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.
  • version added: 1.5
  • jQuery.sub( )

There are two specific use cases for which jQuery.sub() was created. The first was for providing a painless way of overriding jQuery methods without completely destroying the original methods and another was for helping to do encapsulation and basic namespacing for jQuery plugins.

Note that jQuery.sub() doesn't attempt to do any sort of isolation - that's not its intention. All the methods on the sub'd version of jQuery will still point to the original jQuery (events bound and triggered will still be through the main jQuery, data will be bound to elements through the main jQuery, Ajax queries and events will run through the main jQuery, etc.).

Note that if you're looking to use this for plugin development you should first consider using something like the jQuery UI widget factory which manages both state and plugin sub-methods. to build a plugin.

The particular use cases of this method can be best described through some examples.

Examples:

Example:

Adding a method to a jQuery sub so that it isn't exposed externally:
(function(){
    var sub$ = jQuery.sub();

    sub$.fn.myCustomMethod = function(){
      return 'just for me';
    };

    sub$(document).ready(function() {
      sub$('body').myCustomMethod() // 'just for me'
    });
  })();

  typeof jQuery('body').myCustomMethod // undefined

Example:

Override some jQuery methods to provide new functionality.
(function() {
  var myjQuery = jQuery.sub();

  myjQuery.fn.remove = function() {
    // New functionality: Trigger a remove event
    this.trigger("remove");

    // Be sure to call the original jQuery remove method
    return jQuery.fn.remove.apply( this, arguments );
  };

  myjQuery(function($) {
    $(".menu").click(function() {
      $(this).find(".submenu").remove();
    });

    // A new remove event is now triggered from this copy of jQuery
    $(document).bind("remove", function(e) {
      $(e.target).parent().hide();
    });
  });
})();

// Regular jQuery doesn't trigger a remove event when removing an element
// This functionality is only contained within the modified 'myjQuery'.

Example:

Create a plugin that returns plugin-specific methods.
(function() {
  // Create a new copy of jQuery using sub()
  var plugin = jQuery.sub();

  // Extend that copy with the new plugin methods
  plugin.fn.extend({
    open: function() {
      return this.show();
    },
    close: function() {
      return this.hide();
    }
  });

  // Add our plugin to the original jQuery
  jQuery.fn.myplugin = function() {
    this.addClass("plugin");

    // Make sure our plugin returns our special plugin version of jQuery
    return plugin( this );
  };
})();

$(document).ready(function() {
  // Call the plugin, open method now exists
  $('#main').myplugin().open();

  // Note: Calling just $("#main").open() won't work as open doesn't exist!
});


jQuery.noConflict – jQuery API

Returns: ObjectObject jQuery.noConflict( [ Boolean ] removeAll )

Categories: Core, Setup Methods, Version 1.0
Description: Relinquish jQuery's control of the variable.
  • version added: 1.0
  • jQuery.noConflict( [ Boolean ] removeAll )
  • removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).

Many JavaScript libraries use as a function or variable name, just as jQuery does. In jQuery's case, is just an alias for , so all functionality is available without using . If we need to use another JavaScript library alongside jQuery, we can return control of back to the other library with a call to :

<script type="text/javascript" src="other_lib.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
  $.noConflict();
  // Code that uses other library's $ can follow here.
</script>

This technique is especially effective in conjunction with the .ready() method's ability to alias the jQuery object, as within callback passed to .ready() we can use $ if we wish without fear of conflicts later:

<script type="text/javascript" src="other_lib.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
  $.noConflict();
  jQuery(document).ready(function($) {
    // Code that uses jQuery's $ can follow here.
  });
  // Code that uses other library's $ can follow here.
</script>

If necessary, we can free up the name as well by passing as an argument to the method. This is rarely necessary, and if we must do this (for example, if we need to use multiple versions of the library on the same page), we need to consider that most plug-ins rely on the presence of the jQuery variable and may not operate correctly in this situation.

Examples:

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

Example:

Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery alias inside the functions scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library.
jQuery.noConflict();
(function($) {
  $(function() {
    // more code using $ as alias to jQuery
  });
})(jQuery);
// other code using $ as an alias to the other library

Example:

You can chain the jQuery.noConflict() with the shorthand ready for a compact code.
jQuery.noConflict()(function(){
    // code using jQuery
});
// other code using $ as an alias to the other library

Example:

Creates a different alias instead of jQuery to use in the rest of the script.
var j = jQuery.noConflict();
// Do something with jQuery
j("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';

Example:

Completely move jQuery to a new namespace in another object.
var dom = {};
dom.query = jQuery.noConflict(true);


jQuery – jQuery API

  • jQuery ( [ selector ] selector, [ Element | jQuery ] context )

    • 1.0jQuery ( [ selector ] selector, [ Element | jQuery ] context )
    • 1.0jQuery ( [ Element ] element )
    • 1.0jQuery ( [ Array ] elementArray )
    • 1.0jQuery ( [ Object ] jQuery object )
    • 1.4jQuery ( )

  • jQuery ( [ String ] html, [ document ] ownerDocument )

    • 1.0jQuery ( [ String ] html, [ document ] ownerDocument )
    • 1.4jQuery ( [ String ] html, [ Object ] props )

  • jQuery ( [ Function ] callback )

    • 1.0jQuery ( [ Function ] callback )

Returns: jQueryjQuery jQuery( )

Categories: Core, Version 1.0, Version 1.4
Description: Accepts a string containing a CSS selector which is then used to match a set of elements.
  • version added: 1.0
  • jQuery( [ selector ] selector, [ Element | jQuery ] context )
  • selector A string containing a selector expression
  • context A DOM Element, Document, or jQuery to use as context
  • version added: 1.0
  • jQuery( [ Element ] element )
  • element A DOM element to wrap in a jQuery object.
  • version added: 1.0
  • jQuery( [ Array ] elementArray )
  • elementArray An array containing a set of DOM elements to wrap in a jQuery object.
  • version added: 1.0
  • jQuery( [ Object ] jQuery object )
  • jQuery object An existing jQuery object to clone.
  • version added: 1.4
  • jQuery( )

In the first formulation listed above, — which can also be written as — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements:

$('div.foo');

Selector Context

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the function. For example, to do a search within an event handler, the search can be restricted like so:

$('div.foo').click(function() {
  $('span', this).addClass('bar');
});

When the search for the span selector is restricted to the context of , only spans within the clicked element will get the additional class.

Internally, selector context is implemented with the method, so is equivalent to .

Using DOM elements

The second and third formulations of this function create a jQuery object using one or more DOM elements that were already selected in some other way. A common use of this facility is to call jQuery methods on an element that has been passed to a callback function through the keyword :

$('div.foo').click(function() {
  $(this).slideUp();
});

This example causes elements to be hidden with a sliding animation when clicked. Because the handler receives the clicked item in the keyword as a bare DOM element, the element must be passed to the function before applying jQuery methods to it.

XML data returned from an Ajax call can be passed to the function so individual elements of the XML structure can be retrieved using and other DOM traversal methods.

$.post('url.xml', function(data) {
  var $child = $(data).find('child');
})

Cloning jQuery Objects

When a jQuery object is passed to the function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.

Returning an Empty Set

As of jQuery 1.4, calling the method with returns an empty jQuery set (with a property of 0). In previous versions of jQuery, this would return a set containing the document node.

Examples:

Example:

Find all p elements that are children of a div element and apply a border to them.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>one</p> <div><p>two</p></div> <p>three</p>
  <script>$("div > p").css("border", "1px solid gray");</script>
</body>
</html>

Demo:

Example:

Find all inputs of type radio within the first form in the document.
$("input:radio", document.forms[0]);

Example:

Find all div elements within an XML document from an Ajax response.
$("div", xml.responseXML);

Example:

Set the background color of the page to black.
$(document.body).css( "background", "black" );

Example:

Hide all the input elements within a form.
$(myForm.elements).hide()

Returns: jQueryjQuery jQuery( [ String ] html, [ Object ] props )

Categories: Core, Version 1.0, Version 1.4
Description: Creates DOM elements on the fly from the provided string of raw HTML.
  • version added: 1.0
  • jQuery( [ String ] html, [ document ] ownerDocument )
  • html A string of HTML to create on the fly. Note that this parses HTML, XML.
  • ownerDocument A document in which the new elements will be created
  • version added: 1.4
  • jQuery( [ String ] html, [ Object ] props )
  • html A string defining a single, standalone, HTML element (e.g.
    or
    ).
  • props An map of attributes, events, and methods to call on the newly-created element.

Creating New Elements

If a string is passed as the parameter to , jQuery examines the string to see if it looks like HTML (i.e., it has somewhere within the string). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements. You can perform any of the usual jQuery methods on this object:

$('<p id="test">My <em>new</em> text</p>').appendTo('body');

When the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's mechanism. In most cases, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in. When the parameter has a single tag, such as or , jQuery creates the element using the native JavaScript function.

When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. For example, Internet Explorer prior to version 8 will convert all properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate .

To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag:

$('<a href="http://jquery.com"></a>');

Alternatively, jQuery allows XML-like tag syntax (with or without a space before the slash):

$('<a/>');

Tags that cannot contain elements may be quick-closed or not:

$('<img />');
$('<input>');

As of jQuery 1.4, the second argument can accept a map consisting of a superset of the properties that can be passed to the method. Furthermore, any can be passed in, and the following jQuery methods can be called: , , , , , , , or . Note that Internet Explorer will not allow you to create an or element and change its type; you must specify the type using for example.

Examples:

Example:

Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup.
$("<div><p>Hello</p></div>").appendTo("body")

Example:

Create some DOM elements.
$("<div/>", {
  "class": "test",
  text: "Click me!",
  click: function(){
    $(this).toggleClass("test");
  }
}).appendTo("body");

Returns: jQueryjQuery jQuery( [ Function ] callback )

Categories: Core, Version 1.0, Version 1.4
Description: Binds a function to be executed when the DOM has finished loading.
  • version added: 1.0
  • jQuery( [ Function ] callback )
  • callback The function to execute when the DOM is ready.

This function behaves just like , in that it should be used to wrap other operations on your page that depend on the DOM being ready. While this function is, technically, chainable, there really isn't much use for chaining against it.

Examples:

Example:

Execute the function when the DOM is ready to be used.
$(function(){
   // Document is ready
 });

Example:

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


CSS – jQuery API

CSS

  • Object jQuery.cssHooks

    New in 1.4.3 !

    Provides a way to hook directly into jQuery to override how particular CSS properties are retrieved or set. Amongst other uses, cssHooks can be used to create custom, browser-normalized properties for CSS3 features such as box-shadows and gradients.

  • Integer .outerWidth( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding and border.

  • Integer .outerHeight( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.

  • Integer .innerWidth( )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding but not border.

  • Integer .innerHeight( )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding but not border.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.

  • jQuery .scrollLeft( [ Number ] value )

    New in 1.2.6 !

    Set the current horizontal position of the scroll bar for each of the set of matched elements.

  • jQuery .scrollTop( [ Number ] value )

    New in 1.2.6 !

    Set the current vertical position of the scroll bar for each of the set of matched elements.

  • Object .position( )

    New in 1.2 !

    Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.

  • jQuery .css( [ Map ] map )

    New in 1.0 !

    Set one or more CSS properties for the set of matched elements.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • Boolean .hasClass( [ String ] className )

    New in 1.2 !

    Determine whether any of the matched elements are assigned the given class.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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


jQuery.cssHooks – jQuery API

Returns: ObjectObject jQuery.cssHooks

Categories: CSS, Version 1.4.3
Description: Provides a way to hook directly into jQuery to override how particular CSS properties are retrieved or set. Amongst other uses, cssHooks can be used to create custom, browser-normalized properties for CSS3 features such as box-shadows and gradients.
  • version added: 1.4.3
  • jQuery.cssHooks

The $.cssHooks object provides a way to define functions for getting and setting particular CSS values. This can also be used to create new cssHooks for normalizing CSS3 properties - eg. Webkit-based browsers such as Google Chrome require you to use -webkit-border-radius to set the border-radius on an element, whilst Firefox require -moz-border-radius.

With a cssHook this can however be normalized to something like 'border-radius' so that only one property needs to be set. In addition to providing fine-grained control over how specific style properties are handled, $.cssHooks also extends the set of properties available to the animate() method.

Examples:

Example:

Defining a new cssHook: defining new cssHooks is very straight-forward and the skeleton template below can be used as a guide to creating your own.
(function($){
//first, check to see if cssHooks are supported
    if ( !$.cssHooks ){
        //if not, output an error message
        alert("jQuery 1.4.3 or above is required for this plugin to work");
        return;
    }

$.cssHooks['someCSSProperty'] = {
        get: function(elem, computed, extra){
            //handle getting the CSS property
        },
        set: function(elem, value){
            //handle setting the CSS value
        }
};
})(jQuery);

Example:

Normalizing vendor-specific CSS properties: as mentioned, cssHooks are commonly used for normalizing vendor-specific CSS3 properties. In order to effectively cater for this, it is necessary to check that the browser supports the property before we can normalize it. We will be demonstrating this with the border-radius feature.
//check if we can access the border radius on the element's style object.
//A value of "" or "undefined" will be returned if the property is not
//supported

var div = document.createElement( "div" );
$.support.borderRadius =
div.style.WebkitBorderRadius === ''? 'WebkitBorderRadius' :
(div.style.MozBorderRadius === ''? 'MozBorderRadius' :
(div.style.borderRadius === ''? 'borderRadius' : false));

Example:

If the above test is now integrated into the the skeleton template provided in the first example, a complete cssHook can be defined as follows:
(function($){
    if ( !$.cssHooks ){
        alert("jQuery 1.4.3+ is needed for this plugin to work");
        return;
    }
    var div = document.createElement( "div" );
    $.support.borderRadius =
    div.style.WebkitBorderRadius === ''? 'WebkitBorderRadius' :
    (div.style.MozBorderRadius === ''? 'MozBorderRadius' :
    (div.style.borderRadius === ''? 'borderRadius'  : false));

    //only set cssHooks for browsers that don't support "borderRadius" natively
    if ( $.support.borderRadius && $.support.borderRadius !== "borderRadius" ){
        $.cssHook.borderRadius = {
           get: function( elem, computed, extra ){
                return $.css( elem, $.support.borderRadius );
           },
           set: function( elem, value){
                elem.style[$.support.borderRadius] = value;
           }
        };
    }
})(jQuery);

Example:

You can then set the border radius (in a supported browser) as follows:
$("#element").css("border-radius", "20px");

Example:

Creating a cssHook for normalizing border images: similar to the example where the border radius was normalized, in the below we apply the same concept to border images. As you can see, in many cases normalization is quite straight-forward to achieve.
(function($){

    if ( !$.cssHooks ){
        alert("jQuery 1.4.3+ is needed for this plugin to work");
        return;
    }
var div = document.createElement( "div" );

    $.support.borderImage =
    div.style.MozBorderImage === '' ? 'MozBorderImage' :
    (div.style.WebkitBorderImage === '' ? 'WebkitBorderImage' :
    (div.style.borderImage === '' ? 'borderImage' : false));

    if ( $.support.borderImage && $.support.borderImage !== "borderImage" ){
        $.cssHooks.borderImage = {
            get: function( elem, computed, extra ) {
                return $.css(elem, $.support.borderImage);
            },
            set: function( elem, value ) {
                elem.style[$.support.borderImage] = value;
            }
        };
    }
    div = null;
})(jQuery);

Example:

Getting your cssHook to work with animate(): to allow your cssHook to be used with .animate() you can simply do the following:
$.fx.step['someCSSProperty'] = function(fx){
        $.cssHooks['someCSSProperty'].set(fx.elem, fx.now + fx.unit);
};

//Note that the above works best for simple numeric value animations
//and more custom //code may be required depending on the complexity
//of what you're trying to achieve.


outerWidth – jQuery API

Returns: IntegerInteger .outerWidth( [ Boolean ] includeMargin )

Categories: CSS, Dimensions, Style Properties, Version 1.2.6
Description: Get the current computed width for the first element in the set of matched elements, including padding and border.
  • version added: 1.2.6
  • .outerWidth( [ Boolean ] includeMargin )
  • includeMargin A Boolean indicating whether to include the element's margin in the calculation.

Returns the width of the element, along with left and right padding, border, and optionally margin, in pixels.

If is omitted or , the padding and border are included in the calculation; if , the margin is also included.

This method is not applicable to and objects; for these, use instead.

Examples:

Example:

Get the outerWidth of a paragraph.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin:10px;padding:5px;border:2px solid #666; }</style>
</head>
<body>
  <p>Hello</p><p></p>
  <script>var p = $("p:first");
$("p:last").text( "outerWidth:" + p.outerWidth()+ " , outerWidth(true):" + p.outerWidth(true) );</script>
</body>
</html>

Demo:


outerHeight – jQuery API

Returns: IntegerInteger .outerHeight( [ Boolean ] includeMargin )

Categories: CSS, Dimensions, Style Properties, Version 1.2.6
Description: Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.
  • version added: 1.2.6
  • .outerHeight( [ Boolean ] includeMargin )
  • includeMargin A Boolean indicating whether to include the element's margin in the calculation.

The top and bottom padding and border are always included in the calculation; if the argument is set to , the margin (top and bottom) is also included.

This method is not applicable to and objects; for these, use instead.

Examples:

Example:

Get the outerHeight of a paragraph.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin:10px;padding:5px;border:2px solid #666; }</style>
</head>
<body>
  <p>Hello</p><p></p>
  <script>var p = $("p:first");
$("p:last").text( "outerHeight:" + p.outerHeight() + " , outerHeight(true):" + p.outerHeight(true) );</script>
</body>
</html>

Demo:


innerWidth – jQuery API

Returns: IntegerInteger .innerWidth( )

Categories: CSS, Dimensions, Style Properties, Version 1.2.6
Description: Get the current computed width for the first element in the set of matched elements, including padding but not border.
  • version added: 1.2.6
  • .innerWidth( )

This method returns the width of the element, including left and right padding, in pixels.

This method is not applicable to and objects; for these, use instead.

Examples:

Example:

Get the innerWidth of a paragraph.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin:10px;padding:5px;border:2px solid #666; }</style>
</head>
<body>
  <p>Hello</p><p></p>
  <script>var p = $("p:first");
$("p:last").text( "innerWidth:" + p.innerWidth() );</script>
</body>
</html>

Demo:


innerHeight – jQuery API

Returns: IntegerInteger .innerHeight( )

Categories: CSS, Dimensions, Style Properties, Version 1.2.6
Description: Get the current computed height for the first element in the set of matched elements, including padding but not border.
  • version added: 1.2.6
  • .innerHeight( )

This method returns the height of the element, including top and bottom padding, in pixels.

This method is not applicable to and objects; for these, use instead.

Examples:

Example:

Get the innerHeight of a paragraph.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin:10px;padding:5px;border:2px solid #666; }</style>
</head>
<body>
  <p>Hello</p><p></p>
  <script>var p = $("p:first");
$("p:last").text( "innerHeight:" + p.innerHeight() );</script>
</body>
</html>

Demo:


width – jQuery API

  • width ( )

    • 1.0width ( )

  • width ( [ String | Number ] value )

    • 1.0width ( [ String | Number ] value )
    • 1.4.1width ( [ Function ] function(index, width) )

Returns: IntegerInteger .width( )

Categories: CSS, Dimensions, Style Properties, Version 1.0, Version 1.4.1
Description: Get the current computed width for the first element in the set of matched elements.
  • version added: 1.0
  • .width( )

The difference between and is that the latter returns a unit-less pixel value (for example, ) while the former returns a value with units intact (for example, ). The method is recommended when an element's width needs to be used in a mathematical calculation.

This method is also able to find the width of the window and document.

$(window).width();   // returns width of browser viewport
$(document).width(); // returns width of HTML document

Note that will always return the content width, regardless of the value of the CSS property.

Examples:

Example:

Show various widths. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { background:yellow; }
  button { font-size:12px; margin:2px; }
  p { width:150px; border:1px red solid; }
  div { color:red; font-weight:bold;  }</style>
</head>
<body>
  <button id="getp">Get Paragraph Width</button>
  <button id="getd">Get Document Width</button>
  <button id="getw">Get Window Width</button>

  <div>&nbsp;</div>
  <p>
    Sample paragraph to test width
  </p>
  <script>function showWidth(ele, w) {
      $("div").text("The width for the " + ele +
                    " is " + w + "px.");
    }
    $("#getp").click(function () {
      showWidth("paragraph", $("p").width());
    });
    $("#getd").click(function () {
      showWidth("document", $(document).width());
    });
    $("#getw").click(function () {
      showWidth("window", $(window).width());
    });</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .width( [ Function ] function(index, width) )

Categories: CSS, Dimensions, Style Properties, Version 1.0, Version 1.4.1
Description: Set the CSS width of each element in the set of matched elements.
  • version added: 1.0
  • .width( [ String | Number ] value )
  • value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).
  • version added: 1.4.1
  • .width( [ Function ] function(index, width) )
  • function(index, width) A function returning the width to set. Receives the index position of the element in the set and the old width as arguments.

When calling , the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit. If a string is provided, however, any valid CSS measurement may be used for the width (such as , , or ). Note that in modern browsers, the CSS width property does not include padding, border, or margin, unless the CSS property is used.

If no explicit unit was specified (like 'em' or '%') then "px" is concatenated to the value.

Note that sets the width of the box in accordance with the CSS property. Changing this property to will cause this function to change the outerWidth of the box instead of the content width.

Examples:

Example:

To set the width of each div on click to 30px plus a color change.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:70px; height:50px; float:left; margin:5px;
        background:red; cursor:pointer; }</style>
</head>
<body>
  <div></div>
  <div>d</div>

  <div>d</div>
  <div>d</div>
  <div>d</div>
  <script>$("div").one('click', function () {
      $(this).width(30)
             .css({cursor:"auto", "background-color":"blue"});
    });</script>
</body>
</html>

Demo:


height – jQuery API

  • height ( )

    • 1.0height ( )

  • height ( [ String | Number ] value )

    • 1.0height ( [ String | Number ] value )
    • 1.4.1height ( [ Function ] function(index, height) )

Returns: IntegerInteger .height( )

Categories: CSS, Dimensions, Style Properties, Version 1.0, Version 1.4.1
Description: Get the current computed height for the first element in the set of matched elements.
  • version added: 1.0
  • .height( )

The difference between and is that the latter returns a unit-less pixel value (for example, ) while the former returns a value with units intact (for example, ). The method is recommended when an element's height needs to be used in a mathematical calculation.

This method is also able to find the height of the window and document.

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

Note that will always return the content height, regardless of the value of the CSS property.

Examples:

Example:

Show various heights. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { background:yellow; }
  button { font-size:12px; margin:2px; }
  p { width:150px; border:1px red solid; }
  div { color:red; font-weight:bold; }</style>
</head>
<body>
  <button id="getp">Get Paragraph Height</button>
  <button id="getd">Get Document Height</button>
  <button id="getw">Get Window Height</button>

  <div>&nbsp;</div>
  <p>
    Sample paragraph to test height
  </p>
  <script>function showHeight(ele, h) {
      $("div").text("The height for the " + ele +
                    " is " + h + "px.");
    }
    $("#getp").click(function () {
      showHeight("paragraph", $("p").height());
    });
    $("#getd").click(function () {
      showHeight("document", $(document).height());
    });
    $("#getw").click(function () {
      showHeight("window", $(window).height());
    });</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .height( [ Function ] function(index, height) )

Categories: CSS, Dimensions, Style Properties, Version 1.0, Version 1.4.1
Description: Set the CSS height of every matched element.
  • version added: 1.0
  • .height( [ String | Number ] value )
  • value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string).
  • version added: 1.4.1
  • .height( [ Function ] function(index, height) )
  • function(index, height) A function returning the height to set. Receives the index position of the element in the set and the old height as arguments.

When calling , the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit. If a string is provided, however, any valid CSS measurement may be used for the height (such as , , or ). Note that in modern browsers, the CSS height property does not include padding, border, or margin.

If no explicit unit was specified (like 'em' or '%') then "px" is concatenated to the value.

Note that sets the height of the box in accordance with the CSS property. Changing this property to will cause this function to change the outerHeight of the box instead of the content height.

Examples:

Example:

To set the height of each div on click to 30px plus a color change.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:50px; height:70px; float:left; margin:5px;
        background:rgb(255,140,0); cursor:pointer; }</style>
</head>
<body>
  <div></div>
  <div></div>

  <div></div>
  <div></div>
  <div></div>
  <script>$("div").one('click', function () {
      $(this).height(30)
             .css({cursor:"auto", backgroundColor:"green"});
    });</script>
</body>
</html>

Demo:


scrollLeft – jQuery API

  • scrollLeft ( )

    • 1.2.6scrollLeft ( )

  • scrollLeft ( [ Number ] value )

    • 1.2.6scrollLeft ( [ Number ] value )

Returns: IntegerInteger .scrollLeft( )

Categories: CSS, Offset, Style Properties, Version 1.2.6
Description: Get the current horizontal position of the scroll bar for the first element in the set of matched elements.
  • version added: 1.2.6
  • .scrollLeft( )

The horizontal scroll position is the same as the number of pixels that are hidden from view above the scrollable area. If the scroll bar is at the very left, or if the element is not scrollable, this number will be .

Examples:

Example:

Get the scrollLeft of a paragraph.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin:10px;padding:5px;border:2px solid #666; }</style>
</head>
<body>
  <p>Hello</p><p></p>
  <script>var p = $("p:first");
            $("p:last").text( "scrollLeft:" + p.scrollLeft() );</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .scrollLeft( [ Number ] value )

Categories: CSS, Offset, Style Properties, Version 1.2.6
Description: Set the current horizontal position of the scroll bar for each of the set of matched elements.
  • version added: 1.2.6
  • .scrollLeft( [ Number ] value )
  • value An integer indicating the new position to set the scroll bar to.

The horizontal scroll position is the same as the number of pixels that are hidden from view above the scrollable area. Setting the positions the horizontal scroll of each matched element.

Examples:

Example:

Set the scrollLeft of a div.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div.demo {
  background:#CCCCCC none repeat scroll 0 0;
  border:3px solid #666666;
  margin:5px;
  padding:5px;
  position:relative;
  width:200px;
  height:100px;
  overflow:auto;
  }
  p { margin:10px;padding:5px;border:2px solid #666;width:1000px;height:1000px; }</style>
</head>
<body>
  <div class="demo"><h1>lalala</h1><p>Hello</p></div>
  <script>$("div.demo").scrollLeft(300);</script>
</body>
</html>

Demo:


scrollTop – jQuery API

  • scrollTop ( )

    • 1.2.6scrollTop ( )

  • scrollTop ( [ Number ] value )

    • 1.2.6scrollTop ( [ Number ] value )

Returns: IntegerInteger .scrollTop( )

Categories: CSS, Offset, Style Properties, Version 1.2.6
Description: Get the current vertical position of the scroll bar for the first element in the set of matched elements.
  • version added: 1.2.6
  • .scrollTop( )

The vertical scroll position is the same as the number of pixels that are hidden from view above the scrollable area. If the scroll bar is at the very top, or if the element is not scrollable, this number will be .

Examples:

Example:

Get the scrollTop of a paragraph.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin:10px;padding:5px;border:2px solid #666; }</style>
</head>
<body>
  <p>Hello</p><p></p>
  <script>var p = $("p:first");
$("p:last").text( "scrollTop:" + p.scrollTop() );</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .scrollTop( [ Number ] value )

Categories: CSS, Offset, Style Properties, Version 1.2.6
Description: Set the current vertical position of the scroll bar for each of the set of matched elements.
  • version added: 1.2.6
  • .scrollTop( [ Number ] value )
  • value An integer indicating the new position to set the scroll bar to.

The vertical scroll position is the same as the number of pixels that are hidden from view above the scrollable area. Setting the positions the vertical scroll of each matched element.

Examples:

Example:

Set the scrollTop of a div.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div.demo {
background:#CCCCCC none repeat scroll 0 0;
border:3px solid #666666;
margin:5px;
padding:5px;
position:relative;
width:200px;
height:100px;
overflow:auto;
}
  p { margin:10px;padding:5px;border:2px solid #666;width:1000px;height:1000px; }</style>
</head>
<body>
  <div class="demo"><h1>lalala</h1><p>Hello</p></div>
  <script>$("div.demo").scrollTop(300);</script>
</body>
</html>

Demo:


position – jQuery API

Returns: ObjectObject .position( )

Categories: CSS, Offset, Style Properties, Version 1.2
Description: Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
  • version added: 1.2
  • .position( )

The method allows us to retrieve the current position of an element . Contrast this with , which retrieves the current position . When positioning a new element near another one and within the same containing DOM element, is the more useful.

Returns an object containing the properties and .

Examples:

Example:

Access the position of the second paragraph:
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { padding: 15px;}
  p { margin-left:10px; }</style>
</head>
<body>

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

  <script>var p = $("p:first");
var position = p.position();
$("p:last").text( "left: " + position.left + ", top: " + position.top );</script>
</body>
</html>

Demo:


offset – jQuery API

  • offset ( )

    • 1.2offset ( )

  • offset ( [ Object ] coordinates )

    • 1.4offset ( [ Object ] coordinates )
    • 1.4offset ( [ Function ] function(index, coords) )

Returns: ObjectObject .offset( )

Categories: CSS, Offset, Style Properties, Version 1.2, Version 1.4
Description: Get the current coordinates of the first element in the set of matched elements, relative to the document.
  • version added: 1.2
  • .offset( )

The method allows us to retrieve the current position of an element . Contrast this with , which retrieves the current position . When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), is the more useful.

returns an object containing the properties and .

Examples:

Example:

Access the offset of the second paragraph:
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin-left:10px; }</style>
</head>
<body>
  <p>Hello</p><p>2nd Paragraph</p>
  <script>var p = $("p:last");
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );</script>
</body>
</html>

Demo:

Example:

Click to see the offset.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin-left:10px; color:blue; width:200px;
    cursor:pointer; }
span { color:red; cursor:pointer; }
div.abs { width:50px; height:50px; position:absolute;
          left:220px; top:35px; background-color:green;
          cursor:pointer; }</style>
</head>
<body>
  <div id="result">Click an element.</div>
<p>
  This is the best way to <span>find</span> an offset.
</p>

<div class="abs">
</div>

  <script>$("*", document.body).click(function (e) {
  var offset = $(this).offset();
  e.stopPropagation();
  $("#result").text(this.tagName + " coords ( " + offset.left + ", " +
                                  offset.top + " )");
});</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .offset( [ Function ] function(index, coords) )

Categories: CSS, Offset, Style Properties, Version 1.2, Version 1.4
Description: Set the current coordinates of every element in the set of matched elements, relative to the document.
  • version added: 1.4
  • .offset( [ Object ] coordinates )
  • coordinates An object containing the properties and , which are integers indicating the new top and left coordinates for the elements.
  • version added: 1.4
  • .offset( [ Function ] function(index, coords) )
  • function(index, coords) A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new and properties.

The setter method allows us to reposition an element. The element's position is specified . If the element's style property is currently , it will be set to to allow for this repositioning.

Examples:

Example:

Set the offset of the second paragraph:
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin-left:10px; }</style>
</head>
<body>
  <p>Hello</p><p>2nd Paragraph</p>
  <script>$("p:last").offset({ top: 10, left: 30 });</script>
</body>
</html>

Demo:


css – jQuery API

  • css ( [ String ] propertyName )

    • 1.0css ( [ String ] propertyName )

  • css ( [ String ] propertyName, [ String | Number ] value )

    • 1.0css ( [ String ] propertyName, [ String | Number ] value )
    • 1.4css ( [ String ] propertyName, [ Function ] function(index, value) )
    • 1.0css ( [ Map ] map )

Returns: StringString .css( [ String ] propertyName )

Categories: CSS, Style Properties, Version 1.0, Version 1.4
Description: Get the value of a style property for the first element in the set of matched elements.
  • version added: 1.0
  • .css( [ String ] propertyName )
  • propertyName A CSS property.

The method is a convenient way to get a style property from the first matched element, especially in light of the different ways browsers access most of those properties (the method in standards-based browsers versus the and properties in Internet Explorer) and the different terms browsers use for certain properties. For example, Internet Explorer's DOM implementation refers to the property as , while W3C standards-compliant browsers refer to it as . The method accounts for such differences, producing the same result no matter which term we use. For example, an element that is floated left will return the string for each of the following three lines:

Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both and .

Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: and , and so on.

Examples:

Example:

To access the background color of a clicked div.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:60px; height:60px; margin:5px; float:left; }</style>
</head>
<body>

<span id="result">&nbsp;</span>
<div style="background-color:blue;"></div>
<div style="background-color:rgb(15,99,30);"></div>

<div style="background-color:#123456;"></div>
<div style="background-color:#f11;"></div>
  <script>$("div").click(function () {
  var color = $(this).css("background-color");
  $("#result").html("That div is <span style='color:" +
                     color + ";'>" + color + "</span>.");
});</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .css( [ Map ] map )

Categories: CSS, Style Properties, Version 1.0, Version 1.4
Description: Set one or more CSS properties for the set of matched elements.
  • version added: 1.0
  • .css( [ String ] propertyName, [ String | Number ] value )
  • propertyName A CSS property name.
  • value A value to set for the property.
  • version added: 1.4
  • .css( [ String ] propertyName, [ Function ] function(index, value) )
  • propertyName A CSS property name.
  • function(index, value) A function returning the value to set. Receives the index position of the element in the set and the old value as arguments.
  • version added: 1.0
  • .css( [ Map ] map )
  • map A map of property-value pairs to set.

As with the method, the method makes setting properties of elements quick and easy. This method can take either a property name and value as separate parameters, or a single map of key-value pairs (JavaScript object notation).

Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both and . Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name.

When using as a setter, jQuery modifies the element's property. For example, is equivalent to . Setting the value of a style property to an empty string — e.g. — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's method, or through direct DOM manipulation of the property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or element.

As of jQuery 1.4, allows us to pass a function as the property value:

$('div.example').css('width', function(index) {
  return index * 50;
});

This example sets the widths of the matched elements to incrementally larger values.

Examples:

Example:

To change the color of any paragraph to red on mouseover event.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:blue; width:200px; font-size:14px; }</style>
</head>
<body>

  <p>Just roll the mouse over me.</p>

  <p>Or me to see a color change.</p>

  <script>$("p").mouseover(function () {
    $(this).css("color","red");
  });</script>
</body>
</html>

Demo:

Example:

To highlight a clicked word in the paragraph.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:blue; font-weight:bold; cursor:pointer; }</style>
</head>
<body>

<p>
  Once upon a time there was a man
  who lived in a pizza parlor. This
  man just loved pizza and ate it all
  the time.  He went on to be the
  happiest man in the world.  The end.
</p>
  <script>var words = $("p:first").text().split(" ");
  var text = words.join("</span> <span>");
  $("p:first").html("<span>" + text + "</span>");
  $("span").click(function () {
    $(this).css("background-color","yellow");
  });</script>
</body>
</html>

Demo:

Example:

To set the color of all paragraphs to red and background to blue:
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:green; }</style>
</head>
<body>

  <p>Move the mouse over a paragraph.</p>
  <p>Like this one or the one above.</p>

  <script>$("p").hover(function () {
    $(this).css({'background-color' : 'yellow', 'font-weight' : 'bolder'});
  }, function () {
    var cssObj = {
      'background-color' : '#ddd',
      'font-weight' : '',
      'color' : 'rgb(0,40,244)'
    }
    $(this).css(cssObj);
  });</script>
</body>
</html>

Demo:

Example:

Increase the size of a div when you click it:
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width: 20px; height: 15px; background-color: #f33; }</style>
</head>
<body>

  <div>click</div>
  <div>click</div>

  <script>$("div").click(function() {
    $(this).css({
      width: function(index, value) {
        return parseFloat(value) * 1.2;
      },
      height: function(index, value) {
        return parseFloat(value) * 1.2;
      }

    });
  });</script>
</body>
</html>

Demo:


Data – jQuery API

Data

  • Boolean jQuery.hasData( [ Element ] element )

    New in 1.5 !

    Determine whether an element has any jQuery data associated with it.

  • jQuery jQuery.removeData( [ Element ] element, [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery jQuery.dequeue( [ Element ] element, [ String ] queueName )

    New in 1.3 !

    Execute the next function on the queue for the matched element.

  • jQuery jQuery.queue( [ Element ] element, [ String ] queueName, [ Function ] callback() )

    New in 1.3 !

    Manipulate the queue of functions to be executed on the matched element.

  • jQuery .clearQueue( [ String ] queueName )

    New in 1.4 !

    Remove from the queue all items that have not yet been run.

  • jQuery .removeData( [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • jQuery .dequeue( [ String ] queueName )

    New in 1.2 !

    Execute the next function on the queue for the matched elements.

  • jQuery .queue( [ String ] queueName, [ Function ] callback( next ) )

    New in 1.2 !

    Manipulate the queue of functions to be executed on the matched elements.


jQuery.hasData – jQuery API

Returns: BooleanBoolean jQuery.hasData( [ Element ] element )

Categories: Data, Version 1.5
Description: Determine whether an element has any jQuery data associated with it.
  • version added: 1.5
  • jQuery.hasData( [ Element ] element )
  • element A DOM element to be checked for data.

The method provides a way to determine if an element currently has any values that were set using . If no data is associated with an element (there is no data object at all or the data object is empty), the method returns ; otherwise it returns .

The primary advantage of is that it does not create and associate a data object with the element if none currently exists. In contrast, always returns a data object to the caller, creating one if no data object previously existed.

Examples:

Example:

Set data on an element and see the results of hasData.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>Results: </p>
  <script>$(function(){
  var $p = jQuery("p"), p = $p[0];
  $p.append(jQuery.hasData(p)+" "); /* false */
  jQuery.data(p, "testing", 123);
  $p.append(jQuery.hasData(p)+" "); /* true*/
  jQuery.removeData(p, "testing");
  $p.append(jQuery.hasData(p)+" "); /* false */
});</script>
</body>
</html>

Demo:


jQuery.removeData – jQuery API

Returns: jQueryjQuery jQuery.removeData( [ Element ] element, [ String ] name )

Categories: Data, Utilities, Version 1.2.3
Description: Remove a previously-stored piece of data.
  • version added: 1.2.3
  • jQuery.removeData( [ Element ] element, [ String ] name )
  • element A DOM element from which to remove data.
  • name A string naming the piece of data to remove.

This is a low-level method, you should probably use instead.

The method allows us to remove values that were previously set using . When called with the name of a key, deletes that particular value; when called with no arguments, all values are removed.

Examples:

Example:

Set a data store for 2 names then remove one of them.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:2px; color:blue; }
        span { color:red; }</style>
</head>
<body>
  <div>value1 before creation: <span></span></div>
        <div>value1 after creation: <span></span></div>
        <div>value1 after removal: <span></span></div>
        <div>value2 after removal: <span></span></div>
  <script>var div = $("div")[0];
$("span:eq(0)").text("" + $("div").data("test1"));
jQuery.data(div, "test1", "VALUE-1");
jQuery.data(div, "test2", "VALUE-2");
$("span:eq(1)").text("" + jQuery.data(div, "test1"));
jQuery.removeData(div, "test1");
$("span:eq(2)").text("" + jQuery.data(div, "test1"));
$("span:eq(3)").text("" + jQuery.data(div, "test2"));</script>
</body>
</html>

Demo:


jQuery.data – jQuery API

  • jQuery.data ( [ Element ] element, [ String ] key, [ Object ] value )

    • 1.2.3jQuery.data ( [ Element ] element, [ String ] key, [ Object ] value )

  • jQuery.data ( [ Element ] element, [ String ] key )

    • 1.2.3jQuery.data ( [ Element ] element, [ String ] key )
    • 1.4jQuery.data ( [ Element ] element )

Returns: jQueryjQuery jQuery.data( [ Element ] element, [ String ] key, [ Object ] value )

Categories: Data, Utilities, Version 1.2.3, Version 1.4, Version 1.4.3
Description: Store arbitrary data associated with the specified element.
  • version added: 1.2.3
  • jQuery.data( [ Element ] element, [ String ] key, [ Object ] value )
  • element The DOM element to associate with the data.
  • key A string naming the piece of data to set.
  • value The new data value.

This is a low-level method; a more convenient is also available.

The method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore free from memory leaks. jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page. We can set several distinct values for a single element and retrieve them later:

jQuery.data(document.body, 'foo', 52);
jQuery.data(document.body, 'bar', 'test');

Examples:

Example:

Store then retrieve a value from the div element.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:blue; }
  span { color:red; }</style>
</head>
<body>
  <div>
    The values stored were
    <span></span>
    and
    <span></span>
  </div>
  <script>var div = $("div")[0];
    jQuery.data(div, "test", { first: 16, last: "pizza!" });
    $("span:first").text(jQuery.data(div, "test").first);
    $("span:last").text(jQuery.data(div, "test").last);</script>
</body>
</html>

Demo:

Returns: ObjectObject jQuery.data( [ Element ] element )

Categories: Data, Utilities, Version 1.2.3, Version 1.4, Version 1.4.3
Description: Returns value at named data store for the element, as set by , or the full data store for the element.
  • version added: 1.2.3
  • jQuery.data( [ Element ] element, [ String ] key )
  • element The DOM element to query for the data.
  • key Name of the data stored.
  • version added: 1.4
  • jQuery.data( [ Element ] element )
  • element The DOM element to query for the data.

This is a low-level method; a more convenient is also available.

The method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can retrieve several distinct values for a single element one at a time, or as a set:

alert(jQuery.data( document.body, 'foo' ));
alert(jQuery.data( document.body ));

The above lines alert the data values that were set on the element. If nothing was set on that element, an empty string is returned.

Calling retrieves all of the element's associated values as a JavaScript object. Note that jQuery itself uses this method to store data for internal use, such as event handlers, so do not assume that it contains only data that your own code has stored.

Examples:

Example:

Get the data named "blah" stored at for an element.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:5px; background:yellow; }
button { margin:5px; font-size:14px; }
p { margin:5px; color:blue; }
span { color:red; }</style>
</head>
<body>
  <div>A div</div>
<button>Get "blah" from the div</button>
<button>Set "blah" to "hello"</button>

<button>Set "blah" to 86</button>
<button>Remove "blah" from the div</button>
<p>The "blah" value of this div is <span>?</span></p>
  <script>$("button").click(function(e) {
  var value, div = $("div")[0];

  switch ($("button").index(this)) {
    case 0 :
      value = jQuery.data(div, "blah");
      break;
    case 1 :
      jQuery.data(div, "blah", "hello");
      value = "Stored!";
      break;
    case 2 :
      jQuery.data(div, "blah", 86);
      value = "Stored!";
      break;
    case 3 :
      jQuery.removeData(div, "blah");
      value = "Removed!";
      break;
  }

  $("span").text("" + value);
});</script>
</body>
</html>

Demo:


jQuery.dequeue – jQuery API

Returns: jQueryjQuery jQuery.dequeue( [ Element ] element, [ String ] queueName )

Categories: Data, Utilities, Version 1.3
Description: Execute the next function on the queue for the matched element.
  • version added: 1.3
  • jQuery.dequeue( [ Element ] element, [ String ] queueName )
  • element A DOM element from which to remove and execute a queued function.
  • queueName A string containing the name of the queue. Defaults to , the standard effects queue.

This is a low-level method, you should probably use instead.

When is called, the next function on the queue is removed from the queue, and then executed. This function should in turn (directly or indirectly) cause to be called, so that the sequence can continue.

Examples:

Example:

Use dequeue to end a custom queue function which allows the queue to keep going.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:3px; width:50px; position:absolute;
        height:50px; left:10px; top:30px;
        background-color:yellow; }
  div.red { background-color:red; }</style>
</head>
<body>
  <button>Start</button>  <div></div>
  <script>$("button").click(function () {
      $("div").animate({left:'+=200px'}, 2000);
      $("div").animate({top:'0px'}, 600);
      $("div").queue(function () {
        $(this).toggleClass("red");
         $.dequeue( this );
              });
      $("div").animate({left:'10px', top:'30px'}, 700);
    });</script>
</body>
</html>

Demo:


jQuery.queue – jQuery API

  • jQuery.queue ( [ Element ] element, [ String ] queueName )

    • 1.3jQuery.queue ( [ Element ] element, [ String ] queueName )

  • jQuery.queue ( [ Element ] element, [ String ] queueName, [ Array ] newQueue )

    • 1.3jQuery.queue ( [ Element ] element, [ String ] queueName, [ Array ] newQueue )
    • 1.3jQuery.queue ( [ Element ] element, [ String ] queueName, [ Function ] callback() )

Returns: ArrayArray jQuery.queue( [ Element ] element, [ String ] queueName )

Categories: Data, Utilities, Version 1.3
Description: Show the queue of functions to be executed on the matched element.
  • version added: 1.3
  • jQuery.queue( [ Element ] element, [ String ] queueName )
  • element A DOM element to inspect for an attached queue.
  • queueName A string containing the name of the queue. Defaults to , the standard effects queue.

This is a low-level method, you should probably use instead.

Examples:

Example:

Show the length of the queue.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:3px; width:40px; height:40px;
        position:absolute; left:0px; top:30px;
        background:green; display:none; }
  div.newcolor { background:blue; }
  span { color:red; }</style>
</head>
<body>
  <button id="show">Show Length of Queue</button>
  <span></span>
  <div></div>
  <script>$("#show").click(function () {
      var n = jQuery.queue( $("div")[0], "fx" );
      $("span").text("Queue length is: " + n.length);
    });
    function runIt() {
      $("div").show("slow");
      $("div").animate({left:'+=200'},2000);
      $("div").slideToggle(1000);
      $("div").slideToggle("fast");
      $("div").animate({left:'-=200'},1500);
      $("div").hide("slow");
      $("div").show(1200);
      $("div").slideUp("normal", runIt);
    }
    runIt();</script>
</body>
</html>

Demo:

Returns: jQueryjQuery jQuery.queue( [ Element ] element, [ String ] queueName, [ Function ] callback() )

Categories: Data, Utilities, Version 1.3
Description: Manipulate the queue of functions to be executed on the matched element.
  • version added: 1.3
  • jQuery.queue( [ Element ] element, [ String ] queueName, [ Array ] newQueue )
  • element A DOM element where the array of queued functions is attached.
  • queueName A string containing the name of the queue. Defaults to , the standard effects queue.
  • newQueue An array of functions to replace the current queue contents.
  • version added: 1.3
  • jQuery.queue( [ Element ] element, [ String ] queueName, [ Function ] callback() )
  • element A DOM element on which to add a queued function.
  • queueName A string containing the name of the queue. Defaults to , the standard effects queue.
  • callback() The new function to add to the queue.

This is a low-level method, you should probably use instead.

Every element can have one or more queues of functions attached to it by jQuery. In most applications, only one queue (called ) is used. Queues allow a sequence of actions to be called on an element asynchronously, without halting program execution.

The method allows us to directly manipulate this queue of functions. Calling with a callback is particularly useful; it allows us to place a new function at the end of the queue.

Note that when adding a function with , we should ensure that is eventually called so that the next function in line executes.

Examples:

Example:

Queue a custom function.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:3px; width:40px; height:40px;
        position:absolute; left:0px; top:30px;
        background:green; display:none; }
  div.newcolor { background:blue; }</style>
</head>
<body>
  Click here...
  <div></div>
  <script>$(document.body).click(function () {
      $("div").show("slow");
      $("div").animate({left:'+=200'},2000);
      jQuery.queue( $("div")[0], "fx", function () {
        $(this).addClass("newcolor");
        jQuery.dequeue( this );
      });
      $("div").animate({left:'-=200'},500);
      jQuery.queue( $("div")[0], "fx", function () {
        $(this).removeClass("newcolor");
        jQuery.dequeue( this );
      });
      $("div").slideUp();
    });</script>
</body>
</html>

Demo:

Example:

Set a queue array to delete the queue.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:3px; width:40px; height:40px;
        position:absolute; left:0px; top:30px;
        background:green; display:none; }
  div.newcolor { background:blue; }</style>
</head>
<body>

  <button id="start">Start</button>
  <button id="stop">Stop</button>
  <div></div>
  <script>$("#start").click(function () {
      $("div").show("slow");
      $("div").animate({left:'+=200'},5000);
      jQuery.queue( $("div")[0], "fx", function () {
        $(this).addClass("newcolor");
        jQuery.dequeue( this );
      });
      $("div").animate({left:'-=200'},1500);
      jQuery.queue( $("div")[0], "fx", function () {
        $(this).removeClass("newcolor");
        jQuery.dequeue( this );
      });
      $("div").slideUp();
    });
    $("#stop").click(function () {
      jQuery.queue( $("div")[0], "fx", [] );
      $("div").stop();
    });</script>
</body>
</html>

Demo:


clearQueue – jQuery API

Returns: jQueryjQuery .clearQueue( [ String ] queueName )

Categories: Custom, Data, Utilities, Version 1.4
Description: Remove from the queue all items that have not yet been run.
  • version added: 1.4
  • .clearQueue( [ String ] queueName )
  • queueName A string containing the name of the queue. Defaults to , the standard effects queue.

When the method is called, all functions on the queue that have not been executed are removed from the queue. When used without an argument, removes the remaining functions from , the standard effects queue. In this way it is similar to . However, while the method is meant to be used only with animations, can also be used to remove any function that has been added to a generic jQuery queue with the method.

Examples:

Example:

Empty the queue.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:3px; width:40px; height:40px;
    position:absolute; left:0px; top:30px;
    background:green; display:none; }
div.newcolor { background:blue; }</style>
</head>
<body>
  <button id="start">Start</button>
<button id="stop">Stop</button>
<div></div>
  <script>$("#start").click(function () {
  $("div").show("slow");
  $("div").animate({left:'+=200'},5000);
  $("div").queue(function () {
    $(this).addClass("newcolor");
    $(this).dequeue();
  });
  $("div").animate({left:'-=200'},1500);
  $("div").queue(function () {
    $(this).removeClass("newcolor");
    $(this).dequeue();
  });
  $("div").slideUp();
});
$("#stop").click(function () {
  $("div").clearQueue();
  $("div").stop();
});</script>
</body>
</html>

Demo:


removeData – jQuery API

Returns: jQueryjQuery .removeData( [ String ] name )

Categories: Data, Data Storage, Version 1.2.3
Description: Remove a previously-stored piece of data.
  • version added: 1.2.3
  • .removeData( [ String ] name )
  • name A string naming the piece of data to delete.

The method allows us to remove values that were previously set using . When called with the name of a key, deletes that particular value; when called with no arguments, all values are removed.

NOTE: Starting with jQuery 1.4.3, calling will cause the value of the property being removed to revert to the value of the data attribute of the same name in the DOM, rather than being set to .

Examples:

Example:

Set a data store for 2 names then remove one of them.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:2px; color:blue; }
  span { color:red; }</style>
</head>
<body>
  <div>value1 before creation: <span></span></div>
  <div>value1 after creation: <span></span></div>
  <div>value1 after removal: <span></span></div>

  <div>value2 after removal: <span></span></div>
  <script>$("span:eq(0)").text("" + $("div").data("test1"));
    $("div").data("test1", "VALUE-1");
    $("div").data("test2", "VALUE-2");
    $("span:eq(1)").text("" + $("div").data("test1"));
    $("div").removeData("test1");
    $("span:eq(2)").text("" + $("div").data("test1"));
    $("span:eq(3)").text("" + $("div").data("test2"));</script>
</body>
</html>

Demo:


data – jQuery API

  • data ( [ String ] key, [ Object ] value )

    • 1.2.3data ( [ String ] key, [ Object ] value )
    • 1.4.3data ( [ Object ] obj )

  • data ( [ String ] key )

    • 1.2.3data ( [ String ] key )
    • 1.4data ( )

Returns: jQueryjQuery .data( [ Object ] obj )

Categories: Data, Data Storage, Version 1.2.3, Version 1.4, Version 1.4.3
Description: Store arbitrary data associated with the matched elements.
  • version added: 1.2.3
  • .data( [ String ] key, [ Object ] value )
  • key A string naming the piece of data to set.
  • value The new data value; it can be any Javascript type including Array or Object.
  • version added: 1.4.3
  • .data( [ Object ] obj )
  • obj An object of key-value pairs of data to update.

The method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

We can set several distinct values for a single element and retrieve them later:

$('body').data('foo', 52);
$('body').data('bar', { myType: 'test', count: 40 });

$('body').data('foo'); // 52
$('body').data(); // {foo: 52, bar: { myType: 'test', count: 40 }}

In jQuery 1.4.3 setting an element's data object with extends the data previously stored with that element. jQuery itself uses the method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.

Prior to jQuery 1.4.3 (starting in jQuery 1.4) the .data() method completely replaced all data, instead of just extending the data object. If you are using third-party plugins it may not be advisable to completely replace the element's data object, since plugins may have also set data.

Due to the way browsers interact with plugins and external code, the method cannot be used on (unless it's a Flash plugin), or elements.

As of jQuery 1.4.3 will be automatically pulled in to jQuery's data object.

For example, given the following HTML:

<div data-role="page" data-hidden="true" data-options='{"name":"John"}'></div>

All of the following jQuery code will work.

$("div").data("role") === "page";
$("div").data("hidden") === true;
$("div").data("options").name === "John";

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the method. When the data attribute is an object (starts with '{') or array (starts with '[') then is used to parse the string; it must follow . The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

Examples:

Example:

Store then retrieve a value from the div element.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:blue; }
  span { color:red; }</style>
</head>
<body>
  <div>
    The values stored were
    <span></span>
    and
    <span></span>
  </div>
  <script>$("div").data("test", { first: 16, last: "pizza!" });
$("span:first").text($("div").data("test").first);
$("span:last").text($("div").data("test").last);</script>
</body>
</html>

Demo:

Returns: ObjectObject .data( )

Categories: Data, Data Storage, Version 1.2.3, Version 1.4, Version 1.4.3
Description: Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).
  • version added: 1.2.3
  • .data( [ String ] key )
  • key Name of the data stored.
  • version added: 1.4
  • .data( )

The method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can retrieve several distinct values for a single element one at a time, or as a set:

alert($('body').data('foo'));
alert($('body').data());

The above lines alert the data values that were set on the element. If nothing was set on that element, null is returned.

Calling with no parameters retrieves all of the values as a JavaScript object. This object can be safely cached in a variable as long as a new object is not set with . Using the object directly to get or set values is faster than making individual calls to to get or set each value:

var mydata = $("#mydiv").data();
if ( mydata.count < 9 ) {
    mydata.count = 43;
    mydata.status = "embiggened";
}

Examples:

Example:

Get the data named "blah" stored at for an element.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:5px; background:yellow; }
  button { margin:5px; font-size:14px; }
  p { margin:5px; color:blue; }
  span { color:red; }</style>
</head>
<body>
  <div>A div</div>
  <button>Get "blah" from the div</button>
  <button>Set "blah" to "hello"</button>

  <button>Set "blah" to 86</button>
  <button>Remove "blah" from the div</button>
  <p>The "blah" value of this div is <span>?</span></p>
  <script>$("button").click(function(e) {
  var value;

  switch ($("button").index(this)) {
    case 0 :
      value = $("div").data("blah");
      break;
    case 1 :
      $("div").data("blah", "hello");
      value = "Stored!";
      break;
    case 2 :
      $("div").data("blah", 86);
      value = "Stored!";
      break;
    case 3 :
      $("div").removeData("blah");
      value = "Removed!";
      break;
  }

  $("span").text("" + value);
});</script>
</body>
</html>

Demo:


dequeue – jQuery API

Returns: jQueryjQuery .dequeue( [ String ] queueName )

Categories: Custom, Data, Utilities, Version 1.2
Description: Execute the next function on the queue for the matched elements.
  • version added: 1.2
  • .dequeue( [ String ] queueName )
  • queueName A string containing the name of the queue. Defaults to , the standard effects queue.

When is called, the next function on the queue is removed from the queue, and then executed. This function should in turn (directly or indirectly) cause to be called, so that the sequence can continue.

Examples:

Example:

Use dequeue to end a custom queue function which allows the queue to keep going.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:3px; width:50px; position:absolute;
  height:50px; left:10px; top:30px;
  background-color:yellow; }
  div.red { background-color:red; }</style>
</head>
<body>
  <button>Start</button>
<div></div>
  <script>$("button").click(function () {
  $("div").animate({left:'+=200px'}, 2000);
  $("div").animate({top:'0px'}, 600);
  $("div").queue(function () {
    $(this).toggleClass("red");
    $(this).dequeue();
  });
  $("div").animate({left:'10px', top:'30px'}, 700);
});</script>
</body>
</html>

Demo:


queue – jQuery API

  • queue ( [ String ] queueName )

    • 1.2queue ( [ String ] queueName )

  • queue ( [ String ] queueName, [ Array ] newQueue )

    • 1.2queue ( [ String ] queueName, [ Array ] newQueue )
    • 1.2queue ( [ String ] queueName, [ Function ] callback( next ) )

Returns: ArrayArray .queue( [ String ] queueName )

Categories: Custom, Data, Utilities, Version 1.2
Description: Show the queue of functions to be executed on the matched elements.
  • version added: 1.2
  • .queue( [ String ] queueName )
  • queueName A string containing the name of the queue. Defaults to , the standard effects queue.

Examples:

Example:

Show the length of the queue.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:3px; width:40px; height:40px;
        position:absolute; left:0px; top:60px;
        background:green; display:none; }
  div.newcolor { background:blue; }
  p { color:red; }</style>
</head>
<body>
  <button id="show">Show Length of Queue</button>
  <p></p>
  <div></div>
  <script>$("#show").click(function () {
      var n = $("div").queue("fx");
      $("p").text("Queue length is: " + n.length);
    });
    function runIt() {
      $("div").show("slow");
      $("div").animate({left:'+=200'},2000);
      $("div").slideToggle(1000);
      $("div").slideToggle("fast");
      $("div").animate({left:'-=200'},1500);
      $("div").hide("slow");
      $("div").show(1200);
      $("div").slideUp("normal", runIt);
    }
    runIt();</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .queue( [ String ] queueName, [ Function ] callback( next ) )

Categories: Custom, Data, Utilities, Version 1.2
Description: Manipulate the queue of functions to be executed on the matched elements.
  • version added: 1.2
  • .queue( [ String ] queueName, [ Array ] newQueue )
  • queueName A string containing the name of the queue. Defaults to , the standard effects queue.
  • newQueue An array of functions to replace the current queue contents.
  • version added: 1.2
  • .queue( [ String ] queueName, [ Function ] callback( next ) )
  • queueName A string containing the name of the queue. Defaults to , the standard effects queue.
  • callback( next ) The new function to add to the queue, with a function to call that will dequeue the next item.

Every element can have one to many queues of functions attached to it by jQuery. In most applications, only one queue (called ) is used. Queues allow a sequence of actions to be called on an element asynchronously, without halting program execution. The typical example of this is calling multiple animation methods on an element. For example:

$('#foo').slideUp().fadeIn();

When this statement is executed, the element begins its sliding animation immediately, but the fading transition is placed on the queue to be called only once the sliding transition is complete.

The method allows us to directly manipulate this queue of functions. Calling with a callback is particularly useful; it allows us to place a new function at the end of the queue.

This feature is similar to providing a callback function with an animation method, but does not require the callback to be given at the time the animation is performed.

$('#foo').slideUp();
$('#foo').queue(function() {
  alert('Animation complete.');
  $(this).dequeue();
});

This is equivalent to:

$('#foo').slideUp(function() {
  alert('Animation complete.');
});

Note that when adding a function with , we should ensure that is eventually called so that the next function in line executes.

In jQuery 1.4 the function that's called is passed in another function, as the first argument, that when called automatically dequeues the next item and keeps the queue moving. You would use it like so:

$("#test").queue(function(next) {
    // Do some stuff...
    next();
});

Examples:

Example:

Queue a custom function.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:3px; width:40px; height:40px;
        position:absolute; left:0px; top:30px;
        background:green; display:none; }
  div.newcolor { background:blue; }</style>
</head>
<body>
  Click here...
  <div></div>
  <script>$(document.body).click(function () {
      $("div").show("slow");
      $("div").animate({left:'+=200'},2000);
      $("div").queue(function () {
        $(this).addClass("newcolor");
        $(this).dequeue();
      });
      $("div").animate({left:'-=200'},500);
      $("div").queue(function () {
        $(this).removeClass("newcolor");
        $(this).dequeue();
      });
      $("div").slideUp();
    });</script>
</body>
</html>

Demo:

Example:

Set a queue array to delete the queue.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:3px; width:40px; height:40px;
        position:absolute; left:0px; top:30px;
        background:green; display:none; }
  div.newcolor { background:blue; }</style>
</head>
<body>
  <button id="start">Start</button>
  <button id="stop">Stop</button>
  <div></div>
  <script>$("#start").click(function () {
      $("div").show("slow");
      $("div").animate({left:'+=200'},5000);
      $("div").queue(function () {
        $(this).addClass("newcolor");
        $(this).dequeue();
      });
      $("div").animate({left:'-=200'},1500);
      $("div").queue(function () {
        $(this).removeClass("newcolor");
        $(this).dequeue();
      });
      $("div").slideUp();
    });
    $("#stop").click(function () {
      $("div").queue("fx", []);
      $("div").stop();
    });</script>
</body>
</html>

Demo:


Deferred Object – jQuery API

Deferred Object

  • Promise .deferred.promise( )

    New in 1.5 !

    Return a Deferred's Promise object.

  • Deferred .deferred.resolveWith( [ Object ] context, [ Array ] args )

    New in 1.5 !

    Resolve a Deferred object and call any doneCallbacks with the given and .

  • Deferred .deferred.rejectWith( [ Object ] context, [ Array ] args )

    New in 1.5 !

    Reject a Deferred object and call any failCallbacks with the given and .

  • Deferred .deferred.fail( [ Function ] failCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is rejected.

  • Deferred .deferred.done( [ Function ] doneCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is resolved.

  • Deferred .deferred.then( [ Function ] doneCallbacks, [ Function ] failCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is resolved or rejected.

  • Deferred .deferred.reject( [ Object ] args )

    New in 1.5 !

    Reject a Deferred object and call any failCallbacks with the given .

  • Boolean .deferred.isRejected( )

    New in 1.5 !

    Determine whether a Deferred object has been rejected.

  • Boolean .deferred.isResolved( )

    New in 1.5 !

    Determine whether a Deferred object has been resolved.

  • Deferred .deferred.resolve( [ Object ] args )

    New in 1.5 !

    Resolve a Deferred object and call any doneCallbacks with the given .


deferred.promise – jQuery API

Returns: PromisePromise .deferred.promise( )

Categories: Deferred Object, Version 1.5
Description: Return a Deferred's Promise object.
  • version added: 1.5
  • .deferred.promise( )

The method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request. The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (, , , , and ), but not ones that change the state (, , , and ).

If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point. Return the Promise object via so other code can register callbacks or inspect the current state.

For more information, see the documentation for .

Examples:

Example:

This test creates a Deferred and sets two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action.
// Create a Deferred and return its Promise
function asyncEvent(){
    var dfd = new jQuery.Deferred();
    setTimeout(function(){
        dfd.resolve("hurray");
    }, Math.floor(Math.random()*1500));
    setTimeout(function(){
        dfd.reject("sorry");
    }, Math.floor(Math.random()*1500));
    return dfd.promise();
}

// Attach a done and fail handler for the asyncEvent
$.when( asyncEvent() ).then(
    function(status){
        alert( status+', things are going well' );
    },
    function(status){
        alert( status+', you fail this time' );
    }
);


deferred.resolveWith – jQuery API

Returns: DeferredDeferred .deferred.resolveWith( [ Object ] context, [ Array ] args )

Categories: Deferred Object, Version 1.5
Description: Resolve a Deferred object and call any doneCallbacks with the given and .
  • version added: 1.5
  • .deferred.resolveWith( [ Object ] context, [ Array ] args )
  • context Context passed to the doneCallbacks as the object.
  • args An optional array of arguments that are passed to the doneCallbacks.

Normally, only the creator of a Deferred should call this method; you can prevent other code from changing the Deferred's state by returning a restricted Promise object through .

When the Deferred is resolved, any doneCallbacks added by or are called. Callbacks are executed in the order they were added. Each callback is passed the from the . Any doneCallbacks added after the Deferred enters the resolved state are executed immediately when they are added, using the arguments that were passed to the call. For more information, see the documentation for .

Examples:


deferred.rejectWith – jQuery API

Returns: DeferredDeferred .deferred.rejectWith( [ Object ] context, [ Array ] args )

Categories: Deferred Object, Version 1.5
Description: Reject a Deferred object and call any failCallbacks with the given and .
  • version added: 1.5
  • .deferred.rejectWith( [ Object ] context, [ Array ] args )
  • context Context passed to the failCallbacks as the object.
  • args An optional array of arguments that are passed to the failCallbacks.

Normally, only the creator of a Deferred should call this method; you can prevent other code from changing the Deferred's state by returning a restricted Promise object through .

When the Deferred is rejected, any failCallbacks added by or are called. Callbacks are executed in the order they were added. Each callback is passed the from the call. Any failCallbacks added after the Deferred enters the rejected state are executed immediately when they are added, using the arguments that were passed to the call. For more information, see the documentation for .

Examples:


deferred.fail – jQuery API

Returns: DeferredDeferred .deferred.fail( [ Function ] failCallbacks )

Categories: Deferred Object, Version 1.5
Description: Add handlers to be called when the Deferred object is rejected.
  • version added: 1.5
  • .deferred.fail( [ Function ] failCallbacks )
  • failCallbacks A function, or array of functions, that are called when the Deferred is rejected.

The argument can be either a single function or an array of functions. When the Deferred is rejected, the failCallbacks are called. Callbacks are executed in the order they were added. Since returns the deferred object, other methods of the deferred object can be chained to this one, including additional methods. The failCallbacks are executed using the arguments provided to the or method call in the order they were added. For more information, see the documentation for .

Examples:

Example:

Since the method returns a jqXHR object, which is derived from a Deferred, you can attach a success and failure callback using the and methods.
$.get("test.php")
  .done(function(){ alert("$.get succeeded"); })
  .fail(function(){ alert("$.get failed!"); });


deferred.done – jQuery API

Returns: DeferredDeferred .deferred.done( [ Function ] doneCallbacks )

Categories: Deferred Object, Version 1.5
Description: Add handlers to be called when the Deferred object is resolved.
  • version added: 1.5
  • .deferred.done( [ Function ] doneCallbacks )
  • doneCallbacks A function, or array of functions, that are called when the Deferred is resolved.

The argument can be either a single function or an array of functions. When the Deferred is resolved, the doneCallbacks are called. Callbacks are executed in the order they were added. Since returns the deferred object, other methods of the deferred object can be chained to this one, including additional methods. When the Deferred is resolved, doneCallbacks are executed using the arguments provided to the or method call in the order they were added. For more information, see the documentation for .

Examples:

Example:

Since the method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the method.
$.get("test.php").done(
    function(){ alert("$.get succeeded"); }
);


deferred.then – jQuery API

Returns: DeferredDeferred .deferred.then( [ Function ] doneCallbacks, [ Function ] failCallbacks )

Categories: Deferred Object, Version 1.5
Description: Add handlers to be called when the Deferred object is resolved or rejected.
  • version added: 1.5
  • .deferred.then( [ Function ] doneCallbacks, [ Function ] failCallbacks )
  • doneCallbacks A function, or array of functions, called when the Deferred is resolved.
  • failCallbacks A function, or array of functions, called when the Deferred is rejected.

Both arguments can be either a single function or an array of functions. Either argument can also be null if no callback of that type is desired. Alternatively, use or to set only doneCallbacks or failCallbacks. When the Deferred is resolved, the doneCallbacks are called. If the Deferred is instead rejected, the failCallbacks are called. Callbacks are executed in the order they were added. Since returns the deferred object, other methods of the deferred object can be chained to this one, including additional methods. For more information, see the documentation for .

Examples:

Example:

Since the method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the method.
$.get("test.php").then(
    function(){ alert("$.get succeeded"); },
    function(){ alert("$.get failed!"); }
);


deferred.reject – jQuery API

Returns: DeferredDeferred .deferred.reject( [ Object ] args )

Categories: Deferred Object, Version 1.5
Description: Reject a Deferred object and call any failCallbacks with the given .
  • version added: 1.5
  • .deferred.reject( [ Object ] args )
  • args Optional arguments that are passed to the failCallbacks.

Normally, only the creator of a Deferred should call this method; you can prevent other code from changing the Deferred's state by returning a restricted Promise object through .

When the Deferred is rejected, any failCallbacks added by or are called. Callbacks are executed in the order they were added. Each callback is passed the from the call. Any failCallbacks added after the Deferred enters the rejected state are executed immediately when they are added, using the arguments that were passed to the call. For more information, see the documentation for .

Examples:


deferred.isRejected – jQuery API

Returns: BooleanBoolean .deferred.isRejected( )

Categories: Deferred Object, Version 1.5
Description: Determine whether a Deferred object has been rejected.
  • version added: 1.5
  • .deferred.isRejected( )

Returns if the Deferred object is in the rejected state, meaning that either or has been called for the object and the failCallbacks have been called (or are in the process of being called).

Note that a Deferred object can be in one of three states: unresolved, resolved, or rejected; use to determine whether the Deferred object is in the resolved state. These methods are primarily useful for debugging, for example to determine whether a Deferred has already been resolved even though you are inside code that intended to reject it.

Examples:


deferred.isResolved – jQuery API

Returns: BooleanBoolean .deferred.isResolved( )

Categories: Deferred Object, Version 1.5
Description: Determine whether a Deferred object has been resolved.
  • version added: 1.5
  • .deferred.isResolved( )

Returns if the Deferred object is in the resolved state, meaning that either or has been called for the object and the doneCallbacks have been called (or are in the process of being called).

Note that a Deferred object can be in one of three states: unresolved, resolved, or rejected; use to determine whether the Deferred object is in the rejected state. These methods are primarily useful for debugging, for example to determine whether a Deferred has already been resolved even though you are inside code that intended to reject it.

Examples:


deferred.resolve – jQuery API

Returns: DeferredDeferred .deferred.resolve( [ Object ] args )

Categories: Deferred Object, Version 1.5
Description: Resolve a Deferred object and call any doneCallbacks with the given .
  • version added: 1.5
  • .deferred.resolve( [ Object ] args )
  • args Optional arguments that are passed to the doneCallbacks.

When the Deferred is resolved, any doneCallbacks added by or are called. Callbacks are executed in the order they were added. Each callback is passed the from the . Any doneCallbacks added after the Deferred enters the resolved state are executed immediately when they are added, using the arguments that were passed to the call. For more information, see the documentation for .

Examples:


Dimensions – jQuery API

Dimensions

  • Integer .outerWidth( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding and border.

  • Integer .outerHeight( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.

  • Integer .innerWidth( )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding but not border.

  • Integer .innerHeight( )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding but not border.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.


Effects – jQuery API

Effects

  • jQuery .toggle( [ Boolean ] showOrHide )

    New in 1.3 !

    Display or hide the matched elements.

  • jQuery .hide( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements.

  • jQuery .show( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements.

  • Number jQuery.fx.interval

    New in 1.4.3 !

    The rate (in milliseconds) at which animations fire.

  • jQuery .delay( [ Integer ] duration, [ String ] queueName )

    New in 1.4 !

    Set a timer to delay execution of subsequent items in the queue.

  • Boolean jQuery.fx.off

    New in 1.3 !

    Globally disable all animations.

  • jQuery .clearQueue( [ String ] queueName )

    New in 1.4 !

    Remove from the queue all items that have not yet been run.

  • jQuery .dequeue( [ String ] queueName )

    New in 1.2 !

    Execute the next function on the queue for the matched elements.

  • jQuery .queue( [ String ] queueName, [ Function ] callback( next ) )

    New in 1.2 !

    Manipulate the queue of functions to be executed on the matched elements.

  • jQuery .stop( [ Boolean ] clearQueue, [ Boolean ] jumpToEnd )

    New in 1.2 !

    Stop the currently-running animation on the matched elements.

  • jQuery .animate( [ Map ] properties, [ Map ] options )

    New in 1.0 !

    Perform a custom animation of a set of CSS properties.

  • jQuery .fadeToggle( [ String,Number ] duration, [ String ] easing, [ Function ] callback )

    New in 1.4.4 !

    Display or hide the matched elements by animating their opacity.

  • jQuery .fadeTo( [ String,Number ] duration, [ Number ] opacity, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Adjust the opacity of the matched elements.

  • jQuery .fadeOut( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements by fading them to transparent.

  • jQuery .fadeIn( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements by fading them to opaque.

  • jQuery .slideToggle( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display or hide the matched elements with a sliding motion.

  • jQuery .slideUp( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements with a sliding motion.

  • jQuery .slideDown( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements with a sliding motion.

  • jQuery .fadeToggle( [ String,Number ] duration, [ String ] easing, [ Function ] callback )

    New in 1.4.4 !

    Display or hide the matched elements by animating their opacity.


Basics – jQuery API

Basics

  • jQuery .toggle( [ Boolean ] showOrHide )

    New in 1.3 !

    Display or hide the matched elements.

  • jQuery .hide( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements.

  • jQuery .show( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements.


toggle – jQuery API

  • toggle ( [ Function ] handler(eventObject), [ Function ] handler(eventObject), [ Function ] handler(eventObject) )

    • 1.0toggle ( [ Function ] handler(eventObject), [ Function ] handler(eventObject), [ Function ] handler(eventObject) )

  • toggle ( [ String,Number ] duration, [ Callback ] callback )

    • 1.0toggle ( [ String,Number ] duration, [ Callback ] callback )
    • 1.4.3toggle ( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )
    • 1.3toggle ( [ Boolean ] showOrHide )

Returns: jQueryjQuery .toggle( [ Function ] handler(eventObject), [ Function ] handler(eventObject), [ Function ] handler(eventObject) )

Categories: Mouse Events, Version 1.0
Description: Bind two or more handlers to the matched elements, to be executed on alternate clicks.
  • version added: 1.0
  • .toggle( [ Function ] handler(eventObject), [ Function ] handler(eventObject), [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute every even time the element is clicked.
  • handler(eventObject) A function to execute every odd time the element is clicked.
  • handler(eventObject) Additional handlers to cycle through after clicks.

The method binds a handler for the event, so the rules outlined for the triggering of apply here as well.

For example, consider the HTML:
<div id="target">
  Click here
</div>

Event handlers can then be bound to the :

$('#target').toggle(function() {
  alert('First handler for .toggle() called.');
}, function() {
  alert('Second handler for .toggle() called.');
});

As the element is clicked repeatedly, the messages alternate:

If more than two handlers are provided, will cycle among all of them. For example, if there are three handlers, then the first handler will be called on the first click, the fourth click, the seventh click, and so on.

The method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into prove limiting. For example, is not guaranteed to work correctly if applied twice to the same element. Since internally uses a handler to do its work, we must unbind to remove a behavior attached with , so other handlers can be caught in the crossfire. The implementation also calls on the event, so links will not be followed and buttons will not be clicked if has been called on the element.

Examples:

Example:

Click to toggle highlight on the list item.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>ul { margin:10px; list-style:inside circle; font-weight:bold; }
  li { cursor:pointer; }</style>
</head>
<body>
  <ul>
    <li>Go to the store</li>
    <li>Pick up dinner</li>
    <li>Debug crash</li>

    <li>Take a jog</li>
  </ul>
  <script>$("li").toggle(
      function () {
        $(this).css({"list-style-type":"disc", "color":"blue"});
      },
      function () {
        $(this).css({"list-style-type":"disc", "color":"red"});
      },
      function () {
        $(this).css({"list-style-type":"", "color":""});
      }
    );</script>
</body>
</html>

Demo:

Example:

To toggle a style on table cells:
$("td").toggle(
  function () {
    $(this).addClass("selected");
  },
  function () {
    $(this).removeClass("selected");
  }
);

Returns: jQueryjQuery .toggle( [ Boolean ] showOrHide )

Categories: Basics, Version 1.0, Version 1.3, Version 1.4.3
Description: Display or hide the matched elements.
  • version added: 1.0
  • .toggle( [ String,Number ] duration, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • callback A function to call once the animation is complete.
  • version added: 1.4.3
  • .toggle( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • easing A string indicating which easing function to use for the transition.
  • callback A function to call once the animation is complete.
  • version added: 1.3
  • .toggle( [ Boolean ] showOrHide )
  • showOrHide A Boolean indicating whether to show or hide the elements.

With no parameters, the method simply toggles the visibility of elements:

$('.target').toggle();

The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS property. If the element is initially displayed, it will be hidden; if hidden, it will be shown. The property is saved and restored as needed. If an element has a value of , then is hidden and shown, it will once again be displayed .

When a duration is provided, becomes an animation method. The method animates the width, height, and opacity of the matched elements simultaneously. When these properties reach 0 after a hiding animation, the style property is set to to ensure that the element no longer affects the layout of the page.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings and can be supplied to indicate durations of and milliseconds, respectively.

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called , and one that progresses at a constant pace, called . More easing functions are available with the use of plug-ins, most notably the .

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

We can animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />

We will cause to be called when another element is clicked:

$('#clickme').click(function() {
  $('#book').toggle('slow', function() {
    // Animation complete.
  });
});

With the element initially shown, we can hide it slowly with the first click:

A second click will show the element once again:

The second version of the method accepts a Boolean parameter. If this parameter is , then the matched elements are shown; if , the elements are hidden. In essence, the statement:

$('#foo').toggle(showOrHide);

is equivalent to:

if ( showOrHide == true ) {
  $('#foo').show();
} else if ( showOrHide == false ) {
  $('#foo').hide();
}

Examples:

Example:

Toggles all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <button>Toggle</button>
<p>Hello</p>
<p style="display: none">Good Bye</p>
  <script>$("button").click(function () {
$("p").toggle();
});</script>
</body>
</html>

Demo:

Example:

Animates all paragraphs to be shown if they are hidden and hidden if they are visible, completing the animation within 600 milliseconds.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:#dad;
font-weight:bold;
font-size:16px; }</style>
</head>
<body>
  <button>Toggle 'em</button>

<p>Hiya</p>
<p>Such interesting text, eh?</p>
  <script>$("button").click(function () {
$("p").toggle("slow");
});</script>
</body>
</html>

Demo:

Example:

Shows all paragraphs, then hides them all, back and forth.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <button>Toggle</button>
<p>Hello</p>
<p style="display: none">Good Bye</p>
  <script>var flip = 0;
$("button").click(function () {
$("p").toggle( flip++ % 2 == 0 );
});</script>
</body>
</html>

Demo:


hide – jQuery API

Returns: jQueryjQuery .hide( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

Categories: Basics, Version 1.0, Version 1.4.3
Description: Hide the matched elements.
  • version added: 1.0
  • .hide( )
  • version added: 1.0
  • .hide( [ String,Number ] duration, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • callback A function to call once the animation is complete.
  • version added: 1.4.3
  • .hide( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • easing A string indicating which easing function to use for the transition.
  • callback A function to call once the animation is complete.

With no parameters, the method is the simplest way to hide an element:

$('.target').hide();

The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling , except that the value of the property is saved in jQuery's data cache so that can later be restored to its initial value. If an element has a value of , then is hidden and shown, it will once again be displayed .

When a duration is provided, becomes an animation method. The method animates the width, height, and opacity of the matched elements simultaneously. When these properties reach 0, the style property is set to to ensure that the element no longer affects the layout of the page.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings and can be supplied to indicate durations of and milliseconds, respectively.

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called , and one that progresses at a constant pace, called . More easing functions are available with the use of plug-ins, most notably the .

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

We can animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
With the element initially shown, we can hide it slowly:
$('#clickme').click(function() {
  $('#book').hide('slow', function() {
    alert('Animation complete.');
  });
});

Examples:

Example:

Hides all paragraphs then the link on click.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>Hello</p>
  <a href="#">Click to hide me too</a>
  <p>Here is another paragraph</p>
  <script>$("p").hide();
    $("a").click(function () {
      $(this).hide();
      return true;
    });</script>
</body>
</html>

Demo:

Example:

Animates all shown paragraphs to hide slowly, completing the animation within 600 milliseconds.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:#dad; font-weight:bold; }</style>
</head>
<body>
  <button>Hide 'em</button>

  <p>Hiya</p>
  <p>Such interesting text, eh?</p>
  <script>$("button").click(function () {
      $("p").hide("slow");
    });</script>
</body>
</html>

Demo:

Example:

Animates all spans (words in this case) to hide fastly, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span { background:#def3ca; padding:3px; float:left; }</style>
</head>
<body>
  <button id="hidr">Hide</button>
  <button id="showr">Show</button>
  <div>

    <span>Once</span> <span>upon</span> <span>a</span>
    <span>time</span> <span>there</span> <span>were</span>
    <span>three</span> <span>programmers...</span>

  </div>
  <script>$("#hidr").click(function () {
      $("span:last-child").hide("fast", function () {
        // use callee so don't have to name the function
        $(this).prev().hide("fast", arguments.callee);
      });
    });
    $("#showr").click(function () {
      $("span").show(2000);
    });</script>
</body>
</html>

Demo:

Example:

Hides the divs when clicked over 2 seconds, then removes the div element when its hidden. Try clicking on more than one box at a time.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { background:#ece023; width:30px;
        height:40px; margin:2px; float:left; }</style>
</head>
<body>
  <div></div>
  <script>for (var i = 0; i < 5; i++) {
      $("<div>").appendTo(document.body);
    }
    $("div").click(function () {
      $(this).hide(2000, function () {
        $(this).remove();
      });
    });</script>
</body>
</html>

Demo:


show – jQuery API

Returns: jQueryjQuery .show( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

Categories: Basics, Version 1.0, Version 1.4.3
Description: Display the matched elements.
  • version added: 1.0
  • .show( )
  • version added: 1.0
  • .show( [ String,Number ] duration, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • callback A function to call once the animation is complete.
  • version added: 1.4.3
  • .show( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • easing A string indicating which easing function to use for the transition.
  • callback A function to call once the animation is complete.

With no parameters, the method is the simplest way to display an element:

$('.target').show();

The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling , except that the property is restored to whatever it was initially. If an element has a value of , then is hidden and shown, it will once again be displayed .

When a duration is provided, becomes an animation method. The method animates the width, height, and opacity of the matched elements simultaneously.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings and can be supplied to indicate durations of and milliseconds, respectively.

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called , and one that progresses at a constant pace, called . More easing functions are available with the use of plug-ins, most notably the .

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

We can animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
With the element initially hidden, we can show it slowly:
$('#clickme').click(function() {
  $('#book').show('slow', function() {
    // Animation complete.
  });
});

Examples:

Example:

Animates all hidden paragraphs to show slowly, completing the animation within 600 milliseconds.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <button>Show it</button>

      <p style="display: none">Hello  2</p>
  <script>$("button").click(function () {
    $("p").show("slow");
    });</script>
</body>
</html>

Demo:

Example:

Animates all hidden divs to show fastly in order, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { background:#def3ca; margin:3px; width:80px;
  display:none; float:left; text-align:center; }</style>
</head>
<body>

  <button id="showr">Show</button>
  <button id="hidr">Hide</button>
  <div>Hello 3,</div>

  <div>how</div>
  <div>are</div>
  <div>you?</div>
  <script>$("#showr").click(function () {
  $("div:eq(0)").show("fast", function () {
    /* use callee so don't have to name the function */
    $(this).next("div").show("fast", arguments.callee);
  });
});
$("#hidr").click(function () {
  $("div").hide(2000);
});</script>
</body>
</html>

Demo:

Example:

Shows all span and input elements with an animation. Once the animation is done, it changes the text.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span { display:none; }
  div { display:none; }
  p { font-weight:bold; background-color:#fcd; }</style>
</head>
<body>
  <button>Do it!</button>
  <span>Are you sure? (type 'yes' if you are) </span>
  <div>
    <form>
      <input type="text"  value="as;ldkfjalsdf"/>
    </form>
  </div>
  <p style="display:none;">I'm hidden...</p>

  <script>function doIt() {
  $("span,div").show("slow");
}
/* can pass in function name */
$("button").click(doIt);

$("form").submit(function () {
  if ($("input").val() == "yes") {
    $("p").show(4000, function () {
      $(this).text("Ok, DONE! (now showing)");
    });
  }
  $("span,div").hide("fast");
  /* to stop the submit */
  return false;
});</script>
</body>
</html>

Demo:


Custom – jQuery API

Custom

  • Number jQuery.fx.interval

    New in 1.4.3 !

    The rate (in milliseconds) at which animations fire.

  • jQuery .delay( [ Integer ] duration, [ String ] queueName )

    New in 1.4 !

    Set a timer to delay execution of subsequent items in the queue.

  • Boolean jQuery.fx.off

    New in 1.3 !

    Globally disable all animations.

  • jQuery .clearQueue( [ String ] queueName )

    New in 1.4 !

    Remove from the queue all items that have not yet been run.

  • jQuery .dequeue( [ String ] queueName )

    New in 1.2 !

    Execute the next function on the queue for the matched elements.

  • jQuery .queue( [ String ] queueName, [ Function ] callback( next ) )

    New in 1.2 !

    Manipulate the queue of functions to be executed on the matched elements.

  • jQuery .stop( [ Boolean ] clearQueue, [ Boolean ] jumpToEnd )

    New in 1.2 !

    Stop the currently-running animation on the matched elements.

  • jQuery .animate( [ Map ] properties, [ Map ] options )

    New in 1.0 !

    Perform a custom animation of a set of CSS properties.


jQuery.fx.interval – jQuery API

Returns: NumberNumber jQuery.fx.interval

Categories: Custom, Properties of the Global jQuery Object, Version 1.4.3
Description: The rate (in milliseconds) at which animations fire.
  • version added: 1.4.3
  • jQuery.fx.interval

This property can be manipulated to adjust the number of frames per second at which animations will run. The default is 13 milliseconds. Making this a lower number could make the animations run smoother in faster browsers (such as Chrome) but there may be performance and CPU implications of doing so.

Since jQuery uses one global interval, no animation should be running or all animations should stop for the change of this property to take effect.

Examples:

Example:

Cause all animations to run with less frames.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:50px; height:30px; margin:5px; float:left;
          background:green; }</style>
</head>
<body>
  <p><input type="button" value="Run"/></p>
<div></div>
  <script>jQuery.fx.interval = 100;

$("input").click(function(){
  $("div").toggle( 3000 );
});</script>
</body>
</html>

Demo:


delay – jQuery API

Returns: jQueryjQuery .delay( [ Integer ] duration, [ String ] queueName )

Categories: Custom, Version 1.4
Description: Set a timer to delay execution of subsequent items in the queue.
  • version added: 1.4
  • .delay( [ Integer ] duration, [ String ] queueName )
  • duration An integer indicating the number of milliseconds to delay execution of the next item in the queue.
  • queueName A string containing the name of the queue. Defaults to , the standard effects queue.

Added to jQuery in version 1.4, the method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will delay the no-arguments forms of or which do not use the effects queue.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings and can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

Using the standard effects queue, we can, for example, set an 800-millisecond delay between the and of :

$('#foo').slideUp(300).delay(800).fadeIn(400);

When this statement is executed, the element slides up for 300 milliseconds and then pauses for 800 milliseconds before fading in for 400 milliseconds.

Examples:

Example:

Animate the hiding and showing of two divs, delaying the first before showing it.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width: 60px; height: 60px; float: left; }
.first { background-color: #3f3; }
.second { background-color: #33f;}</style>
</head>
<body>

<p><button>Run</button></p>
<div class="first"></div>
<div class="second"></div>

  <script>$("button").click(function() {
      $("div.first").slideUp(300).delay(800).fadeIn(400);
      $("div.second").slideUp(300).fadeIn(400);
    });</script>
</body>
</html>

Demo:


jQuery.fx.off – jQuery API

Returns: BooleanBoolean jQuery.fx.off

Categories: Custom, Properties of the Global jQuery Object, Version 1.3
Description: Globally disable all animations.
  • version added: 1.3
  • jQuery.fx.off

When this property is set to , all animation methods will immediately set elements to their final state when called, rather than displaying an effect. This may be desirable for a couple reasons:

Animations can be turned back on by setting the property to .

Examples:

Example:

Toggle animation on and off
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:50px; height:30px; margin:5px; float:left;
          background:green; }</style>
</head>
<body>
  <p><input type="button" value="Run"/> <button>Toggle fx</button></p>
<div></div>
  <script>var toggleFx = function() {
  $.fx.off = !$.fx.off;
};
toggleFx();

$("button").click(toggleFx)

$("input").click(function(){
  $("div").toggle("slow");
});</script>
</body>
</html>

Demo:


stop – jQuery API

Returns: jQueryjQuery .stop( [ Boolean ] clearQueue, [ Boolean ] jumpToEnd )

Categories: Custom, Version 1.2
Description: Stop the currently-running animation on the matched elements.
  • version added: 1.2
  • .stop( [ Boolean ] clearQueue, [ Boolean ] jumpToEnd )
  • clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to .
  • jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to .

When is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with when is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called.

If more than one animation method is called on the same element, the later animations are placed in the effects queue for the element. These animations will not begin until the first one completes. When is called, the next animation in the queue begins immediately. If the parameter is provided with a value of , then the rest of the animations in the queue are removed and never run.

If the property is provided with a value of , the current animation stops, but the element is immediately given its target values for each CSS property. In our above example, the element would be immediately hidden. The callback function is then immediately called, if provided.

The usefulness of the method is evident when we need to animate an element on and :

<div id="hoverme">
  Hover me
  <img id="hoverme" src="book.png" alt="" width="100" height="123" />
</div>

We can create a nice fade effect without the common problem of multiple queued animations by adding to the chain:

$('#hoverme-stop-2').hover(function() {
  $(this).find('img').stop(true, true).fadeOut();
}, function() {
  $(this).find('img').stop(true, true).fadeIn();
});

Examples:

Example:

Click the Go button once to start the animation, then click the STOP button to stop it where it's currently positioned. Another option is to click several buttons to queue them up and see that stop just kills the currently playing one.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div {
position: absolute;
background-color: #abc;
left: 0px;
top:30px;
width: 60px;
height: 60px;
margin: 5px;
}</style>
</head>
<body>
  <button id="go">Go</button>
<button id="stop">STOP!</button>
<button id="back">Back</button>
<div class="block"></div>
  <script>// Start animation
$("#go").click(function(){
$(".block").animate({left: '+=100px'}, 2000);
});

// Stop animation when button is clicked
$("#stop").click(function(){
$(".block").stop();
});

// Start animation in the opposite direction
$("#back").click(function(){
$(".block").animate({left: '-=100px'}, 2000);
});</script>
</body>
</html>

Demo:


animate – jQuery API

Returns: jQueryjQuery .animate( [ Map ] properties, [ Map ] options )

Categories: Custom, Version 1.0
Description: Perform a custom animation of a set of CSS properties.
  • version added: 1.0
  • .animate( [ Map ] properties, [ String,Number ] duration, [ String ] easing, [ Function ] complete )
  • properties A map of CSS properties that the animation will move toward.
  • duration A string or number determining how long the animation will run.
  • easing A string indicating which easing function to use for the transition.
  • complete A function to call once the animation is complete.
  • version added: 1.0
  • .animate( [ Map ] properties, [ Map ] options )
  • properties A map of CSS properties that the animation will move toward.
  • options A map of additional options to pass to the method. Supported keys:

The method allows us to create animation effects on any numeric CSS property. The only required parameter is a map of CSS properties. This map is similar to the one that can be sent to the method, except that the range of properties is more restrictive.

Animation Properties and Values

All animated properties should be animated to a , except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, , , or can be animated but cannot be.) Property values are treated as a number of pixels unless otherwise specified. The units and can be specified where applicable.

In addition to style properties, some non-style properties such as and , as well as custom properties, can be animated.

Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: and , and so on.

In addition to numeric values, each property can take the strings , , and . These shortcuts allow for custom hiding and showing animations that take into account the display type of the element.

Animated properties can also be relative. If a value is supplied with a leading or sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.

Unlike shorthand animation methods such as and , the method does make hidden elements visible as part of the effect. For example, given , the animation will run, but .

Duration

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings and can be supplied to indicate durations of and milliseconds, respectively.

Complete Function

If supplied, the callback function is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but is set to the DOM element being animated. If multiple elements are animated, the callback is executed once per matched element, not once for the animation as a whole.

Basic Usage

To animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123"
  style="position: relative; left: 10px;" />

To animate the opacity, left offset, and height of the image simultaneously:

$('#clickme').click(function() {
  $('#book').animate({
    opacity: 0.25,
    left: '+=50',
    height: 'toggle'
  }, 5000, function() {
    // Animation complete.
  });
});

Note that the target value of the property is . Since the image was visible before, the animation shrinks the height to 0 to hide it. A second click then reverses this transition:

The of the image is already at its target value, so this property is not animated by the second click. Since the target value for is a relative value, the image moves even farther to the right during this second animation.

Directional properties (, , , ) have no discernible effect on elements if their style property is , which it is by default.

Step Function

The second version of provides a option — a callback function that is fired at each step of the animation. This function is useful for enabling custom animation types or altering the animation as it is occurring. It accepts two arguments ( and ), and is set to the DOM element being animated.

Note that the function is called for each animated property on each animated element. For example, given two list items, the function fires four times at each step of the animation:

$('li').animate({
  opacity: .5,
  height: '50%'
},
{
  step: function(now, fx) {
    var data = fx.elem.id + ' ' + fx.prop + ': ' + now;
    $('body').append('<div>' + data + '</div>');
  }
});

Easing

The remaining parameter of is a string naming an easing function to use. An easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called , and one that progresses at a constant pace, called . More easing functions are available with the use of plug-ins, most notably the .

Per-property Easing

As of jQuery version 1.4, you can set per-property easing functions within a single call. In the first version of , each property can take an array as its value: The first member of the array is the CSS property and the second member is an easing function. If a per-property easing function is not defined for a particular property, it uses the value of the method's optional easing argument. If the easing argument is not defined, the default function is used.

For example, to simultaneously animate the width and height with the easing function and the opacity with the easing function:

$('#clickme').click(function() {
  $('#book').animate({
    width: ['toggle', 'swing'],
    height: ['toggle', 'swing'],
    opacity: 'toggle'
  }, 5000, 'linear', function() {
      $(this).after('<div>Animation complete.</div>');
  });
});

In the second version of , the options map can include the property, which is itself a map of CSS properties and their corresponding easing functions. For example, to simultaneously animate the width using the easing function and the height using the easing function:

$('#clickme').click(function() {
  $('#book').animate({
    width: 'toggle',
    height: 'toggle'
  }, {
    duration: 5000,
    specialEasing: {
      width: 'linear',
      height: 'easeOutBounce'
    },
    complete: function() {
      $(this).after('<div>Animation complete.</div>');
    }
  });
});

As previously noted, a plugin is required for the function.

Examples:

Example:

Click the button to animate the div with a number of different properties.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div {
background-color:#bca;
width:100px;
border:1px solid green;
}</style>
</head>
<body>
  <button id="go">&raquo; Run</button>

<div id="block">Hello!</div>
  <script>/* Using multiple unit types within one animation. */

$("#go").click(function(){
  $("#block").animate({
    width: "70%",
    opacity: 0.4,
    marginLeft: "0.6in",
    fontSize: "3em",
    borderWidth: "10px"
  }, 1500 );
});</script>
</body>
</html>

Demo:

Example:

Animates a div's left property with a relative value. Click several times on the buttons to see the relative animations queued up.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div {
  position:absolute;
  background-color:#abc;
  left:50px;
  width:90px;
  height:90px;
  margin:5px;
}</style>
</head>
<body>
  <button id="left">&laquo;</button> <button id="right">&raquo;</button>
<div class="block"></div>

  <script>$("#right").click(function(){
  $(".block").animate({"left": "+=50px"}, "slow");
});

$("#left").click(function(){
  $(".block").animate({"left": "-=50px"}, "slow");
});</script>
</body>
</html>

Demo:

Example:

The first button shows how an unqueued animation works. It expands the div out to 90% width the font-size is increasing. Once the font-size change is complete, the border animation will begin. The second button starts a traditional chained animation, where each animation will start once the previous animation on the element has completed.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div {
  background-color:#bca;
  width:200px;
  height:1.1em;
  text-align:center;
  border:2px solid green;
  margin:3px;
  font-size:14px;
}
button {
  font-size:14px;
}</style>
</head>
<body>
  <button id="go1">&raquo; Animate Block1</button>
<button id="go2">&raquo; Animate Block2</button>
<button id="go3">&raquo; Animate Both</button>

<button id="go4">&raquo; Reset</button>
<div id="block1">Block1</div>
<div id="block2">Block2</div>
  <script>$( "#go1" ).click(function(){
  $( "#block1" ).animate( { width: "90%" }, { queue: false, duration: 3000 })
     .animate({ fontSize: "24px" }, 1500 )
     .animate({ borderRightWidth: "15px" }, 1500 );
});

$( "#go2" ).click(function(){
  $( "#block2" ).animate({ width: "90%" }, 1000 )
     .animate({ fontSize: "24px" }, 1000 )
     .animate({ borderLeftWidth: "15px" }, 1000 );
});

$( "#go3" ).click(function(){
  $( "#go1" ).add( "#go2" ).click();
});

$( "#go4" ).click(function(){
  $( "div" ).css({ width: "", fontSize: "", borderWidth: "" });
});</script>
</body>
</html>

Demo:

Example:

Animates the first div's left property and synchronizes the remaining divs, using the step function to set their left properties at each stage of the animation.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div {
   position: relative;
   background-color: #abc;
   width: 40px;
   height: 40px;
   float: left;
   margin: 5px;
}</style>
</head>
<body>

<p><button id="go">Run »</button></p>
<div class="block"></div> <div class="block"></div>
<div class="block"></div> <div class="block"></div>
<div class="block"></div> <div class="block"></div>

  <script>$( "#go" ).click(function(){
  $( ".block:first" ).animate({
    left: 100
  }, {
    duration: 1000,
    step: function( now, fx ){
      $( ".block:gt(0)" ).css( "left", now );
    }
  });
});</script>
</body>
</html>

Demo:

Example:

Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.
$( "p" ).animate({
  "height": "toggle", "opacity": "toggle"
}, "slow" );

Example:

Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds.
$( "p" ).animate({
  "left": "50", "opacity": 1
}, 500 );

Example:

An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. Note, this code will do nothing unless the paragraph element is hidden.
$( "p" ).animate({
  "opacity": "show"
}, "slow", "easein" );

Example:

Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.
$( "p" ).animate({
  "height": "toggle", "opacity": "toggle"
}, { duration: "slow" });

Example:

Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. It also will do it the queue, meaning it will automatically start without waiting for its turn.
$( "p" ).animate({
  left: "50px", opacity: 1
}, { duration: 500, queue: false });

Example:

An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function.
$( "p" ).animate({
  "opacity": "show"
}, { "duration": "slow", "easing": "easein" });

Example:

An example of using a callback function. The first argument is an array of CSS properties, the second specifies that the animation should take 1000 milliseconds to complete, the third states the easing type, and the fourth argument is an anonymous callback function.
$( "p" ).animate({
  height:200, width:400, opacity: .5
}, 1000, "linear", function(){ alert("all done"); });


Fading – jQuery API

Fading

  • jQuery .fadeToggle( [ String,Number ] duration, [ String ] easing, [ Function ] callback )

    New in 1.4.4 !

    Display or hide the matched elements by animating their opacity.

  • jQuery .fadeTo( [ String,Number ] duration, [ Number ] opacity, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Adjust the opacity of the matched elements.

  • jQuery .fadeOut( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements by fading them to transparent.

  • jQuery .fadeIn( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements by fading them to opaque.


fadeToggle – jQuery API

Returns: jQueryjQuery .fadeToggle( [ String,Number ] duration, [ String ] easing, [ Function ] callback )

Categories: Effects, Fading, Version 1.4.4
Description: Display or hide the matched elements by animating their opacity.
  • version added: 1.4.4
  • .fadeToggle( [ String,Number ] duration, [ String ] easing, [ Function ] callback )
  • duration A string or number determining how long the animation will run.
  • easing A string indicating which easing function to use for the transition.
  • callback A function to call once the animation is complete.

The method animates the opacity of the matched elements. When called on a visible element, the element's style property is set to once the opacity reaches 0, so the element no longer affects the layout of the page.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings and can be supplied to indicate durations of and milliseconds, respectively.

The string representing an easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called , and one that progresses at a constant pace, called . More easing functions are available with the use of plug-ins, most notably the .

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

Examples:

Example:

Fades first paragraph in or out, completing the animation within 600 milliseconds and using a linear easing. Fades last paragraph in or out for 200 milliseconds, inserting a "finished" message upon completion.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

<button>fadeToggle p1</button>
<button>fadeToggle p2</button>
<p>This paragraph has a slow, linear fade.</p>

<p>This paragraph has a fast animation.</p>
<div id="log"></div>

  <script>$("button:first").click(function() {
  $("p:first").fadeToggle("slow", "linear");
});
$("button:last").click(function () {
  $("p:last").fadeToggle("fast", function () {
    $("#log").append("<div>finished</div>");
  });
});</script>
</body>
</html>

Demo:


fadeTo – jQuery API

Returns: jQueryjQuery .fadeTo( [ String,Number ] duration, [ Number ] opacity, [ String ] easing, [ Callback ] callback )

Categories: Fading, Version 1.0, Version 1.4.3
Description: Adjust the opacity of the matched elements.
  • version added: 1.0
  • .fadeTo( [ String,Number ] duration, [ Number ] opacity, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • opacity A number between 0 and 1 denoting the target opacity.
  • callback A function to call once the animation is complete.
  • version added: 1.4.3
  • .fadeTo( [ String,Number ] duration, [ Number ] opacity, [ String ] easing, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • opacity A number between 0 and 1 denoting the target opacity.
  • easing A string indicating which easing function to use for the transition.
  • callback A function to call once the animation is complete.

The method animates the opacity of the matched elements.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings and can be supplied to indicate durations of and milliseconds, respectively. If any other string is supplied, the default duration of milliseconds is used. Unlike the other effect methods, requires that be explicitly specified.

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

We can animate any element, such as a simple image:

<div id="clickme">
    Click here
  </div>
  <img id="book" src="book.png" alt="" width="100" height="123" />
  With the element initially shown, we can dim it slowly:
  $('#clickme').click(function() {
    $('#book').fadeTo('slow', 0.5, function() {
      // Animation complete.
    });
  });

With set to , this method just changes the CSS property, so is the same as .

Examples:

Example:

Animates first paragraph to fade to an opacity of 0.33 (33%, about one third visible), completing the animation within 600 milliseconds.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>
Click this paragraph to see it fade.
</p>

<p>
Compare to this one that won't fade.
</p>
  <script>$("p:first").click(function () {
$(this).fadeTo("slow", 0.33);
});</script>
</body>
</html>

Demo:

Example:

Fade div to a random opacity on each click, completing the animation within 200 milliseconds.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { width:80px; margin:0; padding:5px; }
div { width:40px; height:40px; position:absolute; }
div#one { top:0; left:0; background:#f00; }
div#two { top:20px; left:20px; background:#0f0; }
div#three { top:40px; left:40px; background:#00f; }</style>
</head>
<body>
  <p>And this is the library that John built...</p>

<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
  <script>$("div").click(function () {
$(this).fadeTo("fast", Math.random());
});</script>
</body>
</html>

Demo:

Example:

Find the right answer! The fade will take 250 milliseconds and change various styles when it completes.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div, p { width:80px; height:40px; top:0; margin:0;
position:absolute; padding-top:8px; }
p { background:#fcc; text-align:center; }
div { background:blue; }</style>
</head>
<body>
  <p>Wrong</p>
<div></div>
<p>Wrong</p>
<div></div>

<p>Right!</p>
<div></div>
  <script>var getPos = function (n) {
return (Math.floor(n) * 90) + "px";
};
$("p").each(function (n) {
var r = Math.floor(Math.random() * 3);
var tmp = $(this).text();
$(this).text($("p:eq(" + r + ")").text());
$("p:eq(" + r + ")").text(tmp);
$(this).css("left", getPos(n));
});
$("div").each(function (n) {
      $(this).css("left", getPos(n));
    })
.css("cursor", "pointer")
.click(function () {
      $(this).fadeTo(250, 0.25, function () {
            $(this).css("cursor", "")
                   .prev().css({"font-weight": "bolder",
                                "font-style": "italic"});
          });
    });</script>
</body>
</html>

Demo:


fadeOut – jQuery API

Returns: jQueryjQuery .fadeOut( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

Categories: Fading, Version 1.0, Version 1.4.3
Description: Hide the matched elements by fading them to transparent.
  • version added: 1.0
  • .fadeOut( [ String,Number ] duration, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • callback A function to call once the animation is complete.
  • version added: 1.4.3
  • .fadeOut( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • easing A string indicating which easing function to use for the transition.
  • callback A function to call once the animation is complete.

The method animates the opacity of the matched elements. Once the opacity reaches 0, the style property is set to , so the element no longer affects the layout of the page.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings and can be supplied to indicate durations of and milliseconds, respectively. If any other string is supplied, or if the parameter is omitted, the default duration of milliseconds is used.

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called , and one that progresses at a constant pace, called . More easing functions are available with the use of plug-ins, most notably the .

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

We can animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />

With the element initially shown, we can hide it slowly:

$('#clickme').click(function() {
  $('#book').fadeOut('slow', function() {
    // Animation complete.
  });
});

Examples:

Example:

Animates all paragraphs to fade out, completing the animation within 600 milliseconds.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { font-size:150%; cursor:pointer; }</style>
</head>
<body>
  <p>
  If you click on this paragraph
  you'll see it just fade away.
  </p>
  <script>$("p").click(function () {
  $("p").fadeOut("slow");
  });</script>
</body>
</html>

Demo:

Example:

Fades out spans in one section that you click on.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span { cursor:pointer; }
  span.hilite { background:yellow; }
  div { display:inline; color:red; }</style>
</head>
<body>
  <h3>Find the modifiers - <div></div></h3>
  <p>
  If you <span>really</span> want to go outside
  <span>in the cold</span> then make sure to wear
  your <span>warm</span> jacket given to you by
  your <span>favorite</span> teacher.
  </p>
  <script>$("span").click(function () {
  $(this).fadeOut(1000, function () {
  $("div").text("'" + $(this).text() + "' has faded!");
  $(this).remove();
  });
  });
  $("span").hover(function () {
  $(this).addClass("hilite");
  }, function () {
  $(this).removeClass("hilite");
  });</script>
</body>
</html>

Demo:

Example:

Fades out two divs, one with a "linear" easing and one with the default, "swing," easing.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>.box,
button { float:left; margin:5px 10px 5px 0; }
.box { height:80px; width:80px; background:#090; }
#log { clear:left; }</style>
</head>
<body>

<button id="btn1">fade out</button>
<button id="btn2">show</button>

<div id="log"></div>

<div id="box1" class="box">linear</div>
<div id="box2" class="box">swing</div>

  <script>$("#btn1").click(function() {
  function complete() {
    $("<div/>").text(this.id).appendTo("#log");
  }

  $("#box1").fadeOut(1600, "linear", complete);
  $("#box2").fadeOut(1600, complete);
});

$("#btn2").click(function() {
  $("div").show();
  $("#log").empty();
});</script>
</body>
</html>

Demo:


fadeIn – jQuery API

Returns: jQueryjQuery .fadeIn( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

Categories: Fading, Version 1.0, Version 1.4.3
Description: Display the matched elements by fading them to opaque.
  • version added: 1.0
  • .fadeIn( [ String,Number ] duration, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • callback A function to call once the animation is complete.
  • version added: 1.4.3
  • .fadeIn( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • easing A string indicating which easing function to use for the transition.
  • callback A function to call once the animation is complete.

The method animates the opacity of the matched elements.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings and can be supplied to indicate durations of and milliseconds, respectively. If any other string is supplied, or if the parameter is omitted, the default duration of milliseconds is used.

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called , and one that progresses at a constant pace, called . More easing functions are available with the use of plug-ins, most notably the .

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

We can animate any element, such as a simple image:

<div id="clickme">
      Click here
    </div>
    <img id="book" src="book.png" alt="" width="100" height="123" />
    With the element initially hidden, we can show it slowly:
    $('#clickme').click(function() {
      $('#book').fadeIn('slow', function() {
        // Animation complete
      });
    });

Examples:

Example:

Animates hidden divs to fade in one by one, completing each animation within 600 milliseconds.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span { color:red; cursor:pointer; }
    div { margin:3px; width:80px; display:none;
      height:80px; float:left; }
      div#one { background:#f00; }
      div#two { background:#0f0; }
      div#three { background:#00f; }</style>
</head>
<body>
  <span>Click here...</span>

    <div id="one"></div>
    <div id="two"></div>
    <div id="three"></div>
  <script>$(document.body).click(function () {
        $("div:hidden:first").fadeIn("slow");
      });</script>
</body>
</html>

Demo:

Example:

Fades a red block in over the text. Once the animation is done, it quickly fades in more text on top.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { position:relative; width:400px; height:90px; }
      div { position:absolute; width:400px; height:65px;
        font-size:36px; text-align:center;
        color:yellow; background:red;
        padding-top:25px;
        top:0; left:0; display:none; }
        span { display:none; }</style>
</head>
<body>
  <p>
        Let it be known that the party of the first part
        and the party of the second part are henceforth
        and hereto directed to assess the allegations
        for factual correctness... (<a href="#">click!</a>)
        <div><span>CENSORED!</span></div>

      </p>
  <script>$("a").click(function () {
          $("div").fadeIn(3000, function () {
            $("span").fadeIn(100);
          });
          return false;
        });</script>
</body>
</html>

Demo:


Sliding – jQuery API

Sliding

  • jQuery .slideToggle( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display or hide the matched elements with a sliding motion.

  • jQuery .slideUp( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements with a sliding motion.

  • jQuery .slideDown( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements with a sliding motion.


slideToggle – jQuery API

Returns: jQueryjQuery .slideToggle( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

Categories: Sliding, Version 1.0, Version 1.4.3
Description: Display or hide the matched elements with a sliding motion.
  • version added: 1.0
  • .slideToggle( [ String,Number ] duration, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • callback A function to call once the animation is complete.
  • version added: 1.4.3
  • .slideToggle( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • easing A string indicating which easing function to use for the transition.
  • callback A function to call once the animation is complete.

The method animates the height of the matched elements. This causes lower parts of the page to slide up or down, appearing to reveal or conceal the items. If the element is initially displayed, it will be hidden; if hidden, it will be shown. The property is saved and restored as needed. If an element has a value of , then is hidden and shown, it will once again be displayed . When the height reaches 0 after a hiding animation, the style property is set to to ensure that the element no longer affects the layout of the page.

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called , and one that progresses at a constant pace, called . More easing functions are available with the use of plug-ins, most notably the .

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings and can be supplied to indicate durations of and milliseconds, respectively.

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

We can animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />

We will cause to be called when another element is clicked:

$('#clickme').click(function() {
  $('#book').slideToggle('slow', function() {
    // Animation complete.
  });
});

With the element initially shown, we can hide it slowly with the first click:

A second click will show the element once again:

Examples:

Example:

Animates all paragraphs to slide up or down, completing the animation within 600 milliseconds.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { width:400px; }</style>
</head>
<body>
  <button>Toggle</button>

  <p>
    This is the paragraph to end all paragraphs.  You
    should feel <em>lucky</em> to have seen such a paragraph in
    your life.  Congratulations!
  </p>
  <script>$("button").click(function () {
      $("p").slideToggle("slow");
    });</script>
</body>
</html>

Demo:

Example:

Animates divs between dividers with a toggle that makes some appear and some disappear.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { background:#b977d1; margin:3px; width:60px;
        height:60px; float:left; }
  div.still { background:#345; width:5px; }
  div.hider { display:none; }
  span { color:red; }
  p { clear: left; }</style>
</head>
<body>
  <div></div>
<div class="still"></div>
<div style="display:none;">
</div><div class="still"></div>
<div></div>
<div class="still"></div>
<div class="hider"></div>
<div class="still"></div>
<div class="hider"></div>
<div class="still"></div>
<div></div>
<p><button id="aa">Toggle</button> There have been <span>0</span> toggled divs.</p>
  <script>$("#aa").click(function () {
    $("div:not(.still)").slideToggle("slow", function () {
      var n = parseInt($("span").text(), 10);
      $("span").text(n + 1);
    });
  });</script>
</body>
</html>

Demo:


slideUp – jQuery API

Returns: jQueryjQuery .slideUp( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

Categories: Sliding, Version 1.0, Version 1.4.3
Description: Hide the matched elements with a sliding motion.
  • version added: 1.0
  • .slideUp( [ String,Number ] duration, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • callback A function to call once the animation is complete.
  • version added: 1.4.3
  • .slideUp( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • easing A string indicating which easing function to use for the transition.
  • callback A function to call once the animation is complete.

The method animates the height of the matched elements. This causes lower parts of the page to slide up, appearing to conceal the items. Once the height reaches 0, the style property is set to to ensure that the element no longer affects the layout of the page.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings and can be supplied to indicate durations of and milliseconds, respectively. If any other string is supplied, or if the parameter is omitted, the default duration of milliseconds is used.

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called , and one that progresses at a constant pace, called . More easing functions are available with the use of plug-ins, most notably the .

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

We can animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />

With the element initially shown, we can hide it slowly:

$('#clickme').click(function() {
  $('#book').slideUp('slow', function() {
    // Animation complete.
  });
});

Examples:

Example:

Animates all divs to slide up, completing the animation within 400 milliseconds.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { background:#3d9a44; margin:3px; width:80px;
    height:40px; float:left; }</style>
</head>
<body>
  Click me!
  <div></div>
  <div></div>
  <div></div>
  <div></div>

  <div></div>
  <script>$(document.body).click(function () {
    if ($("div:first").is(":hidden")) {
      $("div").show("slow");
    } else {
      $("div").slideUp();
    }
  });</script>
</body>
</html>

Demo:

Example:

Animates the parent paragraph to slide up, completing the animation within 200 milliseconds. Once the animation is done, it displays an alert.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { margin:2px; }</style>
</head>
<body>
  <div>
  <button>Hide One</button>
  <input type="text" value="One" />

</div>
<div>
  <button>Hide Two</button>
  <input type="text" value="Two" />

</div>
<div>
  <button>Hide Three</button>
  <input type="text" value="Three" />

</div>
<div id="msg"></div>
  <script>$("button").click(function () {
    $(this).parent().slideUp("slow", function () {
      $("#msg").text($("button", this).text() + " has completed.");
    });
  });</script>
</body>
</html>

Demo:


slideDown – jQuery API

Returns: jQueryjQuery .slideDown( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

Categories: Sliding, Version 1.0, Version 1.4.3
Description: Display the matched elements with a sliding motion.
  • version added: 1.0
  • .slideDown( [ String,Number ] duration, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • callback A function to call once the animation is complete.
  • version added: 1.4.3
  • .slideDown( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )
  • duration A string or number determining how long the animation will run.
  • easing A string indicating which easing function to use for the transition.
  • callback A function to call once the animation is complete.

The method animates the height of the matched elements. This causes lower parts of the page to slide down, making way for the revealed items.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings and can be supplied to indicate durations of and milliseconds, respectively. If any other string is supplied, or if the parameter is omitted, the default duration of milliseconds is used.

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called , and one that progresses at a constant pace, called . More easing functions are available with the use of plug-ins, most notably the .

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

We can animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />

With the element initially hidden, we can show it slowly:

$('#clickme').click(function() {
  $('#book').slideDown('slow', function() {
    // Animation complete.
  });
});

Examples:

Example:

Animates all divs to slide down and show themselves over 600 milliseconds.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { background:#de9a44; margin:3px; width:80px;
height:40px; display:none; float:left; }</style>
</head>
<body>
  Click me!
<div></div>
<div></div>
<div></div>
  <script>$(document.body).click(function () {
if ($("div:first").is(":hidden")) {
$("div").slideDown("slow");
} else {
$("div").hide();
}
});</script>
</body>
</html>

Demo:

Example:

Animates all inputs to slide down, completing the animation within 1000 milliseconds. Once the animation is done, the input look is changed especially if it is the middle input which gets the focus.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { background:#cfd; margin:3px; width:50px;
text-align:center; float:left; cursor:pointer;
border:2px outset black; font-weight:bolder; }
input { display:none; width:120px; float:left;
margin:10px; }</style>
</head>
<body>
  <div>Push!</div>
<input type="text" />
<input type="text" class="middle" />

<input type="text" />
  <script>$("div").click(function () {
$(this).css({ borderStyle:"inset", cursor:"wait" });
$("input").slideDown(1000,function(){
$(this).css("border", "2px red inset")
.filter(".middle")
 .css("background", "yellow")
 .focus();
$("div").css("visibility", "hidden");
});
});</script>
</body>
</html>

Demo:


Events – jQuery API

Events

  • jQuery .scroll( )

    New in 1.0 !

    Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.

  • jQuery .resize( )

    New in 1.0 !

    Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.

  • jQuery .error( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "error" JavaScript event.

  • jQuery .unload( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "unload" JavaScript event.

  • jQuery .load( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "load" JavaScript event.

  • jQuery .ready( [ Function ] handler )

    New in 1.0 !

    Specify a function to execute when the DOM is fully loaded.

  • jQuery .undelegate( [ String ] namespace )

    New in 1.6 !

    Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.

  • jQuery .delegate( [ String ] selector, [ Map ] events )

    New in 1.4.3 !

    Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

  • Function jQuery.proxy( [ Object ] context, [ String ] name )

    New in 1.4 !

    Takes a function and returns a new one that will always have a particular context.

  • jQuery .die( [ Map ] eventTypes )

    New in 1.4.3 !

    Remove an event handler previously attached using from the elements.

  • jQuery .live( [ Object ] events )

    New in 1.4.3 !

    Attach a handler to the event for all elements which match the current selector, now and in the future.

  • Object .triggerHandler( [ String ] eventType, [ Array ] extraParameters )

    New in 1.2 !

    Execute all handlers attached to an element for an event.

  • jQuery .trigger( [ Event ] event )

    New in 1.3 !

    Execute all handlers and behaviors attached to the matched elements for the given event type.

  • jQuery .one( [ String ] eventType, [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.1 !

    Attach a handler to an event for the elements. The handler is executed at most once per element.

  • jQuery .unbind( [ Object ] event )

    New in 1.0 !

    Remove a previously-attached event handler from the elements.

  • jQuery .bind( [ Object ] events )

    New in 1.4 !

    Attach a handler to an event for the elements.

  • String event.namespace

    New in 1.4.3 !

    The namespace specified when the event was triggered.

  • Boolean event.isImmediatePropagationStopped( )

    New in 1.3 !

    Returns whether event.stopImmediatePropagation() was ever called on this event object.

  • event.stopImmediatePropagation( )

    New in 1.3 !

    Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.

  • Boolean event.isPropagationStopped( )

    New in 1.3 !

    Returns whether was ever called on this event object.

  • event.stopPropagation( )

    New in 1.0 !

    Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

  • Boolean event.isDefaultPrevented( )

    New in 1.3 !

    Returns whether was ever called on this event object.

  • undefined event.preventDefault( )

    New in 1.0 !

    If this method is called, the default action of the event will not be triggered.

  • Number event.timeStamp

    New in 1.2.6 !

    The difference in milliseconds between the time an event is triggered and January 1, 1970.

  • Object event.result

    New in 1.3 !

    The last value returned by an event handler that was triggered by this event, unless the value was .

  • Number event.which

    New in 1.1.3 !

    For key or button events, this attribute indicates the specific button or key that was pressed.

  • Number event.pageY

    New in 1.0.4 !

    The mouse position relative to the top edge of the document.

  • Number event.pageX

    New in 1.0.4 !

    The mouse position relative to the left edge of the document.

  • Element event.currentTarget

    New in 1.3 !

    The current DOM element within the event bubbling phase.

  • Element event.relatedTarget

    New in 1.1.4 !

    The other DOM element involved in the event, if any.

  • Anything event.data

    New in 1.1 !

    The optional data passed to jQuery.fn.bind when the current executing handler was bound.

  • Element event.target

    New in 1.0 !

    The DOM element that initiated the event.

  • String event.type

    New in 1.0 !

    Describes the nature of the event.

  • jQuery .submit( )

    New in 1.0 !

    Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

  • jQuery .select( )

    New in 1.0 !

    Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

  • jQuery .change( )

    New in 1.0 !

    Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

  • jQuery .blur( )

    New in 1.0 !

    Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.

  • jQuery .focus( )

    New in 1.0 !

    Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.

  • jQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusout" JavaScript event.

  • jQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusin" JavaScript event.

  • jQuery .keydown( )

    New in 1.0 !

    Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.

  • jQuery .keyup( )

    New in 1.0 !

    Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.

  • jQuery .keypress( )

    New in 1.0 !

    Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.

  • jQuery .toggle( [ Function ] handler(eventObject), [ Function ] handler(eventObject), [ Function ] handler(eventObject) )

    New in 1.0 !

    Bind two or more handlers to the matched elements, to be executed on alternate clicks.

  • jQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusout" JavaScript event.

  • jQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusin" JavaScript event.

  • jQuery .mousemove( )

    New in 1.0 !

    Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.

  • jQuery .hover( [ Function ] handlerInOut(eventObject) )

    New in 1.4 !

    Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.

  • jQuery .mouseleave( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.

  • jQuery .mouseenter( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

  • jQuery .mouseout( )

    New in 1.0 !

    Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.

  • jQuery .mouseover( )

    New in 1.0 !

    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • jQuery .dblclick( )

    New in 1.0 !

    Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.

  • jQuery .click( )

    New in 1.0 !

    Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

  • jQuery .mouseup( )

    New in 1.0 !

    Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.

  • jQuery .mousedown( )

    New in 1.0 !

    Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.


Browser Events – jQuery API

Browser Events

  • jQuery .scroll( )

    New in 1.0 !

    Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.

  • jQuery .resize( )

    New in 1.0 !

    Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.

  • jQuery .error( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "error" JavaScript event.


scroll – jQuery API

Returns: jQueryjQuery .scroll( )

Categories: Browser Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .scroll( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .scroll( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .scroll( )

This method is a shortcut for in the first and second variations, and in the third.

The event is sent to an element when the user scrolls to a different place in the element. It applies to objects, but also to scrollable frames and elements with the CSS property set to (or when the element's explicit height or width is less than the height or width of its contents).

For example, consider the HTML:

<div id="target" style="overflow: scroll; width: 200px; height: 100px;">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit,
  sed do eiusmod tempor incididunt ut labore et dolore magna
  aliqua. Ut enim ad minim veniam, quis nostrud exercitation
  ullamco laboris nisi ut aliquip ex ea commodo consequat.
  Duis aute irure dolor in reprehenderit in voluptate velit
  esse cillum dolore eu fugiat nulla pariatur. Excepteur
  sint occaecat cupidatat non proident, sunt in culpa qui
  officia deserunt mollit anim id est laborum.
</div>
<div id="other">
  Trigger the handler
</div>
<div id="log"></div>

The style definition is present to make the target element small enough to be scrollable:

The event handler can be bound to this element:

$('#target').scroll(function() {
  $('#log').append('<div>Handler for .scroll() called.</div>');
});

Now when the user scrolls the text up or down, one or more messages are appended to :

To trigger the event manually, apply without an argument:

$('#other').click(function() {
  $('#target').scroll();
});

After this code executes, clicks on will also append the message.

A event is sent whenever the element's scroll position changes, regardless of the cause. A mouse click or drag on the scroll bar, dragging inside the element, pressing the arrow keys, or using the mouse's scroll wheel could cause this event.

Examples:

Example:

To do something when your page is scrolled:
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:blue; }
  p { color:green; }
  span { color:red; display:none; }</style>
</head>
<body>
  <div>Try scrolling the iframe.</div>
  <p>Paragraph - <span>Scroll happened!</span></p>
  <script>$("p").clone().appendTo(document.body);
    $("p").clone().appendTo(document.body);
    $("p").clone().appendTo(document.body);
    $(window).scroll(function () {
      $("span").css("display", "inline").fadeOut("slow");
    });</script>
</body>
</html>

Demo:


resize – jQuery API

Returns: jQueryjQuery .resize( )

Categories: Browser Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .resize( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .resize( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .resize( )

This method is a shortcut for in the first and second variations, and in the third.

The event is sent to the element when the size of the browser window changes:

$(window).resize(function() {
  $('#log').append('<div>Handler for .resize() called.</div>');
});

Now whenever the browser window's size is changed, the message is appended to <div id="log"> one or more times, depending on the browser.

Code in a handler should never rely on the number of times the handler is called. Depending on implementation, events can be sent continuously as the resizing is in progress (the typical behavior in Internet Explorer and WebKit-based browsers such as Safari and Chrome), or only once at the end of the resize operation (the typical behavior in Firefox).

Examples:

Example:

To see the window width while (or after) it is resized, try:
$(window).resize(function() {
  $('body').prepend('<div>' + $(window).width() + '</div>');
});


error – jQuery API

Returns: jQueryjQuery .error( [ Object ] eventData, [ Function ] handler(eventObject) )

Categories: Browser Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "error" JavaScript event.
  • version added: 1.0
  • .error( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute when the event is triggered.
  • version added: 1.4.3
  • .error( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.

This method is a shortcut for .

The event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly.

For example, consider a page with a simple image element:

<img alt="Book" id="book" />

The event handler can be bound to the image:

$('#book')
  .error(function() {
    alert('Handler for .error() called.')
  })
  .attr("src", "missing.png");

If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:

Note: A jQuery error event handler should not be attached to the window object. The browser fires the window's error event when a script error occurs. However, the window error event receives different arguments and has different return value requirements than conventional event handlers. Use instead.

Examples:

Example:

To hide the "broken image" icons for IE users, you can try:
$("img")
  .error(function(){
    $(this).hide();
  })
  .attr("src", "missing.png");


Document Loading – jQuery API

Document Loading

  • jQuery .unload( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "unload" JavaScript event.

  • jQuery .load( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "load" JavaScript event.

  • jQuery .ready( [ Function ] handler )

    New in 1.0 !

    Specify a function to execute when the DOM is fully loaded.


unload – jQuery API

Returns: jQueryjQuery .unload( [ Object ] eventData, [ Function ] handler(eventObject) )

Categories: Document Loading, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "unload" JavaScript event.
  • version added: 1.0
  • .unload( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute when the event is triggered.
  • version added: 1.4.3
  • .unload( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.

This method is a shortcut for .

The event is sent to the element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an event.

Any event handler should be bound to the object:

$(window).unload(function() {
  alert('Handler for .unload() called.');
});

After this code executes, the alert will be displayed whenever the browser leaves the current page. It is not possible to cancel the event with . This event is available so that scripts can perform cleanup when the user leaves the page.

Examples:

Example:

To display an alert when a page is unloaded:
$(window).unload( function () { alert("Bye now!"); } );


ready – jQuery API

Returns: jQueryjQuery .ready( [ Function ] handler )

Categories: Document Loading, Version 1.0
Description: Specify a function to execute when the DOM is fully loaded.
  • version added: 1.0
  • .ready( [ Function ] handler )
  • handler A function to execute after the DOM is ready.

While JavaScript provides the event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the event instead.

All three of the following syntaxes are equivalent:

There is also . This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to the bound handler will not be executed. Ready handlers bound this way are executed any bound by the other three methods above.

The method can only be called on a jQuery object matching the current document, so the selector can be omitted.

The method is typically used with an anonymous function:

$(document).ready(function() {
  // Handler for .ready() called.
});

Which is equivalent to calling:

$(function() {
 // Handler for .ready() called.
});

If is called after the DOM has been initialized, the new handler passed in will be executed immediately.

Aliasing the jQuery Namespace

When using another JavaScript library, we may wish to call to avoid namespace difficulties. When this function is called, the shortcut is no longer available, forcing us to write each time we would normally write . However, the handler passed to the method can take an argument, which is passed the global object. This means we can rename the object within the context of our handler without affecting other code:

jQuery(document).ready(function($) {
  // Code using $ as usual goes here.
});

Examples:

Example:

Display a message when the DOM is loaded.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:red; }</style>
</head>
<body>
  <p>Not loaded yet.</p>
  <script>$(document).ready(function () {
  $("p").text("The DOM is now loaded and can be manipulated.");
});</script>
</body>
</html>

Demo:


Event Handler Attachment – jQuery API

Event Handler Attachment

  • jQuery .undelegate( [ String ] namespace )

    New in 1.6 !

    Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.

  • jQuery .delegate( [ String ] selector, [ Map ] events )

    New in 1.4.3 !

    Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

  • Function jQuery.proxy( [ Object ] context, [ String ] name )

    New in 1.4 !

    Takes a function and returns a new one that will always have a particular context.

  • jQuery .die( [ Map ] eventTypes )

    New in 1.4.3 !

    Remove an event handler previously attached using from the elements.

  • jQuery .live( [ Object ] events )

    New in 1.4.3 !

    Attach a handler to the event for all elements which match the current selector, now and in the future.

  • Object .triggerHandler( [ String ] eventType, [ Array ] extraParameters )

    New in 1.2 !

    Execute all handlers attached to an element for an event.

  • jQuery .trigger( [ Event ] event )

    New in 1.3 !

    Execute all handlers and behaviors attached to the matched elements for the given event type.

  • jQuery .one( [ String ] eventType, [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.1 !

    Attach a handler to an event for the elements. The handler is executed at most once per element.

  • jQuery .unbind( [ Object ] event )

    New in 1.0 !

    Remove a previously-attached event handler from the elements.

  • jQuery .bind( [ Object ] events )

    New in 1.4 !

    Attach a handler to an event for the elements.


undelegate – jQuery API

Returns: jQueryjQuery .undelegate( [ String ] namespace )

Categories: Event Handler Attachment, Version 1.4.2, Version 1.4.3, Version 1.6
Description: Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.
  • version added: 1.4.2
  • .undelegate( )
  • version added: 1.4.2
  • .undelegate( [ String ] selector, [ String ] eventType )
  • selector A selector which will be used to filter the event results.
  • eventType A string containing a JavaScript event type, such as "click" or "keydown"
  • version added: 1.4.2
  • .undelegate( [ String ] selector, [ String ] eventType, [ Function ] handler )
  • selector A selector which will be used to filter the event results.
  • eventType A string containing a JavaScript event type, such as "click" or "keydown"
  • handler A function to execute at the time the event is triggered.
  • version added: 1.4.3
  • .undelegate( [ String ] selector, [ Map ] events )
  • selector A selector which will be used to filter the event results.
  • events A map of one or more event types and previously bound functions to unbind from them.
  • version added: 1.6
  • .undelegate( [ String ] namespace )
  • namespace A string containing a namespace to unbind all events from.

Undelegate is a way of removing event handlers that have been bound using . It works virtually identically to with the addition of a selector filter argument (which is required for delegation to work).

Examples:

Example:

Can bind and unbind events to the colored button.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>button { margin:5px; }
button#theone { color:red; background:yellow; }</style>
</head>
<body>
  <button id="theone">Does nothing...</button>
<button id="bind">Bind Click</button>
<button id="unbind">Unbind Click</button>
<div style="display:none;">Click!</div>
  <script>function aClick() {
  $("div").show().fadeOut("slow");
}
$("#bind").click(function () {
  $("body").delegate("#theone", "click", aClick)
    .find("#theone").text("Can Click!");
});
$("#unbind").click(function () {
  $("body").undelegate("#theone", "click", aClick)
    .find("#theone").text("Does nothing...");
});</script>
</body>
</html>

Demo:

Example:

To unbind all delegated events from all paragraphs, write:
$("p").undelegate()

Example:

To unbind all delegated click events from all paragraphs, write:
$("p").undelegate( "click" )

Example:

To undelegate just one previously bound handler, pass the function in as the third argument:
var foo = function () {
// code to handle some kind of event
};

// ... now foo will be called when paragraphs are clicked ...
$("body").delegate("p", "click", foo);

// ... foo will no longer be called.
$("body").undelegate("p", "click", foo);

Example:

To unbind all delegated events by their namespace:
var foo = function () {
// code to handle some kind of event
};

// delegate events under the ".whatever" namespace
$("form").delegate("click.whatever", ":button", foo);

$("form").delegate("keypress.whatever", ":text", foo);

// unbind all events delegated under the ".whatever" namespace

$("form").undelegate(".whatever");


delegate – jQuery API

Returns: jQueryjQuery .delegate( [ String ] selector, [ Map ] events )

Categories: Event Handler Attachment, Version 1.4.2, Version 1.4.3
Description: Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
  • version added: 1.4.2
  • .delegate( [ String ] selector, [ String ] eventType, [ Function ] handler )
  • selector A selector to filter the elements that trigger the event.
  • eventType A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.
  • handler A function to execute at the time the event is triggered.
  • version added: 1.4.2
  • .delegate( [ String ] selector, [ String ] eventType, [ Object ] eventData, [ Function ] handler )
  • selector A selector to filter the elements that trigger the event.
  • eventType A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.
  • eventData A map of data that will be passed to the event handler.
  • handler A function to execute at the time the event is triggered.
  • version added: 1.4.3
  • .delegate( [ String ] selector, [ Map ] events )
  • selector A selector to filter the elements that trigger the event.
  • events A map of one or more event types and functions to execute for them.

Delegate is an alternative to using the method, allowing for each binding of event delegation to specific DOM elements. For example the following delegate code:

$("table").delegate("td", "hover", function(){
    $(this).toggleClass("hover");
});

Is equivalent to the following code written using :

$("table").each(function(){
    $("td", this).live("hover", function(){
        $(this).toggleClass("hover");
    });
});

See also the method for a way of removing event handlers added in .

Passing and handling event data works .

Examples:

Example:

Click a paragraph to add another. Note that .delegate() binds the click event to all paragraphs - even new ones.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; font-weight:bold; cursor:pointer;
      padding:5px; }
  p.over { background: #ccc; }
  span { color:red; }</style>
</head>
<body>
  <p>Click me!</p>

  <span></span>
  <script>$("body").delegate("p", "click", function(){
      $(this).after("<p>Another paragraph!</p>");
    });</script>
</body>
</html>

Demo:

Example:

To display each paragraph's text in an alert box whenever it is clicked:
$("body").delegate("p", "click", function(){
  alert( $(this).text() );
});

Example:

To cancel a default action and prevent it from bubbling up, return false:
$("body").delegate("a", "click", function() { return false; })

Example:

To cancel only the default action by using the preventDefault method.
$("body").delegate("a", "click", function(event){
  event.preventDefault();
});

Example:

Can bind custom events too.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:red; }
  span { color:blue; }</style>
</head>
<body>
  <p>Has an attached custom event.</p>
  <button>Trigger custom event</button>
  <span style="display:none;"></span>
  <script>$("body").delegate("p", "myCustomEvent", function(e, myName, myValue){
      $(this).text("Hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent");
    });</script>
</body>
</html>

Demo:


jQuery.proxy – jQuery API

Returns: FunctionFunction jQuery.proxy( [ Object ] context, [ String ] name )

Categories: Event Handler Attachment, Utilities, Version 1.4
Description: Takes a function and returns a new one that will always have a particular context.
  • version added: 1.4
  • jQuery.proxy( [ Function ] function, [ Object ] context )
  • function The function whose context will be changed.
  • context The object to which the context () of the function should be set.
  • version added: 1.4
  • jQuery.proxy( [ Object ] context, [ String ] name )
  • context The object to which the context of the function should be set.
  • name The name of the function whose context will be changed (should be a property of the object).

This method is most useful for attaching event handlers to an element where the context is pointing back to a different object. Additionally, jQuery makes sure that even if you bind the function returned from it will still unbind the correct function if passed the original.

Examples:

Example:

Enforce the context of the function using the "function, context" signature. Unbind the handler after first click.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

  <p><button id="test">Test</button></p>
  <p id="log"></p>

  <script>var obj = {
    name: "John",
    test: function() {
      $("#log").append( this.name );
      $("#test").unbind("click", obj.test);
    }
  };

  $("#test").click( jQuery.proxy( obj.test, obj ) );</script>
</body>
</html>

Demo:

Example:

Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

  <p><button id="test">Test</button></p>
  <p id="log"></p>

  <script>var obj = {
    name: "John",
    test: function() {
      $("#log").append( this.name );
      $("#test").unbind("click", obj.test);
    }
  };

  $("#test").click( jQuery.proxy( obj, "test" ) );</script>
</body>
</html>

Demo:


die – jQuery API

  • die ( )

    • 1.4.1die ( )

  • die ( [ String ] eventType, [ String ] handler )

    • 1.3die ( [ String ] eventType, [ String ] handler )
    • 1.4.3die ( [ Map ] eventTypes )

Returns: jQueryjQuery .die( )

Categories: Event Handler Attachment, Version 1.3, Version 1.4.1, Version 1.4.3
Description: Remove all event handlers previously attached using from the elements.
  • version added: 1.4.1
  • .die( )

Any handler that has been attached with can be removed with . This method is analogous to calling with no arguments, which is used to remove all handlers attached with . See the discussions of and for further details.

Up to jQuery 1.4.4, in order for .die() to function correctly, the selector used with it must match exactly the selector initially used with .live().

Examples:

Returns: jQueryjQuery .die( [ Map ] eventTypes )

Categories: Event Handler Attachment, Version 1.3, Version 1.4.1, Version 1.4.3
Description: Remove an event handler previously attached using from the elements.
  • version added: 1.3
  • .die( [ String ] eventType, [ String ] handler )
  • eventType A string containing a JavaScript event type, such as or .
  • handler The function that is no longer to be executed.
  • version added: 1.4.3
  • .die( [ Map ] eventTypes )
  • eventTypes A map of one or more event types, such as or and their corresponding functions that are no longer to be executed.

Any handler that has been attached with can be removed with . This method is analogous to , which is used to remove handlers attached with . See the discussions of and for further details.

Up to jQuery 1.4.4, in order for to function correctly, the selector used with it must match exactly the selector initially used with .

Examples:

Example:

Can bind and unbind events to the colored button.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>button { margin:5px; }
button#theone { color:red; background:yellow; }</style>
</head>
<body>
  <button id="theone">Does nothing...</button>
<button id="bind">Bind Click</button>
<button id="unbind">Unbind Click</button>

<div style="display:none;">Click!</div>
  <script>function aClick() {
  $("div").show().fadeOut("slow");
}
$("#bind").click(function () {
  $("#theone").live("click", aClick)
              .text("Can Click!");
});
$("#unbind").click(function () {
  $("#theone").die("click", aClick)
              .text("Does nothing...");
});</script>
</body>
</html>

Demo:

Example:

To unbind all live events from all paragraphs, write:
$("p").die()

Example:

To unbind all live click events from all paragraphs, write:
$("p").die( "click" )

Example:

To unbind just one previously bound handler, pass the function in as the second argument:
var foo = function () {
// code to handle some kind of event
};

$("p").live("click", foo); // ... now foo will be called when paragraphs are clicked ...

$("p").die("click", foo); // ... foo will no longer be called.


live – jQuery API

Returns: jQueryjQuery .live( [ Object ] events )

Categories: Event Handler Attachment, Version 1.3
Description: Attach a handler to the event for all elements which match the current selector, now and in the future.
  • version added: 1.3
  • .live( [ String ] eventType, [ Function ] handler )
  • eventType A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names, as well.
  • handler A function to execute at the time the event is triggered.
  • version added: 1.4
  • .live( [ String ] eventType, [ Object ] eventData, [ Function ] handler )
  • eventType A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names, as well.
  • eventData A map of data that will be passed to the event handler.
  • handler A function to execute at the time the event is triggered.
  • version added: 1.4.3
  • .live( [ Object ] events )
  • events A map of one or more JavaScript event types and functions to execute for them.

This method is a variation on the basic method for attaching event handlers to elements. When is called, the elements that the jQuery object refers to get the handler attached; elements that get introduced later do not, so they would require another call. For instance, consider the HTML:

<body>
  <div class="clickme">
    Click here
  </div>
</body>

To bind a simple click handler to this element:

$('.clickme').bind('click', function() {
  // Bound handler called.
});

When the element is clicked, the handler is called. However, suppose that after this, another element is added:

$('body').append('<div class="clickme">Another target</div>');

This new element also matches the selector , but since it was added after the call to , clicks on it will do nothing.

The method provides an alternative to this behavior. To bind a click handler to the target element using this method:

$('.clickme').live('click', function() {
  // Live handler called.
});

And then later add a new element:

$('body').append('<div class="clickme">Another target</div>');

Then clicks on the new element will also trigger the handler.

To the click handlers from all that were bound using , use the method:

$('.clickme').die('click');

Event Delegation

The method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to is never bound to an element; instead, binds a special handler to the root of the DOM tree. In the example above, when the new element is clicked, the following steps occur:

Because the test in step 5 is not performed until the event occurs, elements can be added at any time and still respond to events.

See the discussion for for more information on event binding.

Multiple Events

As of jQuery 1.4.1 can accept multiple, space-separated events, similar to the functionality provided in . For example, you can "live bind" the and events at the same time like so:

$('.hoverme').live('mouseover mouseout', function(event) {
  if (event.type == 'mouseover') {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});

As of jQuery 1.4.3, you can bind multiple live event handlers simultaneously by passing a map of event type/handler pairs:

$('a').live({
  click: function() {
    // do something on click
  },
  mouseover: function() {
    // do something on mouseover
  }
});

Event Data

As of jQuery 1.4, the optional parameter allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures. See the method's "" discussion for more information.

Event Context

As of jQuery 1.4, live events can be bound to a DOM element "context" rather than to the default document root. To set this context, use the , passing in a single DOM element (as opposed to a jQuery collection or a selector).

$('div.clickme', $('#container')[0]).live('click', function() {
  // Live handler called.
});

The live handler in this example is called only when is a descendant of an element with an ID of "container."

Caveats

The technique is useful, but due to its special approach cannot be simply substituted for in all cases. Specific differences include:

Examples:

Example:

Click a paragraph to add another. Note that .live() binds the click event to all paragraphs - even new ones.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; font-weight:bold; cursor:pointer;
      padding:5px; }
  p.over { background: #ccc; }
  span { color:red; }</style>
</head>
<body>
  <p>Click me!</p>

  <span></span>
  <script>$("p").live("click", function(){
      $(this).after("<p>Another paragraph!</p>");
    });</script>
</body>
</html>

Demo:

Example:

Display each paragraph's text in an alert box whenever it is clicked:
$("p").live("click", function(){
  alert( $(this).text() );
});

Example:

Cancel a default action and prevent it from bubbling up, return false:
$("a").live("click", function() { return false; })

Example:

To cancel only the default action by using the preventDefault method.
$("a").live("click", function(event){
  event.preventDefault();
});

Example:

Bind custom events:
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:red; }
  span { color:blue; }</style>
</head>
<body>

  <p>Has an attached custom event.</p>
  <button>Trigger custom event</button>
  <span style="display:none;"></span>

  <script>$("p").live("myCustomEvent", function(e, myName, myValue) {
    $(this).text("Hi there!");
    $("span").stop().css("opacity", 1)
             .text("myName = " + myName)
             .fadeIn(30).fadeOut(1000);
  });
  $("button").click(function () {
    $("p").trigger("myCustomEvent");
  });</script>
</body>
</html>

Demo:

Example:

Click a paragraph to add another. Note that .live() binds the click, mouseover, and mouseout events to all paragraphs - even new ones.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; font-weight:bold; cursor:pointer; padding:5px; }
  p.over { background: #ccc; }
  span { color:red; }</style>
</head>
<body>

  <p>Click me!</p>
  <span></span>

  <script>$("p").live("click", function(){
      $(this).after("<p>Another paragraph!</p>");
    });
    $("p").live({
      "mouseover": function() {
        $(this).addClass("over");
      },
      "mouseout": function() {
        $(this).removeClass("over");
      }
    });</script>
</body>
</html>

Demo:


triggerHandler – jQuery API

Returns: ObjectObject .triggerHandler( [ String ] eventType, [ Array ] extraParameters )

Categories: Event Handler Attachment, Version 1.2
Description: Execute all handlers attached to an element for an event.
  • version added: 1.2
  • .triggerHandler( [ String ] eventType, [ Array ] extraParameters )
  • eventType A string containing a JavaScript event type, such as or .
  • extraParameters An array of additional parameters to pass along to the event handler.

The method behaves similarly to , with the following exceptions:

For more information on this method, see the discussion for .

Examples:

Example:

If you called .triggerHandler() on a focus event - the browser's default focus action would not be triggered, only the event handlers bound to the focus event.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <button id="old">.trigger("focus")</button>
<button id="new">.triggerHandler("focus")</button><br/><br/>

<input type="text" value="To Be Focused"/>
  <script>$("#old").click(function(){
$("input").trigger("focus");
});
$("#new").click(function(){
$("input").triggerHandler("focus");
});
$("input").focus(function(){
$("<span>Focused!</span>").appendTo("body").fadeOut(1000);
});</script>
</body>
</html>

Demo:


trigger – jQuery API

Returns: jQueryjQuery .trigger( [ Event ] event )

Categories: Event Handler Attachment, Version 1.0
Description: Execute all handlers and behaviors attached to the matched elements for the given event type.
  • version added: 1.0
  • .trigger( [ String ] eventType, [ Array ] extraParameters )
  • eventType A string containing a JavaScript event type, such as or .
  • extraParameters An array of additional parameters to pass along to the event handler.
  • version added: 1.3
  • .trigger( [ Event ] event )
  • event A object.

Any event handlers attached with or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the method. A call to executes the handlers in the same order they would be if the event were triggered naturally by the user:

$('#foo').bind('click', function() {
      alert($(this).text());
    });
    $('#foo').trigger('click');

As of jQuery 1.3, ed events bubble up the DOM tree; an event handler can stop the bubbling by returning from the handler or calling the method on the event object passed into the event. Although simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

To trigger handlers bound via jQuery without also triggering the native event, use instead.

When we define a custom event type using the method, the second argument to can become useful. For example, suppose we have bound a handler for the event to our element instead of the built-in event as we did above:

$('#foo').bind('custom', function(event, param1, param2) {
  alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);

The event object is always passed as the first parameter to an event handler, but if additional parameters are specified during a call as they are here, these parameters will be passed along to the handler as well.

Note the difference between the extra parameters we're passing here and the parameter to the method. Both are mechanisms for passing information to an event handler, but the argument to allows information to be determined at the time the event is triggered, while the argument to requires the information to be already computed at the time the handler is bound.

Examples:

Example:

Clicks to button #2 also trigger a click for button #1.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>button { margin:10px; }
div { color:blue; font-weight:bold; }
span { color:red; }</style>
</head>
<body>
  <button>Button #1</button>
<button>Button #2</button>
<div><span>0</span> button #1 clicks.</div>

<div><span>0</span> button #2 clicks.</div>
  <script>$("button:first").click(function () {
update($("span:first"));
});
$("button:last").click(function () {
$("button:first").trigger('click');

update($("span:last"));
});

function update(j) {
var n = parseInt(j.text(), 10);
j.text(n + 1);
}</script>
</body>
</html>

Demo:

Example:

To submit the first form without using the submit() function, try:
$("form:first").trigger("submit")

Example:

To submit the first form without using the submit() function, try:
var event = jQuery.Event("submit");
$("form:first").trigger(event);
if ( event.isDefaultPrevented() ) {
// Perform an action...
}

Example:

To pass arbitrary data to an event:
$("p").click( function (event, a, b) {
// when a normal click fires, a and b are undefined
// for a trigger like below a refers to "foo" and b refers to "bar"

} ).trigger("click", ["foo", "bar"]);

Example:

To pass arbitrary data through an event object:
var event = jQuery.Event("logged");
event.user = "foo";
event.pass = "bar";
$("body").trigger(event);

Example:

Alternative way to pass data through an event object:
$("body").trigger({
type:"logged",
user:"foo",
pass:"bar"

});


one – jQuery API

Returns: jQueryjQuery .one( [ String ] eventType, [ Object ] eventData, [ Function ] handler(eventObject) )

Categories: Event Handler Attachment, Version 1.1
Description: Attach a handler to an event for the elements. The handler is executed at most once per element.
  • version added: 1.1
  • .one( [ String ] eventType, [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventType A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute at the time the event is triggered.

This method is identical to , except that the handler is unbound after its first invocation. For example:

$("#foo").one("click", function() {
  alert("This will be displayed only once.");
});

After the code is executed, a click on the element with ID will display the alert. Subsequent clicks will do nothing. This code is equivalent to:

$("#foo").bind("click", function( event ) {
  alert("This will be displayed only once.");
  $(this).unbind( event );
});

In other words, explicitly calling from within a regularly-bound handler has exactly the same effect.

If the first argument contains more than one space-separated event types, the event handler is called .

Examples:

Example:

Tie a one-time click to each div.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:60px; height:60px; margin:5px; float:left;
background:green; border:10px outset;
cursor:pointer; }
p { color:red; margin:0; clear:left; }</style>
</head>
<body>

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

<p>Click a green square...</p>

  <script>var n = 0;
$("div").one("click", function() {
  var index = $("div").index(this);
  $(this).css({
    borderStyle:"inset",
    cursor:"auto"
  });
  $("p").text("Div at index #" + index + " clicked." +
      "  That's " + ++n + " total clicks.");
});</script>
</body>
</html>

Demo:

Example:

To display the text of all paragraphs in an alert box the first time each of them is clicked:
$("p").one("click", function(){
alert( $(this).text() );
});


unbind – jQuery API

Returns: jQueryjQuery .unbind( [ Object ] event )

Categories: Event Handler Attachment, Version 1.0, Version 1.4.3
Description: Remove a previously-attached event handler from the elements.
  • version added: 1.0
  • .unbind( [ String ] eventType, [ Function ] handler(eventObject) )
  • eventType A string containing a JavaScript event type, such as or .
  • handler(eventObject) The function that is to be no longer executed.
  • version added: 1.4.3
  • .unbind( [ String ] eventType, [ Boolean ] false )
  • eventType A string containing a JavaScript event type, such as or .
  • false Unbinds the corresponding 'return false' function that was bound using .
  • version added: 1.0
  • .unbind( [ Object ] event )
  • event A JavaScript event object as passed to an event handler.

Any handler that has been attached with can be removed with . In the simplest case, with no arguments, removes all handlers attached to the elements:

$('#foo').unbind();

This version removes the handlers regardless of type. To be more precise, we can pass an event type:

$('#foo').unbind('click');

By specifying the event type, only handlers for that event type will be unbound. This approach can still have negative ramifications if other scripts might be attaching behaviors to the same element, however. Robust and extensible applications typically demand the two-argument version for this reason:

var handler = function() {
  alert('The quick brown fox jumps over the lazy dog.');
};
$('#foo').bind('click', handler);
$('#foo').unbind('click', handler);

By naming the handler, we can be assured that no other functions are caught in the crossfire. Note that the following will work:

$('#foo').bind('click', function() {
  alert('The quick brown fox jumps over the lazy dog.');
});

// will NOT work
$('#foo').unbind('click', function() {
  alert('The quick brown fox jumps over the lazy dog.');
});

Even though the two functions are identical in content, they are created separately and so JavaScript is free to keep them as distinct function objects. To unbind a particular handler, we need a reference to that function and not a different one that happens to do the same thing.

Using Namespaces

Instead of maintaining references to handlers in order to unbind them, we can namespace the events and use this capability to narrow the scope of our unbinding actions. As shown in the discussion for the method, namespaces are defined by using a period () character when binding a handler:

$('#foo').bind('click.myEvents', handler);

When a handler is bound in this fashion, we can still unbind it the normal way:

$('#foo').unbind('click');

However, if we want to avoid affecting other handlers, we can be more specific:

$('#foo').unbind('click.myEvents');

If multiple namespaced handlers are bound, we can unbind them at once:

$('#foo').unbind('click.myEvents.yourEvents');

This syntax is similar to that used for CSS class selectors; they are not hierarchical. This method call is thus the same as:

$('#foo').unbind('click.yourEvents.myEvents');

We can also unbind all of the handlers in a namespace, regardless of event type:

$('#foo').unbind('.myEvents');

It is particularly useful to attach namespaces to event bindings when we are developing plug-ins or otherwise writing code that may interact with other event-handling code in the future.

Using the Event Object

The third form of the method is used when we wish to unbind a handler from within itself. For example, suppose we wish to trigger an event handler only three times:

var timesClicked = 0;
$('#foo').bind('click', function(event) {
  alert('The quick brown fox jumps over the lazy dog.');
  timesClicked++;
  if (timesClicked >= 3) {
    $(this).unbind(event);
  }
});

The handler in this case must take a parameter, so that we can capture the event object and use it to unbind the handler after the third click. The event object contains the context necessary for to know which handler to remove. This example is also an illustration of a closure. Since the handler refers to the variable, which is defined outside the function, incrementing the variable has an effect even between invocations of the handler.

Examples:

Example:

Can bind and unbind events to the colored button.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>button { margin:5px; }
button#theone { color:red; background:yellow; }</style>
</head>
<body>
  <button id="theone">Does nothing...</button>
<button id="bind">Bind Click</button>
<button id="unbind">Unbind Click</button>

<div style="display:none;">Click!</div>
  <script>function aClick() {
$("div").show().fadeOut("slow");
}
$("#bind").click(function () {
// could use .bind('click', aClick) instead but for variety...
$("#theone").click(aClick)
  .text("Can Click!");
});
$("#unbind").click(function () {
$("#theone").unbind('click', aClick)
  .text("Does nothing...");
});</script>
</body>
</html>

Demo:

Example:

To unbind all events from all paragraphs, write:
$("p").unbind()

Example:

To unbind all click events from all paragraphs, write:
$("p").unbind( "click" )

Example:

To unbind just one previously bound handler, pass the function in as the second argument:
var foo = function () {
// code to handle some kind of event
};

$("p").bind("click", foo); // ... now foo will be called when paragraphs are clicked ...

$("p").unbind("click", foo); // ... foo will no longer be called.


bind – jQuery API

Returns: jQueryjQuery .bind( [ Object ] events )

Categories: Event Handler Attachment, Version 1.0, Version 1.4, Version 1.4.3
Description: Attach a handler to an event for the elements.
  • version added: 1.0
  • .bind( [ String ] eventType, [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventType A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .bind( [ String ] eventType, [ Object ] eventData, [ Boolean ] false )
  • eventType A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.
  • eventData A map of data that will be passed to the event handler.
  • false Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling.
  • version added: 1.4
  • .bind( [ Object ] events )
  • events A map of one or more JavaScript event types and functions to execute for them.

The method is the primary means of attaching behavior to a document. All JavaScript event types, such as , , and , are allowed for (The and events on the object use nonstandard conventions and are not supported by jQuery; attach a handler directly to the object instead.)

The jQuery library provides shortcut methods for binding the standard event types, such as for . A description of each can be found in the discussion of its shortcut method: , , , , , , , , , , , , , , , , , , , , , , ,

Any string is legal for ; if the string is not the name of a native JavaScript event, then the handler is bound to a custom event. These events are never called by the browser, but may be triggered manually from other JavaScript code using or .

If the string contains a period () character, then the event is namespaced. The period character separates the event from its namespace. For example, in the call , the string is the event type, and the string is the namespace. Namespacing allows us to unbind or trigger some events of a type without affecting others. See the discussion of for more information.

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

A basic usage of is:

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

This code will cause the element with an ID of to respond to the event. When a user clicks inside this element thereafter, the alert will be shown.

Multiple Events

Multiple event types can be bound at once by including each one separated by a space:

$('#foo').bind('mouseenter mouseleave', function() {
  $(this).toggleClass('entered');
});

The effect of this on (when it does not initially have the "entered" class) is to add the "entered" class when the mouse enters the and remove the class when the mouse leaves.

As of jQuery 1.4 we can bind multiple event handlers simultaneously by passing a map of event type/handler pairs:

$('#foo').bind({
  click: function() {
    // do something on click
  },
  mouseenter: function() {
    // do something on mouseenter
  }
});

Event Handlers

The parameter takes a callback function, as shown above. Within the handler, the keyword refers to the DOM element to which the handler is bound. To make use of the element in jQuery, it can be passed to the normal function. For example:

$('#foo').bind('click', function() {
  alert($(this).text());
});

After this code is executed, when the user clicks inside the element with an ID of , its text contents will be shown as an alert.

As of jQuery 1.4.2 duplicate event handlers can be bound to an element instead of being discarded. For example:

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

The above will generate two alerts when the button is clicked.

In jQuery 1.4.3 you can now pass in 'false' in place of an event handler. This will bind an event handler that's equivalent to: . This function can be removed at a later time by calling: .

The callback function can also take parameters. When the function is called, the JavaScript event object will be passed to the first parameter.

The event object is often unnecessary and the parameter omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered. However, at times it becomes necessary to gather more information about the user's environment at the time the event was initiated. .

Returning from a handler is equivalent to calling both and on the event object.

Using the event object in a handler looks like this:

$(document).ready(function() {
  $('#foo').bind('click', function(event) {
    alert('The mouse cursor is at ('
      + event.pageX + ', ' + event.pageY + ')');
  });
});

Note the parameter added to the anonymous function. This code will cause a click on the element with ID to report the page coordinates of the mouse cursor at the time of the click.

Passing Event Data

The optional parameter is not commonly used. When provided, this argument allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures. For example, suppose we have two event handlers that both refer to the same external variable:

var message = 'Spoon!';
$('#foo').bind('click', function() {
  alert(message);
});
message = 'Not in the face!';
$('#bar').bind('click', function() {
  alert(message);
});

Because the handlers are closures that both have in their environment, both will display the message when triggered. The variable's value has changed. To sidestep this, we can pass the message in using :

var message = 'Spoon!';
$('#foo').bind('click', {msg: message}, function(event) {
  alert(event.data.msg);
});
message = 'Not in the face!';
$('#bar').bind('click', {msg: message}, function(event) {
  alert(event.data.msg);
});

This time the variable is not referred to directly within the handlers; instead, the variable is passed in through , which fixes the value at the time the event is bound. The first handler will now display while the second will alert

If is present, it is the second argument to the method; if no additional data needs to be sent to the handler, then the callback is passed as the second and final argument.

As of jQuery 1.4 we can no longer attach data (and thus, events) to object, embed, or applet elements because critical errors occur when attaching data to Java applets.

Examples:

Example:

Handle click and double-click for the paragraph. Note: the coordinates are window relative, so in this case relative to the demo iframe.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; font-weight:bold; cursor:pointer;
padding:5px; }
p.over { background: #ccc; }
span { color:red; }</style>
</head>
<body>
  <p>Click or double click here.</p>
<span></span>
  <script>$("p").bind("click", function(event){
var str = "( " + event.pageX + ", " + event.pageY + " )";
$("span").text("Click happened! " + str);
});
$("p").bind("dblclick", function(){
$("span").text("Double-click happened in " + this.nodeName);
});
$("p").bind("mouseenter mouseleave", function(event){
$(this).toggleClass("over");
});</script>
</body>
</html>

Demo:

Example:

To display each paragraph's text in an alert box whenever it is clicked:
$("p").bind("click", function(){
alert( $(this).text() );
});

Example:

You can pass some extra data before the event handler:
function handler(event) {
alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)

Example:

Cancel a default action and prevent it from bubbling up by returning :
$("form").bind("submit", function() { return false; })

Example:

Cancel only the default action by using the .preventDefault() method.
$("form").bind("submit", function(event) {
event.preventDefault();
});

Example:

Stop an event from bubbling without preventing the default action by using the .stopPropagation() method.
$("form").bind("submit", function(event) {
  event.stopPropagation();
});

Example:

Bind custom events.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:red; }
span { color:blue; }</style>
</head>
<body>
  <p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>
  <script>$("p").bind("myCustomEvent", function(e, myName, myValue){
$(this).text(myName + ", hi there!");
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent", [ "John" ]);
});</script>
</body>
</html>

Demo:

Example:

Bind multiple events simultaneously.
$("div.test").bind({
  click: function(){
    $(this).addClass("active");
  },
  mouseenter: function(){
    $(this).addClass("inside");
  },
  mouseleave: function(){
    $(this).removeClass("inside");
  }
});


Event Object – jQuery API

Event Object

  • String event.namespace

    New in 1.4.3 !

    The namespace specified when the event was triggered.

  • Boolean event.isImmediatePropagationStopped( )

    New in 1.3 !

    Returns whether event.stopImmediatePropagation() was ever called on this event object.

  • event.stopImmediatePropagation( )

    New in 1.3 !

    Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.

  • Boolean event.isPropagationStopped( )

    New in 1.3 !

    Returns whether was ever called on this event object.

  • event.stopPropagation( )

    New in 1.0 !

    Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

  • Boolean event.isDefaultPrevented( )

    New in 1.3 !

    Returns whether was ever called on this event object.

  • undefined event.preventDefault( )

    New in 1.0 !

    If this method is called, the default action of the event will not be triggered.

  • Number event.timeStamp

    New in 1.2.6 !

    The difference in milliseconds between the time an event is triggered and January 1, 1970.

  • Object event.result

    New in 1.3 !

    The last value returned by an event handler that was triggered by this event, unless the value was .

  • Number event.which

    New in 1.1.3 !

    For key or button events, this attribute indicates the specific button or key that was pressed.

  • Number event.pageY

    New in 1.0.4 !

    The mouse position relative to the top edge of the document.

  • Number event.pageX

    New in 1.0.4 !

    The mouse position relative to the left edge of the document.

  • Element event.currentTarget

    New in 1.3 !

    The current DOM element within the event bubbling phase.

  • Element event.relatedTarget

    New in 1.1.4 !

    The other DOM element involved in the event, if any.

  • Anything event.data

    New in 1.1 !

    The optional data passed to jQuery.fn.bind when the current executing handler was bound.

  • Element event.target

    New in 1.0 !

    The DOM element that initiated the event.

  • String event.type

    New in 1.0 !

    Describes the nature of the event.


event.namespace – jQuery API

Returns: StringString event.namespace

Categories: Event Object, Version 1.4.3
Description: The namespace specified when the event was triggered.
  • version added: 1.4.3
  • event.namespace

This will likely be used primarily by plugin authors who wish to handle tasks differently depending on the event namespace used.

Examples:

Example:

Determine the event namespace used.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

<button>display event.namespace</button>
<p></p>

  <script>$("p").bind("test.something", function(event) {
  alert( event.namespace );
});
$("button").click(function(event) {
  $("p").trigger("test.something");
});</script>
</body>
</html>

Demo:


event.isImmediatePropagationStopped – jQuery API

Returns: BooleanBoolean event.isImmediatePropagationStopped( )

Categories: Event Object, Version 1.3
Description: Returns whether event.stopImmediatePropagation() was ever called on this event object.
  • version added: 1.3
  • event.isImmediatePropagationStopped( )

This property was introduced in .

Examples:

Example:

Checks whether event.stopImmediatePropagation() was called.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

  <button>click me</button>
  <div id="stop-log"></div>

  <script>function immediatePropStopped(e) {
  var msg = "";
  if ( e.isImmediatePropagationStopped() ) {
    msg =  "called"
  } else {
    msg = "not called";
  }
  $("#stop-log").append( "<div>" + msg + "</div>" );
}

$("button").click(function(event) {
  immediatePropStopped(event);
  event.stopImmediatePropagation();
  immediatePropStopped(event);
});</script>
</body>
</html>

Demo:


event.stopImmediatePropagation – jQuery API

Returns: event.stopImmediatePropagation( )

Categories: Event Object, Version 1.3
Description: Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.
  • version added: 1.3
  • event.stopImmediatePropagation( )

In addition to keeping any additional handlers on an element from being executed, this method also stops the bubbling by implicitly calling . To simply prevent the event from bubbling to ancestor elements but allow other event handlers to execute on the same element, we can use instead.

Use to know whether this method was ever called (on that event object).

Examples:

Example:

Prevents other event handlers from being called.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { height: 30px; width: 150px; background-color: #ccf; }
div {height: 30px; width: 150px; background-color: #cfc; }</style>
</head>
<body>
  <p>paragraph</p>
<div>division</div>
  <script>$("p").click(function(event){
  event.stopImmediatePropagation();
});
$("p").click(function(event){
  // This function won't be executed
  $(this).css("background-color", "#f00");
});
$("div").click(function(event) {
  // This function will be executed
    $(this).css("background-color", "#f00");
});</script>
</body>
</html>

Demo:


event.isPropagationStopped – jQuery API

Returns: BooleanBoolean event.isPropagationStopped( )

Categories: Event Object, Version 1.3
Description: Returns whether was ever called on this event object.
  • version added: 1.3
  • event.isPropagationStopped( )

This event method is described in the .

Examples:

Example:

Checks whether event.stopPropagation() was called
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

  <button>click me</button>
  <div id="stop-log"></div>

  <script>function propStopped(e) {
  var msg = "";
  if ( e.isPropagationStopped() ) {
    msg =  "called"
  } else {
    msg = "not called";
  }
  $("#stop-log").append( "<div>" + msg + "</div>" );
}

$("button").click(function(event) {
  propStopped(event);
  event.stopPropagation();
  propStopped(event);
});</script>
</body>
</html>

Demo:


event.stopPropagation – jQuery API

Returns: event.stopPropagation( )

Categories: Event Object, Version 1.0
Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
  • version added: 1.0
  • event.stopPropagation( )

We can use to determine if this method was ever called (on that event object).

This method works for custom events triggered with , as well.

Note that this will not prevent other handlers from running.

Examples:

Example:

Kill the bubbling on the click event.
$("p").click(function(event){
  event.stopPropagation();
  // do something
});


event.isDefaultPrevented – jQuery API

Returns: BooleanBoolean event.isDefaultPrevented( )

Categories: Event Object, Version 1.3
Description: Returns whether was ever called on this event object.
  • version added: 1.3
  • event.isDefaultPrevented( )

Examples:

Example:

Checks whether event.preventDefault() was called.
$("a").click(function(event){
  alert( event.isDefaultPrevented() ); // false
  event.preventDefault();
  alert( event.isDefaultPrevented() ); // true
});


event.preventDefault – jQuery API

Returns: undefinedundefined event.preventDefault( )

Categories: Event Object, Version 1.0
Description: If this method is called, the default action of the event will not be triggered.
  • version added: 1.0
  • event.preventDefault( )

For example, clicked anchors will not take the browser to a new URL. We can use to determine if this method has been called by an event handler that was triggered by this event.

Examples:

Example:

Cancel the default action (navigation) of the click.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

<a href="http://jquery.com">default click action is prevented</a>
<div id="log"></div>

  <script>$("a").click(function(event) {
  event.preventDefault();
  $('<div/>')
    .append('default ' + event.type + ' prevented')
    .appendTo('#log');
});</script>
</body>
</html>

Demo:


event.timeStamp – jQuery API

Returns: NumberNumber event.timeStamp

Categories: Event Object, Version 1.2.6
Description: The difference in milliseconds between the time an event is triggered and January 1, 1970.
  • version added: 1.2.6
  • event.timeStamp

This property can be useful for profiling the performance of certain jQuery functions by getting the value at two points in the code and noting the difference.

Examples:

Example:

Display the time since the click handler last executed.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { height: 100px; width: 300px; margin: 10px;
      background-color: #ffd; overflow: auto; }</style>
</head>
<body>

<div>Click.</div>
  <script>var last, diff;
$('div').click(function(event) {
  if ( last ) {
    diff = event.timeStamp - last
    $('div').append('time since last event: ' + diff + '<br/>');
  } else {
    $('div').append('Click again.<br/>');
  }
  last = event.timeStamp;
});</script>
</body>
</html>

Demo:


event.result – jQuery API

Returns: ObjectObject event.result

Categories: Event Object, Version 1.3
Description: The last value returned by an event handler that was triggered by this event, unless the value was .
  • version added: 1.3
  • event.result

This property can be useful for getting previous return values of custom events.

Examples:

Example:

Display previous handler's return value
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

<button>display event.result</button>
<p></p>

  <script>$("button").click(function(event) {
  return "hey";
});
$("button").click(function(event) {
  $("p").html( event.result );
});</script>
</body>
</html>

Demo:


event.which – jQuery API

Returns: NumberNumber event.which

Categories: Event Object, Version 1.1.3
Description: For key or button events, this attribute indicates the specific button or key that was pressed.
  • version added: 1.1.3
  • event.which

normalizes and . It is recommended to watch for keyboard key input. For more detail, read about .

Examples:

Example:

Log what key was depressed.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

<input id="whichkey" value="type something">
<div id="log"></div>
  <script>$('#whichkey').bind('keydown',function(e){
  $('#log').html(e.type + ': ' +  e.which );
});</script>
</body>
</html>

Demo:


event.pageY – jQuery API

Returns: NumberNumber event.pageY

Categories: Event Object, Version 1.0.4
Description: The mouse position relative to the top edge of the document.
  • version added: 1.0.4
  • event.pageY

Examples:

Example:

Show the mouse position relative to the left and top edges of the document (within this iframe).
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body {background-color: #eef; }
div { padding: 20px; }</style>
</head>
<body>
  <div id="log"></div>
  <script>$(document).bind('mousemove',function(e){
            $("#log").text("e.pageX: " + e.pageX + ", e.pageY: " + e.pageY);
});</script>
</body>
</html>

Demo:


event.pageX – jQuery API

Returns: NumberNumber event.pageX

Categories: Event Object, Version 1.0.4
Description: The mouse position relative to the left edge of the document.
  • version added: 1.0.4
  • event.pageX

Examples:

Example:

Show the mouse position relative to the left and top edges of the document (within the iframe).
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body {background-color: #eef; }
div { padding: 20px; }</style>
</head>
<body>
  <div id="log"></div>
  <script>$(document).bind('mousemove',function(e){
            $("#log").text("e.pageX: " + e.pageX + ", e.pageY: " + e.pageY);
});</script>
</body>
</html>

Demo:


event.currentTarget – jQuery API

Returns: ElementElement event.currentTarget

Categories: Event Object, Version 1.3
Description: The current DOM element within the event bubbling phase.
  • version added: 1.3
  • event.currentTarget

This property will typically be equal to the of the function.

Examples:

Example:

Alert that currentTarget matches the `this` keyword.
$("p").click(function(event) {
  alert( event.currentTarget === this ); // true
});


event.relatedTarget – jQuery API

Returns: ElementElement event.relatedTarget

Categories: Event Object, Version 1.1.4
Description: The other DOM element involved in the event, if any.
  • version added: 1.1.4
  • event.relatedTarget

For , indicates the element being entered; for , indicates the element being exited.

Examples:

Example:

On mouseout of anchors, alert the element type being entered.
$("a").mouseout(function(event) {
  alert(event.relatedTarget.nodeName); // "DIV"
});


event.data – jQuery API

Returns: AnythingAnything event.data

Categories: Event Object, Version 1.1
Description: The optional data passed to jQuery.fn.bind when the current executing handler was bound.
  • version added: 1.1
  • event.data

Examples:

Example:

The description of the example.
$("a").each(function(i) {
  $(this).bind('click', {index:i}, function(e){
     alert('my index is ' + e.data.index);
  });
});


event.target – jQuery API

Returns: ElementElement event.target

Categories: Event Object, Version 1.0
Description: The DOM element that initiated the event.
  • version added: 1.0
  • event.target

The property can be the element that registered for the event or a descendant of it. It is often useful to compare to in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.

Examples:

Example:

Display the tag's name on click
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span, strong, p {
  padding: 8px; display: block; border: 1px solid #999;  }</style>
</head>
<body>

<div id="log"></div>
<div>
  <p>
    <strong><span>click</span></strong>
  </p>
</div>
  <script>$("body").click(function(event) {
  $("#log").html("clicked: " + event.target.nodeName);
});</script>
</body>
</html>

Demo:

Example:

Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

<ul>
  <li>item 1
    <ul>
      <li>sub item 1-a</li>
      <li>sub item 1-b</li>
    </ul>
  </li>
  <li>item 2
    <ul>
      <li>sub item 2-a</li>
      <li>sub item 2-b</li>
    </ul>
  </li>
</ul>
  <script>function handler(event) {
  var $target = $(event.target);
  if( $target.is("li") ) {
    $target.children().toggle();
  }
}
$("ul").click(handler).find("ul").hide();</script>
</body>
</html>

Demo:


event.type – jQuery API

Returns: StringString event.type

Categories: Event Object, Version 1.0
Description: Describes the nature of the event.
  • version added: 1.0
  • event.type

Examples:

Example:

On all anchor clicks, alert the event type.
$("a").click(function(event) {
  alert(event.type); // "click"
});


Form Events – jQuery API

Form Events

  • jQuery .submit( )

    New in 1.0 !

    Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

  • jQuery .select( )

    New in 1.0 !

    Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

  • jQuery .change( )

    New in 1.0 !

    Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

  • jQuery .blur( )

    New in 1.0 !

    Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.

  • jQuery .focus( )

    New in 1.0 !

    Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.


submit – jQuery API

  • submit ( )

    • 1.0submit ( )

  • submit ( [ Function ] handler(eventObject) )

    • 1.0submit ( [ Function ] handler(eventObject) )
    • 1.4.3submit ( [ Object ] eventData, [ Function ] handler(eventObject) )
    • 1.0submit ( )

Returns: JQuery(":submit")

Categories: Form, Version 1.0
Description: Selects all elements of type submit.
  • version added: 1.0
  • JQuery(":submit")

The selector typically applies to button or input elements. Note that some browsers treat element as implicitly while others (such as Internet Explorer) do not.

Examples:

Example:

Finds all submit elements that are descendants of a td element.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>textarea { height:45px; }</style>
</head>
<body>

<table>
<form>
<table id="exampleTable" border="1" cellpadding="10" align="center">

    <tr>
        <th>
            Element Type
        </th>
        <th>
            Element
        </th>

    </tr
    <tr>
        <td>
            <input type="button" value="Input Button"/>
        </td>

    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="file" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="hidden" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="image" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="password" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="radio" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="reset" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="submit" />
        </td>

    </tr>
    <tr>
        <td>
            <input type="text" />
        </td>

    </tr>
    <tr>
        <td>
            <select><option>Option</option></select>
        </td>

    </tr>
    <tr>
        <td>
            <textarea></textarea>
        </td>
    </tr>

    <tr>
        <td>
            <button>Button</button>
        </td>
    </tr>
    <tr>
        <td>
            <button type="submit">Button type="submit"</button>
        </td>
    </tr>

</table>
</form>
<div id="result"></div>

  <script>var submitEl = $("td :submit")
      .parent('td')
      .css({background:"yellow", border:"3px red solid"})
    .end();

    $('#result').text('jQuery matched ' + submitEl.length + ' elements.');

    // so it won't submit
    $("form").submit(function () { return false; });

    // Extra JS to make the HTML easier to edit (None of this is relevant to the ':submit' selector
    $('#exampleTable').find('td').each(function(i, el) {
        var inputEl = $(el).children(),
            inputType = inputEl.attr('type') ? ' type="' + inputEl.attr('type') + '"' : '';
        $(el).before('<td>' + inputEl[0].nodeName + inputType + '</td>');
    })</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .submit( )

Categories: Form Events, Forms, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .submit( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .submit( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .submit( )

This method is a shortcut for in the first variation, and in the third.

The event is sent to an element when the user is attempting to submit a form. It can only be attached to elements. Forms can be submitted either by clicking an explicit , , or , or by pressing when certain form elements have focus.

For example, consider the HTML:

<form id="target" action="destination.html">
  <input type="text" value="Hello there" />
  <input type="submit" value="Go" />
</form>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to the form:

$('#target').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});

Now when the form is submitted, the message is alerted. This happens prior to the actual submission, so we can cancel the submit action by calling on the event object or by returning from our handler. We can trigger the event manually when another element is clicked:

$('#other').click(function() {
  $('#target').submit();
});

After this code executes, clicks on will also display the message. In addition, the default action on the form will be fired, so the form will be submitted.

The JavaScript event does not bubble in Internet Explorer. However, scripts that rely on event delegation with the event will work consistently across browsers as of jQuery 1.4, which has normalized the event's behavior.

Examples:

Example:

If you'd like to prevent forms from being submitted unless a flag variable is set, try:
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin:0; color:blue; }
  div,p { margin-left:10px; }
  span { color:red; }</style>
</head>
<body>
  <p>Type 'correct' to validate.</p>
  <form action="javascript:alert('success!');">
    <div>
      <input type="text" />

      <input type="submit" />
    </div>
  </form>
  <span></span>
  <script>$("form").submit(function() {
      if ($("input:first").val() == "correct") {
        $("span").text("Validated...").show();
        return true;
      }
      $("span").text("Not valid!").show().fadeOut(1000);
      return false;
    });</script>
</body>
</html>

Demo:

Example:

If you'd like to prevent forms from being submitted unless a flag variable is set, try:
$("form").submit( function () {
  return this.some_flag_variable;
} );

Example:

To trigger the submit event on the first form on the page, try:
$("form:first").submit();


select – jQuery API

Returns: jQueryjQuery .select( )

Categories: Form Events, Forms, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "select" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .select( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .select( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .select( )

This method is a shortcut for in the first two variations, and in the third.

The event is sent to an element when the user makes a text selection inside it. This event is limited to fields and boxes.

For example, consider the HTML:

<form>
  <input id="target" type="text" value="Hello there" />
</form>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to the text input:

$('#target').select(function() {
  alert('Handler for .select() called.');
});

Now when any portion of the text is selected, the alert is displayed. Merely setting the location of the insertion point will not trigger the event. To trigger the event manually, apply without an argument:

$('#other').click(function() {
  $('#target').select();
});

After this code executes, clicks on the Trigger button will also alert the message:

In addition, the default action on the field will be fired, so the entire text field will be selected.

Examples:

Example:

To do something when text in input boxes is selected:
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:blue; }
  div { color:red; }</style>
</head>
<body>
  <p>

    Click and drag the mouse to select text in the inputs.
  </p>
  <input type="text" value="Some text" />
  <input type="text" value="to test on" />

  <div></div>
  <script>$(":input").select( function () {
      $("div").text("Something was selected").show().fadeOut(1000);
    });</script>
</body>
</html>

Demo:

Example:

To trigger the select event on all input elements, try:
$("input").select();


change – jQuery API

Returns: jQueryjQuery .change( )

Categories: Form Events, Forms, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .change( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .change( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .change( )

This method is a shortcut for in the first two variations, and in the third.

The event is sent to an element when its value changes. This event is limited to elements, boxes and elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

For example, consider the HTML:

<form>
  <input class="target" type="text" value="Field 1" />
  <select class="target">
    <option value="option1" selected="selected">Option 1</option>
    <option value="option2">Option 2</option>
  </select>
</form>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to the text input and the select box:

$('.target').change(function() {
  alert('Handler for .change() called.');
});

Now when the second option is selected from the dropdown, the alert is displayed. It is also displayed if you change the text in the field and then click away. If the field loses focus without the contents having changed, though, the event is not triggered. To trigger the event manually, apply without arguments:

$('#other').click(function() {
  $('.target').change();
});

After this code executes, clicks on will also alert the message. The message will display twice, because the handler has been bound to the event on both of the form elements.

As of jQuery 1.4, the event bubbles in Internet Explorer, behaving consistently with the event in other modern browsers.

Examples:

Example:

Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:red; }</style>
</head>
<body>
  <select name="sweets" multiple="multiple">
    <option>Chocolate</option>
    <option selected="selected">Candy</option>

    <option>Taffy</option>
    <option selected="selected">Caramel</option>
    <option>Fudge</option>
    <option>Cookie</option>

  </select>
  <div></div>
  <script>$("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " ";
              });
          $("div").text(str);
        })
        .change();</script>
</body>
</html>

Demo:

Example:

To add a validity test to all text input elements:
$("input[type='text']").change( function() {
  // check input ($(this).val()) for validity here
});


blur – jQuery API

Returns: jQueryjQuery .blur( )

Categories: Form Events, Forms, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .blur( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .blur( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .blur( )

This method is a shortcut for in the first two variations, and in the third.

The event is sent to an element when it loses focus. Originally, this event was only applicable to form elements, such as . In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page.

For example, consider the HTML:

<form>
  <input id="target" type="text" value="Field 1" />
  <input type="text" value="Field 2" />
</form>
<div id="other">
  Trigger the handler
</div>
The event handler can be bound to the first input field:
$('#target').blur(function() {
  alert('Handler for .blur() called.');
});

Now if the first field has the focus, clicking elsewhere or tabbing away from it displays the alert:

To trigger the event programmatically, apply without an argument:

$('#other').click(function() {
  $('#target').blur();
});

After this code executes, clicks on will also alert the message.

The event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the event will not work consistently across browsers. As of version 1.4.2, however, jQuery works around this limitation by mapping to the event in its event delegation methods, and .

Examples:

Example:

To trigger the blur event on all paragraphs:
$("p").blur();


focus – jQuery API

Returns: jQueryjQuery .focus( )

Categories: Form Events, Forms, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .focus( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .focus( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .focus( )

For example, consider the HTML:

<form>
  <input id="target" type="text" value="Field 1" />
  <input type="text" value="Field 2" />
</form>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to the first input field:

$('#target').focus(function() {
  alert('Handler for .focus() called.');
});

Now clicking on the first field, or tabbing to it from another field, displays the alert:

We can trigger the event when another element is clicked:

$('#other').click(function() {
  $('#target').focus();
});

After this code executes, clicks on will also alert the message.

The event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the event will not work consistently across browsers. As of version 1.4.2, however, jQuery works around this limitation by mapping to the event in its event delegation methods, and .

Examples:

Example:

Fire focus.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span {display:none;}</style>
</head>
<body>
  <p><input type="text" /> <span>focus fire</span></p>

<p><input type="password" /> <span>focus fire</span></p>
  <script>$("input").focus(function () {
         $(this).next("span").css('display','inline').fadeOut(1000);
    });</script>
</body>
</html>

Demo:

Example:

To stop people from writing in text input boxes, try:
$("input[type=text]").focus(function(){
  $(this).blur();
});

Example:

To focus on a login input box with id 'login' on page startup, try:
$(document).ready(function(){
  $("#login").focus();
});


Keyboard Events – jQuery API

Keyboard Events

  • jQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusout" JavaScript event.

  • jQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusin" JavaScript event.

  • jQuery .keydown( )

    New in 1.0 !

    Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.

  • jQuery .keyup( )

    New in 1.0 !

    Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.

  • jQuery .keypress( )

    New in 1.0 !

    Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.


focusout – jQuery API

Returns: jQueryjQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

Categories: Keyboard Events, Mouse Events, Version 1.4, Version 1.4.3
Description: Bind an event handler to the "focusout" JavaScript event.
  • version added: 1.4
  • .focusout( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.

This method is a shortcut for .

The event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the event in that it supports detecting the loss of focus from parent elements (in other words, it supports event bubbling).

This event will likely be used together with the event.

Examples:

Example:

Watch for a loss of focus to occur inside paragraphs and note the difference between the count and the count.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>.inputs { float: left; margin-right: 1em; }
.inputs p { margin-top: 0; }</style>
</head>
<body>

<div class="inputs">
  <p>
    <input type="text" /><br />
    <input type="text" />
  </p>
  <p>
    <input type="password" />
  </p>
</div>
<div id="fo">focusout fire</div>
<div id="b">blur fire</div>

  <script>var fo = 0, b = 0;
$("p").focusout(function() {
  fo++;
  $("#fo")
    .text("focusout fired: " + fo + "x");
}).blur(function() {
  b++;
  $("#b")
    .text("blur fired: " + b + "x");

});</script>
</body>
</html>

Demo:


focusin – jQuery API

Returns: jQueryjQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

Categories: Keyboard Events, Mouse Events, Version 1.4, Version 1.4.3
Description: Bind an event handler to the "focusin" JavaScript event.
  • version added: 1.4
  • .focusin( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.

This method is a shortcut for .

The event is sent to an element when it, or any element inside of it, gains focus. This is distinct from the event in that it supports detecting the focus event on parent elements (in other words, it supports event bubbling).

This event will likely be used together with the event.

Examples:

Example:

Watch for a focus to occur within the paragraphs on the page.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span {display:none;}</style>
</head>
<body>
  <p><input type="text" /> <span>focusin fire</span></p>
<p><input type="password" /> <span>focusin fire</span></p>
  <script>$("p").focusin(function() {
         $(this).find("span").css('display','inline').fadeOut(1000);
    });</script>
</body>
</html>

Demo:


keydown – jQuery API

Returns: jQueryjQuery .keydown( )

Categories: Keyboard Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .keydown( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .keydown( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .keydown( )

This method is a shortcut for in the first and second variations, and in the third.

The event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

For example, consider the HTML:

<form>
  <input id="target" type="text" value="Hello there" />
</form>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to the input field:

$('#target').keydown(function() {
  alert('Handler for .keydown() called.');
});

Now when the insertion point is inside the field, pressing a key displays the alert:

To trigger the event manually, apply without an argument:

$('#other').click(function() {
  $('#target').keydown();
});

After this code executes, clicks on will also alert the message.

If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the object. Because of event bubbling, all key presses will make their way up the DOM to the object unless explicitly stopped.

To determine which key was pressed, examine the that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, may be a better choice.

Examples:

Example:

Show the event object for the keydown handler when a key is pressed in the input.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>fieldset { margin-bottom: 1em; }
input { display: block; margin-bottom: .25em; }
#print-output {
  width: 100%;
}
.print-output-line {
  white-space: pre;
  padding: 5px;
  font-family: monaco, monospace;
  font-size: .7em;
}</style>
</head>
<body>
  <form>
  <fieldset>
    <label for="target">Type Something:</label>
    <input id="target" type="text" />
  </fieldset>
</form>
<button id="other">
  Trigger the handler
</button>
<script type="text/javascript" src="/scripts/events.js"></script>
  <script>var xTriggered = 0;
$('#target').keydown(function(event) {
  if (event.keyCode == '13') {
     event.preventDefault();
   }
   xTriggered++;
   var msg = 'Handler for .keydown() called ' + xTriggered + ' time(s).';
  $.print(msg, 'html');
  $.print(event);
});

$('#other').click(function() {
  $('#target').keydown();
});</script>
</body>
</html>

Demo:


keyup – jQuery API

Returns: jQueryjQuery .keyup( )

Categories: Keyboard Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .keyup( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .keyup( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .keyup( )

This method is a shortcut for in the first two variations, and in the third.

The event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

For example, consider the HTML:

<form>
  <input id="target" type="text" value="Hello there" />
</form>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to the input field:

$('#target').keyup(function() {
  alert('Handler for .keyup() called.');
});

Now when the insertion point is inside the field and a key is pressed and released, the alert is displayed:

To trigger the event manually, apply without arguments:

$('#other').click(function() {
  $('#target').keyup();
});

After this code executes, clicks on will also alert the message.

If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the object. Because of event bubbling, all key presses will make their way up the DOM to the object unless explicitly stopped.

To determine which key was pressed, examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, may be a better choice.

Examples:

Example:

Show the event object for the keyup handler when a key is released in the input.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>fieldset { margin-bottom: 1em; }
input { display: block; margin-bottom: .25em; }
#print-output {
  width: 100%;
}
.print-output-line {
  white-space: pre;
  padding: 5px;
  font-family: monaco, monospace;
  font-size: .7em;
}</style>
</head>
<body>
  <form>
  <fieldset>
    <label for="target">Type Something:</label>
    <input id="target" type="text" />
  </fieldset>
</form>
<button id="other">
  Trigger the handler
</button>
<script type="text/javascript" src="/scripts/events.js"></script>
  <script>var xTriggered = 0;
$('#target').keyup(function(event) {
  if (event.keyCode == '13') {
     event.preventDefault();
   }
   xTriggered++;
   var msg = 'Handler for .keyup() called ' + xTriggered + ' time(s).';
  $.print(msg, 'html');
  $.print(event);
});

$('#other').click(function() {
  $('#target').keyup();
});</script>
</body>
</html>

Demo:


keypress – jQuery API

Returns: jQueryjQuery .keypress( )

Categories: Keyboard Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .keypress( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .keypress( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .keypress( )

as the event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

This method is a shortcut for in the first two variations, and in the third.

The event is sent to an element when the browser registers keyboard input. This is similar to the event, except in the case of key repeats. If the user presses and holds a key, a event is triggered once, but separate events are triggered for each inserted character. In addition, modifier keys (such as Shift) trigger events but not events.

A event handler can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

For example, consider the HTML:

<form>
    <fieldset>
      <input id="target" type="text" value="Hello there" />
    </fieldset>
</form>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to the input field:

$('#target').keypress(function() {
  alert('Handler for .keypress() called.');
});

Now when the insertion point is inside the field, pressing a key displays the alert:

The message repeats if the key is held down. To trigger the event manually, apply without an argument::

$('#other').click(function() {
  $('#target').keypress();
});

After this code executes, clicks on will also alert the message.

If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the object. Because of event bubbling, all key presses will make their way up the DOM to the object unless explicitly stopped.

To determine which character was entered, examine the object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the property so you can reliably use it to retrieve the character code.

Note that and provide a code indicating which key is pressed, while indicates which character was entered. For example, a lowercase "a" will be reported as 65 by and , but as 97 by . An uppercase "A" is reported as 65 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, or is a better choice.

Examples:

Example:

Show the event object for the keypress handler when a key is pressed in the input.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>fieldset { margin-bottom: 1em; }
input { display: block; margin-bottom: .25em; }
#print-output {
  width: 100%;
}
.print-output-line {
  white-space: pre;
  padding: 5px;
  font-family: monaco, monospace;
  font-size: .7em;
}</style>
</head>
<body>
  <form>
  <fieldset>
    <label for="target">Type Something:</label>
    <input id="target" type="text" />
  </fieldset>
</form>
<button id="other">
  Trigger the handler
</button>
<script type="text/javascript" src="/scripts/events.js"></script>
  <script>var xTriggered = 0;
$('#target').keypress(function(event) {
  if (event.which == '13') {
     event.preventDefault();
   }
   xTriggered++;
   var msg = 'Handler for .keypress() called ' + xTriggered + ' time(s).';
  $.print(msg, 'html');
  $.print(event);
});

$('#other').click(function() {
  $('#target').keypress();
});</script>
</body>
</html>

Demo:


Mouse Events – jQuery API

Mouse Events

  • jQuery .toggle( [ Function ] handler(eventObject), [ Function ] handler(eventObject), [ Function ] handler(eventObject) )

    New in 1.0 !

    Bind two or more handlers to the matched elements, to be executed on alternate clicks.

  • jQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusout" JavaScript event.

  • jQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusin" JavaScript event.

  • jQuery .mousemove( )

    New in 1.0 !

    Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.

  • jQuery .hover( [ Function ] handlerInOut(eventObject) )

    New in 1.4 !

    Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.

  • jQuery .mouseleave( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.

  • jQuery .mouseenter( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

  • jQuery .mouseout( )

    New in 1.0 !

    Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.

  • jQuery .mouseover( )

    New in 1.0 !

    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • jQuery .dblclick( )

    New in 1.0 !

    Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.

  • jQuery .click( )

    New in 1.0 !

    Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

  • jQuery .mouseup( )

    New in 1.0 !

    Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.

  • jQuery .mousedown( )

    New in 1.0 !

    Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.


mousemove – jQuery API

Returns: jQueryjQuery .mousemove( )

Categories: Mouse Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .mousemove( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .mousemove( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .mousemove( )

This method is a shortcut for in the first two variations, and in the third.

The event is sent to an element when the mouse pointer moves inside the element. Any HTML element can receive this event.

For example, consider the HTML:

<div id="target">
  Move here
</div>
<div id="other">
  Trigger the handler
</div>
<div id="log"></div>

The event handler can be bound to the target:

$("#target").mousemove(function(event) {
  var msg = "Handler for .mousemove() called at ";
  msg += event.pageX + ", " + event.pageY;
  $("#log").append("<div>" + msg + "</div>");
});

Now when the mouse pointer moves within the target button, the messages are appended to <div id="log">:

To trigger the event manually, apply without an argument:

$("#other").click(function() {
  $("#target").mousemove();
});

After this code executes, clicks on the Trigger button will also append the message:

When tracking mouse movement, you usually need to know the actual position of the mouse pointer. The event object that is passed to the handler contains some information about the mouse coordinates. Properties such as , , and are available, but support for them differs between browsers. Fortunately, jQuery normalizes the and properties so that they can be used in all browsers. These properties provide the X and Y coordinates of the mouse pointer relative to the top-left corner of the document, as illustrated in the example output above.

Keep in mind that the event is triggered whenever the mouse pointer moves, even for a pixel. This means that hundreds of events can be generated over a very small amount of time. If the handler has to do any significant processing, or if multiple handlers for the event exist, this can be a serious performance drain on the browser. It is important, therefore, to optimize handlers as much as possible, and to unbind them as soon as they are no longer needed.

A common pattern is to bind the handler from within a hander, and to unbind it from a corresponding handler. If implementing this sequence of events, remember that the event might be sent to a different HTML element than the event was. To account for this, the handler should typically be bound to an element high up in the DOM tree, such as .

Examples:

Example:

Show the mouse coordinates when the mouse is moved over the yellow div. Coordinates are relative to the window, which in this case is the iframe.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:220px; height:170px; margin;10px; margin-right:50px;
        background:yellow; border:2px groove; float:right; }
  p { margin:0; margin-left:10px; color:red; width:220px;
      height:120px; padding-top:70px;
      float:left; font-size:14px; }
  span { display:block; }</style>
</head>
<body>
  <p>
    Try scrolling too.
    <span>Move the mouse over the div.</span>
    <span>&nbsp;</span>
  </p>

  <div></div>
  <script>$("div").mousemove(function(e){
      var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
      var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
      $("span:first").text("( e.pageX, e.pageY ) - " + pageCoords);
      $("span:last").text("( e.clientX, e.clientY ) - " + clientCoords);
    });</script>
</body>
</html>

Demo:


hover – jQuery API

  • hover ( [ Function ] handlerIn(eventObject), [ Function ] handlerOut(eventObject) )

    • 1.0hover ( [ Function ] handlerIn(eventObject), [ Function ] handlerOut(eventObject) )

  • hover ( [ Function ] handlerInOut(eventObject) )

    • 1.4hover ( [ Function ] handlerInOut(eventObject) )

Returns: jQueryjQuery .hover( [ Function ] handlerIn(eventObject), [ Function ] handlerOut(eventObject) )

Categories: Mouse Events, Version 1.0
Description: Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
  • version added: 1.0
  • .hover( [ Function ] handlerIn(eventObject), [ Function ] handlerOut(eventObject) )
  • handlerIn(eventObject) A function to execute when the mouse pointer enters the element.
  • handlerOut(eventObject) A function to execute when the mouse pointer leaves the element.

The method binds handlers for both and events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

Calling is shorthand for:

$(selector).mouseenter(handlerIn).mouseleave(handlerOut);

See the discussions for and for more details.

Examples:

Example:

To add a special style to list items that are being hovered over, try:
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>ul { margin-left:20px; color:blue; }
  li { cursor:default; }
  span { color:red; }</style>
</head>
<body>
  <ul>
    <li>Milk</li>
    <li>Bread</li>
    <li class='fade'>Chips</li>

    <li class='fade'>Socks</li>
  </ul>
  <script>$("li").hover(
  function () {
    $(this).append($("<span> ***</span>"));
  },
  function () {
    $(this).find("span:last").remove();
  }
);

//li with fade class
$("li.fade").hover(function(){$(this).fadeOut(100);$(this).fadeIn(500);});</script>
</body>
</html>

Demo:

Example:

To add a special style to table cells that are being hovered over, try:
$("td").hover(
  function () {
    $(this).addClass("hover");
  },
  function () {
    $(this).removeClass("hover");
  }
);

Example:

To unbind the above example use:
$("td").unbind('mouseenter mouseleave');

Returns: jQueryjQuery .hover( [ Function ] handlerInOut(eventObject) )

Categories: Mouse Events, Version 1.0
Description: Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.
  • version added: 1.4
  • .hover( [ Function ] handlerInOut(eventObject) )
  • handlerInOut(eventObject) A function to execute when the mouse pointer enters or leaves the element.

The method, when passed a single function, will execute that handler for both and events. This allows the user to use jQuery's various toggle methods within the handler or to respond differently within the handler depending on the .

Calling is shorthand for:

$(selector).bind("mouseenter mouseleave", handlerInOut);

See the discussions for and for more details.

Examples:

Example:

Slide the next sibling LI up or down on hover, and toggle a class.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>ul { margin-left:20px; color:blue; }
  li { cursor:default; }
  li.active { background:black;color:white; }
  span { color:red; }</style>
</head>
<body>
  <ul>
    <li>Milk</li>
    <li>White</li>
    <li>Carrots</li>
    <li>Orange</li>
    <li>Broccoli</li>
    <li>Green</li>
  </ul>
  <script>$("li")
.filter(":odd")
.hide()
 .end()
.filter(":even")
.hover(
  function () {
    $(this).toggleClass("active")
      .next().stop(true, true).slideToggle();
  }
);</script>
</body>
</html>

Demo:


mouseleave – jQuery API

Returns: jQueryjQuery .mouseleave( )

Categories: Mouse Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.
  • version added: 1.0
  • .mouseleave( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .mouseleave( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .mouseleave( )

This method is a shortcut for in the first two variations, and in the third.

The JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser. This event is sent to an element when the mouse pointer leaves the element. Any HTML element can receive this event.

For example, consider the HTML:

<div id="outer">
  Outer
  <div id="inner">
    Inner
  </div>
</div>
<div id="other">
  Trigger the handler
</div>
<div id="log"></div>

The event handler can be bound to any element:

$('#outer').mouseleave(function() {
  $('#log').append('<div>Handler for .mouseleave() called.</div>');
});

Now when the mouse pointer moves out of the , the message is appended to . You can also trigger the event when another element is clicked:

$('#other').click(function() {
  $('#outer').mouseleave();
});

After this code executes, clicks on will also append the message.

The event differs from in the way it handles event bubbling. If were used in this example, then when the mouse pointer moved out of the element, the handler would be triggered. This is usually undesirable behavior. The event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse leaves the element, but not the element.

Examples:

Example:

Show number of times mouseout and mouseleave events are triggered. fires when the pointer moves out of child element as well, while fires only when the pointer moves out of the bound element.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div.out {
width:40%;
height:120px;
margin:0 15px;
background-color:#D6EDFC;
float:left;
}
div.in {
width:60%;
height:60%;
background-color:#FFCC00;
margin:10px auto;
}
p {
line-height:1em;
margin:0;
padding:0;
}</style>
</head>
<body>

<div class="out overout"><p>move your mouse</p><div class="in overout"><p>move your mouse</p><p>0</p></div><p>0</p></div>

<div class="out enterleave"><p>move your mouse</p><div class="in enterleave"><p>move your mouse</p><p>0</p></div><p>0</p></div>

  <script>var i = 0;
    $("div.overout").mouseover(function(){
      $("p:first",this).text("mouse over");
    }).mouseout(function(){
      $("p:first",this).text("mouse out");
      $("p:last",this).text(++i);
    });

    var n = 0;
    $("div.enterleave").mouseenter(function(){
      $("p:first",this).text("mouse enter");
    }).mouseleave(function(){
      $("p:first",this).text("mouse leave");
      $("p:last",this).text(++n);
    });</script>
</body>
</html>

Demo:


mouseenter – jQuery API

Returns: jQueryjQuery .mouseenter( )

Categories: Mouse Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.
  • version added: 1.0
  • .mouseenter( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .mouseenter( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .mouseenter( )

This method is a shortcut for in the first two variations, and in the third.

The JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser. This event is sent to an element when the mouse pointer enters the element. Any HTML element can receive this event.

For example, consider the HTML:

<div id="outer">
  Outer
  <div id="inner">
    Inner
  </div>
</div>
<div id="other">
  Trigger the handler
</div>
<div id="log"></div>

The event handler can be bound to any element:

$('#outer').mouseenter(function() {
  $('#log').append('<div>Handler for .mouseenter() called.</div>');
});

Now when the mouse pointer moves over the , the message is appended to . You can also trigger the event when another element is clicked:

$('#other').click(function() {
  $('#outer').mouseenter();
});

After this code executes, clicks on will also append the message.

The event differs from in the way it handles event bubbling. If were used in this example, then when the mouse pointer moved over the element, the handler would be triggered. This is usually undesirable behavior. The event, on the other hand, only triggers its handler when the mouse enters the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse enters the element, but not the element.

Examples:

Example:

Show texts when mouseenter and mouseout event triggering. fires when the pointer moves into the child element as well, while fires only when the pointer moves into the bound element.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div.out {
width:40%;
height:120px;
margin:0 15px;
background-color:#D6EDFC;
float:left;
}
div.in {
width:60%;
height:60%;
background-color:#FFCC00;
margin:10px auto;
}
p {
line-height:1em;
margin:0;
padding:0;
}</style>
</head>
<body>

<div class="out overout"><p>move your mouse</p><div class="in overout"><p>move your mouse</p><p>0</p></div><p>0</p></div>

<div class="out enterleave"><p>move your mouse</p><div class="in enterleave"><p>move your mouse</p><p>0</p></div><p>0</p></div>

  <script>var i = 0;
    $("div.overout").mouseover(function(){
      $("p:first",this).text("mouse over");
      $("p:last",this).text(++i);
    }).mouseout(function(){
      $("p:first",this).text("mouse out");
    });

    var n = 0;
    $("div.enterleave").mouseenter(function(){
      $("p:first",this).text("mouse enter");
      $("p:last",this).text(++n);
    }).mouseleave(function(){
      $("p:first",this).text("mouse leave");
    });</script>
</body>
</html>

Demo:


mouseout – jQuery API

Returns: jQueryjQuery .mouseout( )

Categories: Mouse Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .mouseout( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .mouseout( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .mouseout( )

This method is a shortcut for in the first two variation, and in the third.

The event is sent to an element when the mouse pointer leaves the element. Any HTML element can receive this event.

For example, consider the HTML:

<div id="outer">
  Outer
  <div id="inner">
    Inner
  </div>
</div>
<div id="other">
  Trigger the handler
</div>
<div id="log"></div>

The event handler can be bound to any element:

$('#outer').mouseout(function() {
  $('#log').append('Handler for .mouseout() called.');
});

Now when the mouse pointer moves out of the , the message is appended to . To trigger the event manually, apply without an argument::

$('#other').click(function() {
  $('#outer').mouseout();
});

After this code executes, clicks on will also append the message.

This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves out of the element in this example, a event will be sent to that, then trickle up to . This can trigger the bound handler at inopportune times. See the discussion for for a useful alternative.

Examples:

Example:

Show the number of times mouseout and mouseleave events are triggered. fires when the pointer moves out of the child element as well, while fires only when the pointer moves out of the bound element.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div.out {
width:40%;
height:120px;
margin:0 15px;
background-color:#D6EDFC;
float:left;
}
div.in {
width:60%;
height:60%;
background-color:#FFCC00;
margin:10px auto;
}
p {
line-height:1em;
margin:0;
padding:0;
}</style>
</head>
<body>

<div class="out overout"><p>move your mouse</p><div class="in overout"><p>move your mouse</p><p>0</p></div><p>0</p></div>

<div class="out enterleave"><p>move your mouse</p><div class="in enterleave"><p>move your mouse</p><p>0</p></div><p>0</p></div>

  <script>var i = 0;
    $("div.overout").mouseout(function(){
      $("p:first",this).text("mouse out");
      $("p:last",this).text(++i);
    }).mouseover(function(){
      $("p:first",this).text("mouse over");
    });

    var n = 0;
    $("div.enterleave").bind("mouseenter",function(){
      $("p:first",this).text("mouse enter");
    }).bind("mouseleave",function(){
      $("p:first",this).text("mouse leave");
      $("p:last",this).text(++n);
    });</script>
</body>
</html>

Demo:


mouseover – jQuery API

Returns: jQueryjQuery .mouseover( )

Categories: Mouse Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .mouseover( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .mouseover( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .mouseover( )

This method is a shortcut for in the first two variations, and in the third.

The event is sent to an element when the mouse pointer enters the element. Any HTML element can receive this event.

For example, consider the HTML:

<div id="outer">
  Outer
  <div id="inner">
    Inner
  </div>
</div>
<div id="other">
  Trigger the handler
</div>
<div id="log"></div>

The event handler can be bound to any element:

$('#outer').mouseover(function() {
  $('#log').append('<div>Handler for .mouseover() called.</div>');
});

Now when the mouse pointer moves over the , the message is appended to . We can also trigger the event when another element is clicked:

$('#other').click(function() {
  $('#outer').mouseover();
});

After this code executes, clicks on will also append the message.

This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves over the element in this example, a event will be sent to that, then trickle up to . This can trigger our bound handler at inopportune times. See the discussion for for a useful alternative.

Examples:

Example:

Show the number of times mouseover and mouseenter events are triggered. fires when the pointer moves into the child element as well, while fires only when the pointer moves into the bound element.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div.out { width:40%; height:120px; margin:0 15px;
          background-color:#D6EDFC; float:left; }
div.in {  width:60%; height:60%;
          background-color:#FFCC00; margin:10px auto; }
p { line-height:1em; margin:0; padding:0; }</style>
</head>
<body>

<div class="out overout">
  <span>move your mouse</span>
  <div class="in">
  </div>
</div>

<div class="out enterleave">
  <span>move your mouse</span>
  <div class="in">
  </div>
</div>

  <script>var i = 0;
  $("div.overout").mouseover(function() {
    i += 1;
    $(this).find("span").text( "mouse over x " + i );
  }).mouseout(function(){
    $(this).find("span").text("mouse out ");
  });

  var n = 0;
  $("div.enterleave").mouseenter(function() {
    n += 1;
    $(this).find("span").text( "mouse enter x " + n );
  }).mouseleave(function() {
    $(this).find("span").text("mouse leave");
  });</script>
</body>
</html>

Demo:


dblclick – jQuery API

Returns: jQueryjQuery .dblclick( )

Categories: Mouse Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .dblclick( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .dblclick( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .dblclick( )

This method is a shortcut for in the first two variations, and in the third. The event is sent to an element when the element is double-clicked. Any HTML element can receive this event. For example, consider the HTML:

<div id="target">
  Double-click here
</div>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to any :

$('#target').dblclick(function() {
  alert('Handler for .dblclick() called.');
});

Now double-clicking on this element displays the alert:

To trigger the event manually, apply without an argument:

$('#other').click(function() {
  $('#target').dblclick();
});

After this code executes, (single) clicks on will also alert the message.

The event is only triggered after this exact series of events:

It is inadvisable to bind handlers to both the and events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two events before the and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.

Examples:

Example:

To bind a "Hello World!" alert box the dblclick event on every paragraph on the page:
$("p").dblclick( function () { alert("Hello World!"); });

Example:

Double click to toggle background color.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { background:blue;
        color:white;
        height:100px;
        width:150px;
 }
  div.dbl { background:yellow;color:black; }</style>
</head>
<body>
  <div></div><span>Double click the block</span>
  <script>var divdbl = $("div:first");
    divdbl.dblclick(function () {
      divdbl.toggleClass('dbl');
    });</script>
</body>
</html>

Demo:


click – jQuery API

Returns: jQueryjQuery .click( )

Categories: Mouse Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .click( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .click( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .click( )

This method is a shortcut for in the first two variations, and in the third.

The event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event.

For example, consider the HTML:
<div id="target">
  Click here
</div>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to any :

$('#target').click(function() {
  alert('Handler for .click() called.');
});

Now if we click on this element, the alert is displayed:

We can also trigger the event when a different element is clicked:

$('#other').click(function() {
  $('#target').click();
});

After this code executes, clicks on will also alert the message.

The event is only triggered after this exact series of events:

This is usually the desired sequence before taking an action. If this is not required, the or event may be more suitable.

Examples:

Example:

To hide paragraphs on a page when they are clicked:
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:red; margin:5px; cursor:pointer; }
  p.hilite { background:yellow; }</style>
</head>
<body>
  <p>First Paragraph</p>

  <p>Second Paragraph</p>
  <p>Yet one more Paragraph</p>
  <script>$("p").click(function () {
      $(this).slideUp();
    });
    $("p").hover(function () {
      $(this).addClass("hilite");
    }, function () {
      $(this).removeClass("hilite");
    });</script>
</body>
</html>

Demo:

Example:

To trigger the click event on all of the paragraphs on the page:
$("p").click();


mouseup – jQuery API

Returns: jQueryjQuery .mouseup( )

Categories: Mouse Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .mouseup( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .mouseup( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .mouseup( )

This method is a shortcut for in the first variation, and in the second.

The event is sent to an element when the mouse pointer is over the element, and the mouse button is released. Any HTML element can receive this event.

For example, consider the HTML:

<div id="target">
  Click here
</div>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to any :

$('#target').mouseup(function() {
  alert('Handler for .mouseup() called.');
});

Now if we click on this element, the alert is displayed:

We can also trigger the event when a different element is clicked:

$('#other').click(function() {
  $('#target').mouseup();
});

After this code executes, clicks on will also alert the message.

If the user clicks outside an element, drags onto it, and releases the button, this is still counted as a event. This sequence of actions is not treated as a button press in most user interfaces, so it is usually better to use the event unless we know that the event is preferable for a particular situation.

Examples:

Example:

Show texts when mouseup and mousedown event triggering.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>Press mouse and release here.</p>

  <script>$("p").mouseup(function(){
      $(this).append('<span style="color:#F00;">Mouse up.</span>');
    }).mousedown(function(){
      $(this).append('<span style="color:#00F;">Mouse down.</span>');
    });</script>
</body>
</html>

Demo:


mousedown – jQuery API

Returns: jQueryjQuery .mousedown( )

Categories: Mouse Events, Version 1.0, Version 1.4.3
Description: Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.
  • version added: 1.0
  • .mousedown( [ Function ] handler(eventObject) )
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.4.3
  • .mousedown( [ Object ] eventData, [ Function ] handler(eventObject) )
  • eventData A map of data that will be passed to the event handler.
  • handler(eventObject) A function to execute each time the event is triggered.
  • version added: 1.0
  • .mousedown( )

This method is a shortcut for in the first variation, and in the second.

The event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed. Any HTML element can receive this event.

For example, consider the HTML:

<div id="target">
  Click here
</div>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to any :

$('#target').mousedown(function() {
  alert('Handler for .mousedown() called.');
});

Now if we click on this element, the alert is displayed:

We can also trigger the event when a different element is clicked:

$('#other').click(function() {
  $('#target').mousedown();
});

After this code executes, clicks on will also alert the message.

The event is sent when any mouse button is clicked. To act only on specific buttons, we can use the event object's property. Not all browsers support this property (Internet Explorer uses button instead), but jQuery normalizes the property so that it is safe to use in any browser. The value of will be 1 for the left button, 2 for the middle button, or 3 for the right button.

This event is primarily useful for ensuring that the primary button was used to begin a drag operation; if ignored, strange results can occur when the user attempts to use a context menu. While the middle and right buttons can be detected with these properties, this is not reliable. In Opera and Safari, for example, right mouse button clicks are not detectable by default.

If the user clicks on an element, drags away from it, and releases the button, this is still counted as a event. This sequence of actions is treated as a "canceling" of the button press in most user interfaces, so it is usually better to use the event unless we know that the event is preferable for a particular situation.

Examples:

Example:

Show texts when mouseup and mousedown event triggering.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>Press mouse and release here.</p>

  <script>$("p").mouseup(function(){
      $(this).append('<span style="color:#F00;">Mouse up.</span>');
    }).mousedown(function(){
      $(this).append('<span style="color:#00F;">Mouse down.</span>');
    });</script>
</body>
</html>

Demo:


Forms – jQuery API

Forms

  • jQuery .submit( )

    New in 1.0 !

    Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

  • jQuery .select( )

    New in 1.0 !

    Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

  • jQuery .change( )

    New in 1.0 !

    Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

  • jQuery .blur( )

    New in 1.0 !

    Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.

  • jQuery .focus( )

    New in 1.0 !

    Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.

  • Array .serializeArray( )

    New in 1.2 !

    Encode a set of form elements as an array of names and values.

  • String .serialize( )

    New in 1.0 !

    Encode a set of form elements as a string for submission.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.


Manipulation – jQuery API

Manipulation

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • Boolean .hasClass( [ String ] className )

    New in 1.2 !

    Determine whether any of the matched elements are assigned the given class.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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

  • jQuery .clone( [ Boolean ] withDataAndEvents, [ Boolean ] deepWithDataAndEvents )

    New in 1.5 !

    Create a deep copy of the set of matched elements.

  • jQuery .unwrap( )

    New in 1.4 !

    Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

  • jQuery .wrapInner( [ Function ] wrappingFunction )

    New in 1.4 !

    Wrap an HTML structure around the content of each element in the set of matched elements.

  • jQuery .wrapAll( [ String | Selector | Element | jQuery ] wrappingElement )

    New in 1.2 !

    Wrap an HTML structure around all elements in the set of matched elements.

  • jQuery .wrap( [ Function ] function(index) )

    New in 1.4 !

    Wrap an HTML structure around each element in the set of matched elements.

  • jQuery .prependTo( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements to the beginning of the target.

  • jQuery .prepend( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

  • jQuery .appendTo( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements to the end of the target.

  • jQuery .append( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the end of each element in the set of matched elements.

  • jQuery .text( [ Function ] function(index, text) )

    New in 1.4 !

    Set the content of each element in the set of matched elements to the specified text.

  • jQuery .html( [ Function ] function(index, oldhtml) )

    New in 1.4 !

    Set the HTML contents of each element in the set of matched elements.

  • jQuery .insertBefore( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements before the target.

  • jQuery .before( [ Function ] function )

    New in 1.4 !

    Insert content, specified by the parameter, before each element in the set of matched elements.

  • jQuery .insertAfter( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements after the target.

  • jQuery .after( [ Function ] function(index) )

    New in 1.4 !

    Insert content, specified by the parameter, after each element in the set of matched elements.

  • jQuery .unwrap( )

    New in 1.4 !

    Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

  • jQuery .detach( [ Selector ] selector )

    New in 1.4 !

    Remove the set of matched elements from the DOM.

  • jQuery .remove( [ String ] selector )

    New in 1.0 !

    Remove the set of matched elements from the DOM.

  • jQuery .empty( )

    New in 1.0 !

    Remove all child nodes of the set of matched elements from the DOM.

  • jQuery .replaceAll( [ Selector ] target )

    New in 1.2 !

    Replace each target element with the set of matched elements.

  • jQuery .replaceWith( [ Function ] function )

    New in 1.4 !

    Replace each element in the set of matched elements with the provided new content.

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.

  • jQuery .removeAttr( [ String ] attributeName )

    New in 1.0 !

    Remove an attribute from each element in the set of matched elements.

  • jQuery .attr( [ String ] attributeName, [ Function ] function(index, attr) )

    New in 1.1 !

    Set one or more attributes for the set of matched elements.

  • Integer .outerWidth( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding and border.

  • Integer .outerHeight( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.

  • Integer .innerWidth( )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding but not border.

  • Integer .innerHeight( )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding but not border.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.

  • jQuery .scrollLeft( [ Number ] value )

    New in 1.2.6 !

    Set the current horizontal position of the scroll bar for each of the set of matched elements.

  • jQuery .scrollTop( [ Number ] value )

    New in 1.2.6 !

    Set the current vertical position of the scroll bar for each of the set of matched elements.

  • Object .position( )

    New in 1.2 !

    Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.

  • jQuery .css( [ Map ] map )

    New in 1.0 !

    Set one or more CSS properties for the set of matched elements.


Class Attribute – jQuery API

Class Attribute

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • Boolean .hasClass( [ String ] className )

    New in 1.2 !

    Determine whether any of the matched elements are assigned the given class.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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


Copying – jQuery API

Copying

  • jQuery .clone( [ Boolean ] withDataAndEvents, [ Boolean ] deepWithDataAndEvents )

    New in 1.5 !

    Create a deep copy of the set of matched elements.


clone – jQuery API

Returns: jQueryjQuery .clone( [ Boolean ] withDataAndEvents, [ Boolean ] deepWithDataAndEvents )

Categories: Copying, Version 1.0, Version 1.5
Description: Create a deep copy of the set of matched elements.
  • version added: 1.0
  • .clone( [ Boolean ] withDataAndEvents )
  • withDataAndEvents A Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4, element data will be copied as well.
  • version added: 1.5
  • .clone( [ Boolean ] withDataAndEvents, [ Boolean ] deepWithDataAndEvents )
  • withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is .
  • deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to ).

The method performs a copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes. When used in conjunction with one of the insertion methods, is a convenient way to duplicate elements on a page. Consider the following HTML:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
</div>

As shown in the discussion for , normally when an element is inserted somewhere in the DOM, it is moved from its old location. So, given the code:

$('.hello').appendTo('.goodbye');

The resulting DOM structure would be:

<div class="container">
  <div class="goodbye">
    Goodbye
    <div class="hello">Hello</div>
  </div>
</div>

To prevent this and instead create a copy of the element, you could write the following:

$('.hello').clone().appendTo('.goodbye');

This would produce:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">
    Goodbye
    <div class="hello">Hello</div>
  </div>
</div>

Normally, any event handlers bound to the original element are copied to the clone. The optional parameter allows us to change this behavior, and to instead make copies of all of the event handlers as well, bound to the new copy of the element. As of jQuery 1.4, all element data (attached by the method) is also copied to the new copy.

However, objects and arrays within element data are not copied and will continue to be shared between the cloned element and the original element. To deep copy all data, copy each one manually:

var $elem = $('#elem').data( "arr": [ 1 ] ), // Original element with attached data
    $clone = $elem.clone( true )
    .data( "arr", $.extend( [], $elem.data("arr") ) ); // Deep copy to prevent data sharing

As of jQuery 1.5, can be optionally enhanced with to copy the events and data for all children of the cloned element.

Examples:

Example:

Clones all b elements (and selects the clones) and prepends them to all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

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

  <script>$("b").clone().prependTo("p");</script>
</body>
</html>

Demo:


DOM Insertion – jQuery API

DOM Insertion

    © 2010 The jQuery Project


DOM Insertion, Around – jQuery API

DOM Insertion, Around

  • jQuery .unwrap( )

    New in 1.4 !

    Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

  • jQuery .wrapInner( [ Function ] wrappingFunction )

    New in 1.4 !

    Wrap an HTML structure around the content of each element in the set of matched elements.

  • jQuery .wrapAll( [ String | Selector | Element | jQuery ] wrappingElement )

    New in 1.2 !

    Wrap an HTML structure around all elements in the set of matched elements.

  • jQuery .wrap( [ Function ] function(index) )

    New in 1.4 !

    Wrap an HTML structure around each element in the set of matched elements.


unwrap – jQuery API

Returns: jQueryjQuery .unwrap( )

Categories: DOM Insertion, Around, DOM Removal, Version 1.4
Description: Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
  • version added: 1.4
  • .unwrap( )

The method removes the element's parent. This is effectively the inverse of the method. The matched elements (and their siblings, if any) replace their parents within the DOM structure.

Examples:

Example:

Wrap/unwrap a div around each of the paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { border: 2px solid blue; }
  p { background:yellow; margin:4px; }</style>
</head>
<body>
  <button>wrap/unwrap</button>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
  <script>$("button").toggle(function(){
  $("p").wrap("<div></div>");
}, function(){
  $("p").unwrap();
});</script>
</body>
</html>

Demo:


wrapInner – jQuery API

Returns: jQueryjQuery .wrapInner( [ Function ] wrappingFunction )

Categories: DOM Insertion, Around, Version 1.2, Version 1.4
Description: Wrap an HTML structure around the content of each element in the set of matched elements.
  • version added: 1.2
  • .wrapInner( [ String ] wrappingElement )
  • wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements.
  • version added: 1.4
  • .wrapInner( [ Function ] wrappingFunction )
  • wrappingFunction A callback function which generates a structure to wrap around the content of the matched elements.

The function can take any string or object that could be passed to the factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around the content of each of the elements in the set of matched elements.

Consider the following HTML:

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

Using , we can insert an HTML structure around the content of each inner elements like so:

$('.inner').wrapInner('<div class="new" />');

The new element is created on the fly and added to the DOM. The result is a new wrapped around the content of each matched element:

<div class="container">
  <div class="inner">
    <div class="new">Hello</div>
  </div>
  <div class="inner">
    <div class="new">Goodbye</div>
  </div>
</div>

The second version of this method allows us to instead specify a callback function. This callback function will be called once for every matched element; it should return a DOM element, jQuery object, or HTML snippet in which to wrap the content of the corresponding element. For example:

$('.inner').wrapInner(function() {
  return '<div class="' + this.nodeValue + '" />';
});

This will cause each to have a class corresponding to the text it wraps:

<div class="container">
  <div class="inner">
    <div class="Hello">Hello</div>
  </div>
  <div class="inner">
    <div class="Goodbye">Goodbye</div>
  </div>
</div>

When passing a selector string to the function, the expected input is well formed HTML with correctly closed tags. Examples of valid input include:

$(elem).wrapInner("<div class='test' />");
$(elem).wrapInner("<div class='test'></div>");
$(elem).wrapInner("<div class=\"test\"></div>");

Examples:

Example:

Selects all paragraphs and wraps a bold tag around each of its contents.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:#bbf; }</style>
</head>
<body>
  <p>Hello</p>

  <p>cruel</p>
  <p>World</p>
  <script>$("p").wrapInner("<b></b>");</script>
</body>
</html>

Demo:

Example:

Wraps a newly created tree of objects around the inside of the body.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { border:2px green solid; margin:2px; padding:2px; }
  p { background:yellow; margin:2px; padding:2px; }</style>
</head>
<body>
  Plain old text, or is it?
  <script>$("body").wrapInner("<div><div><p><em><b></b></em></p></div></div>");</script>
</body>
</html>

Demo:

Example:

Selects all paragraphs and wraps a bold tag around each of its contents.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:#9f9; }</style>
</head>
<body>
  <p>Hello</p>

  <p>cruel</p>
  <p>World</p>
  <script>$("p").wrapInner(document.createElement("b"));</script>
</body>
</html>

Demo:

Example:

Selects all paragraphs and wraps a jQuery object around each of its contents.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:#9f9; }
  .red { color:red; }</style>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
  <script>$("p").wrapInner($("<span class='red'></span>"));</script>
</body>
</html>

Demo:


wrapAll – jQuery API

Returns: jQueryjQuery .wrapAll( [ String | Selector | Element | jQuery ] wrappingElement )

Categories: DOM Insertion, Around, Version 1.2, Version 1.4
Description: Wrap an HTML structure around all elements in the set of matched elements.
  • version added: 1.2
  • .wrapAll( [ String | Selector | Element | jQuery ] wrappingElement )
  • wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.

The function can take any string or object that could be passed to the function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around all of the elements in the set of matched elements, as a single group.

Consider the following HTML:

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

Using , we can insert an HTML structure around the inner elements like so:

$('.inner').wrapAll('<div class="new" />');

The new element is created on the fly and added to the DOM. The result is a new wrapped around all matched elements:

<div class="container">
  <div class="new">
    <div class="inner">Hello</div>
    <div class="inner">Goodbye</div>
  </div>
</div>

Examples:

Example:

Wrap a new div around all of the paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { border: 2px solid blue; }
  p { background:yellow; margin:4px; }</style>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
  <script>$("p").wrapAll("<div></div>");</script>
</body>
</html>

Demo:

Example:

Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { border:2px blue solid; margin:2px; padding:2px; }
  p { background:yellow; margin:2px; padding:2px; }
  strong { color:red; }</style>
</head>
<body>
  <span>Span Text</span>
  <strong>What about me?</strong>
  <span>Another One</span>
  <script>$("span").wrapAll("<div><div><p><em><b></b></em></p></div></div>");</script>
</body>
</html>

Demo:

Example:

Wrap a new div around all of the paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { border: 2px solid blue; }
  p { background:yellow; margin:4px; }</style>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
  <script>$("p").wrapAll(document.createElement("div"));</script>
</body>
</html>

Demo:

Example:

Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { border: 2px solid blue; margin:2px; padding:2px; }
  .doublediv { border-color:red; }
  p { background:yellow; margin:4px; font-size:14px; }</style>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
  <div class="doublediv"><div></div></div>
  <script>$("p").wrapAll($(".doublediv"));</script>
</body>
</html>

Demo:


wrap – jQuery API

Returns: jQueryjQuery .wrap( [ Function ] function(index) )

Categories: DOM Insertion, Around, Version 1.0, Version 1.4
Description: Wrap an HTML structure around each element in the set of matched elements.
  • version added: 1.0
  • .wrap( [ String | Selector | Element | jQuery ] wrappingElement )
  • wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.
  • version added: 1.4
  • .wrap( [ Function ] function(index) )
  • function(index) A callback function returning the HTML content or jQuery object to wrap around the matched elements.

The function can take any string or object that could be passed to the factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around each of the elements in the set of matched elements. This method returns the original set of elements for chaining purposes.

Consider the following HTML:

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

Using , we can insert an HTML structure around the inner elements like so:

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

The new element is created on the fly and added to the DOM. The result is a new wrapped around each matched element:

<div class="container">
  <div class="new">
    <div class="inner">Hello</div>
  </div>
  <div class="new">
    <div class="inner">Goodbye</div>
  </div>
</div>

The second version of this method allows us to instead specify a callback function. This callback function will be called once for every matched element; it should return a DOM element, jQuery object, or HTML snippet in which to wrap the corresponding element. For example:

$('.inner').wrap(function() {
  return '<div class="' + $(this).text() + '" />';
});

This will cause each to have a class corresponding to the text it wraps:

<div class="container">
  <div class="Hello">
    <div class="inner">Hello</div>
  </div>
  <div class="Goodbye">
    <div class="inner">Goodbye</div>
  </div>
</div>

Examples:

Example:

Wrap a new div around all of the paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { border: 2px solid blue; }
  p { background:yellow; margin:4px; }</style>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
  <script>$("p").wrap("<div></div>");</script>
</body>
</html>

Demo:

Example:

Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { border:2px blue solid; margin:2px; padding:2px; }
  p { background:yellow; margin:2px; padding:2px; }
  strong { color:red; }</style>
</head>
<body>
  <span>Span Text</span>
  <strong>What about me?</strong>
  <span>Another One</span>
  <script>$("span").wrap("<div><div><p><em><b></b></em></p></div></div>");</script>
</body>
</html>

Demo:

Example:

Wrap a new div around all of the paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { border: 2px solid blue; }
  p { background:yellow; margin:4px; }</style>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
  <script>$("p").wrap(document.createElement("div"));</script>
</body>
</html>

Demo:

Example:

Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { border: 2px solid blue; margin:2px; padding:2px; }
  .doublediv { border-color:red; }
  p { background:yellow; margin:4px; font-size:14px; }</style>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
  <div class="doublediv"><div></div></div>
  <script>$("p").wrap($(".doublediv"));</script>
</body>
</html>

Demo:


DOM Insertion, Inside – jQuery API

DOM Insertion, Inside

  • jQuery .prependTo( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements to the beginning of the target.

  • jQuery .prepend( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

  • jQuery .appendTo( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements to the end of the target.

  • jQuery .append( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the end of each element in the set of matched elements.

  • jQuery .text( [ Function ] function(index, text) )

    New in 1.4 !

    Set the content of each element in the set of matched elements to the specified text.

  • jQuery .html( [ Function ] function(index, oldhtml) )

    New in 1.4 !

    Set the HTML contents of each element in the set of matched elements.


prependTo – jQuery API

Returns: jQueryjQuery .prependTo( [ Selector | Element | jQuery ] target )

Categories: DOM Insertion, Inside, Version 1.0
Description: Insert every element in the set of matched elements to the beginning of the target.
  • version added: 1.0
  • .prependTo( [ Selector | Element | jQuery ] target )
  • target A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter.

The and methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With, the selector expression preceding the method is the container into which the content is inserted. With , on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

Consider the following HTML:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

We can create content and insert it into several elements at once:

$('<p>Test</p>').prependTo('.inner');

Each inner element gets this new content:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">
    <p>Test</p>
    Hello
  </div>
  <div class="inner">
    <p>Test</p>
    Goodbye
  </div>
</div>

We can also select an element on the page and insert it into another:

$('h2').prependTo($('.container'));

If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

Examples:

Example:

Prepends all spans to the element with the ID "foo"
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { background:yellow; }</style>
</head>
<body>
  <div id="foo">FOO!</div>

  <span>I have something to say... </span>
  <script>$("span").prependTo("#foo"); // check prepend() examples</script>
</body>
</html>

Demo:


prepend – jQuery API

Returns: jQueryjQuery .prepend( [ Function ] function(index, html) )

Categories: DOM Insertion, Inside, Version 1.0, Version 1.4
Description: Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
  • version added: 1.0
  • .prepend( [ String | Element | jQuery ] content, [ String | Element | jQuery ] content )
  • content DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.
  • content One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements.
  • version added: 1.4
  • .prepend( [ Function ] function(index, html) )
  • function(index, html) A function that returns an HTML string to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments.

The method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the child, use ).

The and methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With, the selector expression preceding the method is the container into which the content is inserted. With , on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

Consider the following HTML:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

You can create content and insert it into several elements at once:

$('.inner').prepend('<p>Test</p>');

Each element gets this new content:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">
    <p>Test</p>
    Hello
  </div>
  <div class="inner">
    <p>Test</p>
    Goodbye
  </div>
</div>

You can also select an element on the page and insert it into another:

$('.container').prepend($('h2'));

If selected this way is inserted elsewhere, it will be moved into the target ():

<div class="container">
    <h2>Greetings</h2>
    <div class="inner">Hello</div>
    <div class="inner">Goodbye</div>
</div>

: If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

Additional Arguments

Similar to other content-adding methods such as and , also supports passing in multiple arguments as input. Supported input includes DOM elements, jQuery objects, HTML strings, and arrays of DOM elements.

For example, the following will insert two new s and an existing as the first three child nodes of the body:

var $newdiv1 = $('<div id="object1"/>'),
    newdiv2 = document.createElement('div'),
    existingdiv1 = document.getElementById('foo');

$('body').prepend($newdiv1, [newdiv2, existingdiv1]);

Since can accept any number of additional arguments, the same result can be achieved by passing in the three s as three separate arguments, like so: . The type and number of arguments will largely depend on how you collect the elements in your code.

Examples:

Example:

Prepends some HTML to all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p>there, friend!</p>

<p>amigo!</p>
  <script>$("p").prepend("<b>Hello </b>");</script>
</body>
</html>

Demo:

Example:

Prepends a DOM Element to all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p>is what I'd say</p>
<p>is what I said</p>
  <script>$("p").prepend(document.createTextNode("Hello "));</script>
</body>
</html>

Demo:

Example:

Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p> is what was said.</p><b>Hello</b>
  <script>$("p").prepend( $("b") );</script>
</body>
</html>

Demo:


appendTo – jQuery API

Returns: jQueryjQuery .appendTo( [ Selector | Element | jQuery ] target )

Categories: DOM Insertion, Inside, Version 1.0
Description: Insert every element in the set of matched elements to the end of the target.
  • version added: 1.0
  • .appendTo( [ Selector | Element | jQuery ] target )
  • target A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.

The and methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With, the selector expression preceding the method is the container into which the content is inserted. With , on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

Consider the following HTML:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

We can create content and insert it into several elements at once:

$('<p>Test</p>').appendTo('.inner');

Each inner element gets this new content:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">
    Hello
    <p>Test</p>
  </div>
  <div class="inner">
    Goodbye
    <p>Test</p>
  </div>
</div>

We can also select an element on the page and insert it into another:

$('h2').appendTo($('.container'));

If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
  <h2>Greetings</h2>
</div>

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

Examples:

Example:

Appends all spans to the element with the ID "foo"
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>#foo { background:yellow; }</style>
</head>
<body>
  <span>I have nothing more to say... </span>

  <div id="foo">FOO! </div>
  <script>$("span").appendTo("#foo"); // check append() examples</script>
</body>
</html>

Demo:


append – jQuery API

Returns: jQueryjQuery .append( [ Function ] function(index, html) )

Categories: DOM Insertion, Inside, Version 1.0, Version 1.4
Description: Insert content, specified by the parameter, to the end of each element in the set of matched elements.
  • version added: 1.0
  • .append( [ String | Element | jQuery ] content, [ String | Element | Array | jQuery ] content )
  • content DOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
  • content One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.
  • version added: 1.4
  • .append( [ Function ] function(index, html) )
  • function(index, html) A function that returns an HTML string to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments.

The method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the child, use ).

The and methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With, the selector expression preceding the method is the container into which the content is inserted. With , on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

Consider the following HTML:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

You can create content and insert it into several elements at once:

$('.inner').append('<p>Test</p>');

Each inner element gets this new content:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">
    Hello
    <p>Test</p>
  </div>
  <div class="inner">
    Goodbye
    <p>Test</p>
  </div>
</div>

You can also select an element on the page and insert it into another:

$('.container').append($('h2'));

If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
  <h2>Greetings</h2>
</div>

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

Additional Arguments

Similar to other content-adding methods such as and , also supports passing in multiple arguments as input. Supported input includes DOM elements, jQuery objects, HTML strings, and arrays of DOM elements.

For example, the following will insert two new s and an existing as the last three child nodes of the body:

var $newdiv1 = $('<div id="object1"/>'),
    newdiv2 = document.createElement('div'),
    existingdiv1 = document.getElementById('foo');

$('body').append($newdiv1, [newdiv2, existingdiv1]);

Since can accept any number of additional arguments, the same result can be achieved by passing in the three s as three separate arguments, like so: . The type and number of arguments will largely depend on how you collect the elements in your code.

Examples:

Example:

Appends some HTML to all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p>I would like to say: </p>
  <script>$("p").append("<strong>Hello</strong>");</script>
</body>
</html>

Demo:

Example:

Appends an Element to all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p>I would like to say: </p>

  <script>$("p").append(document.createTextNode("Hello"));</script>
</body>
</html>

Demo:

Example:

Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <strong>Hello world!!!</strong><p>I would like to say: </p>
  <script>$("p").append( $("strong") );</script>
</body>
</html>

Demo:


text – jQuery API

  • text ( )

    • 1.0text ( )

  • text ( )

    • 1.0text ( )

  • text ( [ String ] textString )

    • 1.0text ( [ String ] textString )
    • 1.4text ( [ Function ] function(index, text) )

Returns: JQuery(":text")

Categories: Form, Version 1.0
Description: Selects all elements of type text.
  • version added: 1.0
  • JQuery(":text")

is equivalent to and thus selects all elements. As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare is equivalent to , so should be used instead.

As of jQuery 1.5.2, selects elements that have no specified attribute (in which case is implied).

Examples:

Example:

Finds all text inputs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>textarea { height:25px; }</style>
</head>
<body>
  <form>
    <input type="button" value="Input Button"/>
    <input type="checkbox" />

    <input type="file" />
    <input type="hidden" />
    <input type="image" />

    <input type="password" />
    <input type="radio" />
    <input type="reset" />

    <input type="submit" />
    <input type="text" />
    <select><option>Option</option></select>

    <textarea></textarea>
    <button>Button</button>
  </form>
  <div>
  </div>
  <script>var input = $("form input:text").css({background:"yellow", border:"3px red solid"});
    $("div").text("For this type jQuery found " + input.length + ".")
            .css("color", "red");
    $("form").submit(function () { return false; }); // so it won't submit</script>
</body>
</html>

Demo:

Returns: StringString .text( )

Categories: DOM Insertion, Inside, Version 1.0, Version 1.4
Description: Get the combined text contents of each element in the set of matched elements, including their descendants.
  • version added: 1.0
  • .text( )

Unlike the method, can be used in both XML and HTML documents. The result of the method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.) Consider the following HTML:

<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
  <ul>
  <li>list item 1</li>
  <li>list <strong>item</strong> 2</li>
  </ul>
  </div>

The code would produce the following result:

The method cannot be used on input elements. For input field text, use the method.

As of jQuery 1.4, the method returns the value of text and CDATA nodes as well as element nodes.

Examples:

Example:

Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone).
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:blue; margin:8px; }
  b { color:red; }</style>
</head>
<body>
  <p><b>Test</b> Paragraph.</p>

  <p></p>
  <script>var str = $("p:first").text();
    $("p:last").html(str);</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .text( [ Function ] function(index, text) )

Categories: DOM Insertion, Inside, Version 1.0, Version 1.4
Description: Set the content of each element in the set of matched elements to the specified text.
  • version added: 1.0
  • .text( [ String ] textString )
  • textString A string of text to set as the content of each matched element.
  • version added: 1.4
  • .text( [ Function ] function(index, text) )
  • function(index, text) A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.

Unlike the method, can be used in both XML and HTML documents.

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method , which replaces special characters with their HTML entity equivalents (such as for ). Consider the following HTML:

<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
  <ul>
    <li>list item 1</li>
    <li>list <strong>item</strong> 2</li>
  </ul>
</div>

The code will produce the following DOM output:

<div class="demo-container">
&lt;p&gt;This is a test.&lt;/p&gt;
</div>

It will appear on a rendered page as though the tags were exposed, like this:

<p>This is a test</p>

The method cannot be used on input elements. For input field text, use the method.

As of jQuery 1.4, the method allows us to set the text content by passing in a function.

$('ul li').text(function(index) {
  return 'item number ' + (index + 1);
});

Given an unordered list with three elements, this example will produce the following DOM output:

<ul>
  <li>item number 1</li>
  <li>item number 2</li>
  <li>item number 3</li>
</ul>

Examples:

Example:

Add text to the paragraph (notice the bold tag is escaped).
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:blue; margin:8px; }</style>
</head>
<body>
  <p>Test Paragraph.</p>
  <script>$("p").text("<b>Some</b> new text.");</script>
</body>
</html>

Demo:


DOM Insertion, Outside – jQuery API

DOM Insertion, Outside

  • jQuery .insertBefore( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements before the target.

  • jQuery .before( [ Function ] function )

    New in 1.4 !

    Insert content, specified by the parameter, before each element in the set of matched elements.

  • jQuery .insertAfter( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements after the target.

  • jQuery .after( [ Function ] function(index) )

    New in 1.4 !

    Insert content, specified by the parameter, after each element in the set of matched elements.


insertBefore – jQuery API

Returns: jQueryjQuery .insertBefore( [ Selector | Element | jQuery ] target )

Categories: DOM Insertion, Outside, Version 1.0
Description: Insert every element in the set of matched elements before the target.
  • version added: 1.0
  • .insertBefore( [ Selector | Element | jQuery ] target )
  • target A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter.

The and methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With, the selector expression preceding the method is the container before which the content is inserted. With , on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted before the target container.

Consider the following HTML:

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

We can create content and insert it before several elements at once:

$('<p>Test</p>').insertBefore('.inner');

Each inner element gets this new content:

<div class="container">
  <h2>Greetings</h2>
  <p>Test</p>
  <div class="inner">Hello</div>
  <p>Test</p>
  <div class="inner">Goodbye</div>
</div>

We can also select an element on the page and insert it before another:

$('h2').insertBefore($('.container'));

If an element selected this way is inserted elsewhere, it will be moved before the target (not cloned):

<h2>Greetings</h2>
<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

Examples:

Example:

Inserts all paragraphs before an element with id of "foo". Same as $("#foo").before("p")
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>#foo { background:yellow; }</style>
</head>
<body>
  <div id="foo">FOO!</div><p>I would like to say: </p>
  <script>$("p").insertBefore("#foo"); // check before() examples</script>
</body>
</html>

Demo:


before – jQuery API

Returns: jQueryjQuery .before( [ Function ] function )

Categories: DOM Insertion, Outside, Version 1.0, Version 1.4
Description: Insert content, specified by the parameter, before each element in the set of matched elements.
  • version added: 1.0
  • .before( [ String | Element | jQuery ] content, [ String | Element | Array | jQuery ] content )
  • content HTML string, DOM element, or jQuery object to insert before each element in the set of matched elements.
  • content One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements.
  • version added: 1.4
  • .before( [ Function ] function )
  • function A function that returns an HTML string to insert before each element in the set of matched elements.

The and methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With, the selector expression preceding the method is the container before which the content is inserted. With , on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted before the target container.

Consider the following HTML:

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

You can create content and insert it before several elements at once:

$('.inner').before('<p>Test</p>');

Each inner element gets this new content:

<div class="container">
  <h2>Greetings</h2>
  <p>Test</p>
  <div class="inner">Hello</div>
  <p>Test</p>
  <div class="inner">Goodbye</div>
</div>

You can also select an element on the page and insert it before another:

$('.container').before($('h2'));

If an element selected this way is inserted elsewhere, it will be moved before the target (not cloned):

<h2>Greetings</h2>
<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

In jQuery 1.4, and will also work on disconnected DOM nodes:

$("<div/>").before("<p></p>");

The result is a jQuery set that contains a paragraph and a div (in that order).

Additional Arguments

Similar to other content-adding methods such as and , also supports passing in multiple arguments as input. Supported input includes DOM elements, jQuery objects, HTML strings, and arrays of DOM elements.

For example, the following will insert two new s and an existing before the first paragraph:

var $newdiv1 = $('<div id="object1"/>'),
    newdiv2 = document.createElement('div'),
    existingdiv1 = document.getElementById('foo');

$('p').first().before($newdiv1, [newdiv2, existingdiv1]);

Since can accept any number of additional arguments, the same result can be achieved by passing in the three s as three separate arguments, like so: . The type and number of arguments will largely depend on how you collect the elements in your code.

Examples:

Example:

Inserts some HTML before all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p> is what I said...</p>
  <script>$("p").before("<b>Hello</b>");</script>
</body>
</html>

Demo:

Example:

Inserts a DOM element before all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p> is what I said...</p>
  <script>$("p").before( document.createTextNode("Hello") );</script>
</body>
</html>

Demo:

Example:

Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p> is what I said...</p><b>Hello</b>
  <script>$("p").before( $("b") );</script>
</body>
</html>

Demo:


insertAfter – jQuery API

Returns: jQueryjQuery .insertAfter( [ Selector | Element | jQuery ] target )

Categories: DOM Insertion, Outside, Version 1.0
Description: Insert every element in the set of matched elements after the target.
  • version added: 1.0
  • .insertAfter( [ Selector | Element | jQuery ] target )
  • target A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter.

The and methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With, the selector expression preceding the method is the container after which the content is inserted. With , on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.

Consider the following HTML:

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

We can create content and insert it after several elements at once:

$('<p>Test</p>').insertAfter('.inner');

Each inner element gets this new content:

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <p>Test</p>
  <div class="inner">Goodbye</div>
  <p>Test</p>
</div>

We can also select an element on the page and insert it after another:

$('h2').insertAfter($('.container'));

If an element selected this way is inserted elsewhere, it will be moved after the target (not cloned):

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>
<h2>Greetings</h2>

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

Examples:

Example:

Inserts all paragraphs after an element with id of "foo". Same as $("#foo").after("p")
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>#foo { background:yellow; }</style>
</head>
<body>
  <p> is what I said... </p><div id="foo">FOO!</div>
  <script>$("p").insertAfter("#foo"); // check after() examples</script>
</body>
</html>

Demo:


after – jQuery API

Returns: jQueryjQuery .after( [ Function ] function(index) )

Categories: DOM Insertion, Outside, Version 1.0, Version 1.4
Description: Insert content, specified by the parameter, after each element in the set of matched elements.
  • version added: 1.0
  • .after( [ String | Element | jQuery ] content, [ String | Element | Array | jQuery ] content )
  • content HTML string, DOM element, or jQuery object to insert after each element in the set of matched elements.
  • content One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements.
  • version added: 1.4
  • .after( [ Function ] function(index) )
  • function(index) A function that returns an HTML string to insert after each element in the set of matched elements.

The and methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With, the selector expression preceding the method is the container after which the content is inserted. With , on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.

Using the following HTML:

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

Content can be created and then inserted after several elements at once:

$('.inner').after('<p>Test</p>');

Each inner element gets this new content:

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <p>Test</p>
  <div class="inner">Goodbye</div>
  <p>Test</p>
</div>

An element in the DOM can also be selected and inserted after another element:

$('.container').after($('h2'));

If an element selected this way is inserted elsewhere, it will be moved rather than cloned:

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>
<h2>Greetings</h2>

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

Inserting Disconnected DOM nodes

As of jQuery 1.4, and will also work on disconnected DOM nodes. For example, given the following code:

$('<div/>').after('<p></p>');

The result is a jQuery set containing a div and a paragraph, in that order. That set can be further manipulated, even before it is inserted in the document.

$('<div/>').after('<p></p>').addClass('foo')
  .filter('p').attr('id', 'bar').html('hello')
.end()
.appendTo('body');

This results in the following elements inserted just before the closing tag:

<div class="foo"></div>
<p class="foo" id="bar">hello</p>

Passing a Function

As of jQuery 1.4, supports passing a function that returns the elements to insert.

$('p').after(function() {
  return '<div>' + this.className + '</div>';
});

This example inserts a after each paragraph, with each new containing the class name(s) of its preceding paragraph.

Additional Arguments

Similar to other content-adding methods such as and , also supports passing in multiple arguments as input. Supported input includes DOM elements, jQuery objects, HTML strings, and arrays of DOM elements.

For example, the following will insert two new s and an existing after the first paragraph:

var $newdiv1 = $('<div id="object1"/>'),
    newdiv2 = document.createElement('div'),
    existingdiv1 = document.getElementById('foo');

$('p').first().after($newdiv1, [newdiv2, existingdiv1]);

Since can accept any number of additional arguments, the same result can be achieved by passing in the three s as three separate arguments, like so: . The type and number of arguments will largely depend on the elements are collected in the code.

Examples:

Example:

Inserts some HTML after all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p>I would like to say: </p>
  <script>$("p").after("<b>Hello</b>");</script>
</body>
</html>

Demo:

Example:

Inserts a DOM element after all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p>I would like to say: </p>
  <script>$("p").after( document.createTextNode("Hello") );</script>
</body>
</html>

Demo:

Example:

Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <b>Hello</b><p>I would like to say: </p>
  <script>$("p").after( $("b") );</script>
</body>
</html>

Demo:


DOM Removal – jQuery API

DOM Removal

  • jQuery .unwrap( )

    New in 1.4 !

    Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

  • jQuery .detach( [ Selector ] selector )

    New in 1.4 !

    Remove the set of matched elements from the DOM.

  • jQuery .remove( [ String ] selector )

    New in 1.0 !

    Remove the set of matched elements from the DOM.

  • jQuery .empty( )

    New in 1.0 !

    Remove all child nodes of the set of matched elements from the DOM.


detach – jQuery API

Returns: jQueryjQuery .detach( [ Selector ] selector )

Categories: DOM Removal, Version 1.4
Description: Remove the set of matched elements from the DOM.
  • version added: 1.4
  • .detach( [ Selector ] selector )
  • selector A selector expression that filters the set of matched elements to be removed.

The method is the same as , except that keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

Examples:

Example:

Detach all paragraphs from the DOM
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; margin:6px 0; } p.off { background: black; }</style>
</head>
<body>
  <p>Hello</p>
  how are
  <p>you?</p>
  <button>Attach/detach paragraphs</button>
  <script>$("p").click(function(){
      $(this).toggleClass("off");
    });
    var p;
    $("button").click(function(){
      if ( p ) {
        p.appendTo("body");
        p = null;
      } else {
        p = $("p").detach();
      }
    });</script>
</body>
</html>

Demo:


remove – jQuery API

Returns: jQueryjQuery .remove( [ String ] selector )

Categories: DOM Removal, Version 1.0
Description: Remove the set of matched elements from the DOM.
  • version added: 1.0
  • .remove( [ String ] selector )
  • selector A selector expression that filters the set of matched elements to be removed.

Similar to , the method takes elements out of the DOM. Use when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use instead.

Consider the following HTML:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
</div>

We can target any element for removal:

$('.hello').remove();

This will result in a DOM structure with the element deleted:

<div class="container">
  <div class="goodbye">Goodbye</div>
</div>

If we had any number of nested elements inside , they would be removed, too. Other jQuery constructs such as data or event handlers are erased as well.

We can also include a selector as an optional parameter. For example, we could rewrite the previous DOM removal code as follows:

$('div').remove('.hello');

This would result in the same DOM structure:

<div class="container">
  <div class="goodbye">Goodbye</div>
</div>

Examples:

Example:

Removes all paragraphs from the DOM
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; margin:6px 0; }</style>
</head>
<body>
  <p>Hello</p>
  how are
  <p>you?</p>
  <button>Call remove() on paragraphs</button>
  <script>$("button").click(function () {
      $("p").remove();
    });</script>
</body>
</html>

Demo:

Example:

Removes all paragraphs that contain "Hello" from the DOM. Analogous to doing .
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; margin:6px 0; }</style>
</head>
<body>
  <p class="hello">Hello</p>
  how are
  <p>you?</p>

  <button>Call remove(":contains('Hello')") on paragraphs</button>
  <script>$("button").click(function () {
      $("p").remove(":contains('Hello')");
    });</script>
</body>
</html>

Demo:


empty – jQuery API

  • empty ( )

    • 1.0empty ( )

  • empty ( )

    • 1.0empty ( )

Returns: JQuery(":empty")

Categories: Content Filter, Version 1.0
Description: Select all elements that have no children (including text nodes).
  • version added: 1.0
  • JQuery(":empty")

This is the inverse of .

One important thing to note with :empty (and :parent) is that child elements include text nodes.

The W3C recommends that the element have at least one child node, even if that child is merely text (see http://www.w3.org/TR/html401/struct/text.html#edef-P). Some other elements, on the other hand, are empty (i.e. have no children) by definition: <input>, <img>, <br>, and <hr>, for example.

Examples:

Example:

Finds all elements that are empty - they don't have child elements or text.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>td { text-align:center; }</style>
</head>
<body>
  <table border="1">
    <tr><td>TD #0</td><td></td></tr>
    <tr><td>TD #2</td><td></td></tr>

    <tr><td></td><td>TD#5</td></tr>
  </table>
  <script>$("td:empty").text("Was empty!").css('background', 'rgb(255,220,200)');</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .empty( )

Categories: DOM Removal, Version 1.0
Description: Remove all child nodes of the set of matched elements from the DOM.
  • version added: 1.0
  • .empty( )

This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element. Consider the following HTML:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
</div>

We can target any element for removal:

$('.hello').empty();

This will result in a DOM structure with the text deleted:

<div class="container">
  <div class="hello"></div>
  <div class="goodbye">Goodbye</div>
</div>

If we had any number of nested elements inside , they would be removed, too.

To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

Examples:

Example:

Removes all child nodes (including text nodes) from all paragraphs
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p>
  Hello, <span>Person</span> <a href="javascript:;">and person</a>
</p>

<button>Call empty() on above paragraph</button>
  <script>$("button").click(function () {
    $("p").empty();
  });</script>
</body>
</html>

Demo:


DOM Replacement – jQuery API

DOM Replacement

  • jQuery .replaceAll( [ Selector ] target )

    New in 1.2 !

    Replace each target element with the set of matched elements.

  • jQuery .replaceWith( [ Function ] function )

    New in 1.4 !

    Replace each element in the set of matched elements with the provided new content.


replaceAll – jQuery API

Returns: jQueryjQuery .replaceAll( [ Selector ] target )

Categories: DOM Replacement, Version 1.2
Description: Replace each target element with the set of matched elements.
  • version added: 1.2
  • .replaceAll( [ Selector ] target )
  • target A selector expression indicating which element(s) to replace.

The method is corollary to , but with the source and target reversed. Consider this DOM structure:

<div class="container">
  <div class="inner first">Hello</div>
  <div class="inner second">And</div>
  <div class="inner third">Goodbye</div>
</div>

We can create an element, then replace other elements with it:

$('<h2>New heading</h2>').replaceAll('.inner');

This causes all of them to be replaced:

<div class="container">
  <h2>New heading</h2>
  <h2>New heading</h2>
  <h2>New heading</h2>
</div>

Or, we could select an element to use as the replacement:

$('.first').replaceAll('.third');

This results in the DOM structure:

<div class="container">
  <div class="inner second">And</div>
  <div class="inner first">Hello</div>
</div>

From this example, we can see that the selected element replaces the target by being moved from its old location, not by being cloned.

Examples:

Example:

Replace all the paragraphs with bold words.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
  <script>$("<b>Paragraph. </b>").replaceAll("p"); // check replaceWith() examples</script>
</body>
</html>

Demo:


replaceWith – jQuery API

Returns: jQueryjQuery .replaceWith( [ Function ] function )

Categories: DOM Replacement, Version 1.2, Version 1.4
Description: Replace each element in the set of matched elements with the provided new content.
  • version added: 1.2
  • .replaceWith( [ String | Element | jQuery ] newContent )
  • newContent The content to insert. May be an HTML string, DOM element, or jQuery object.
  • version added: 1.4
  • .replaceWith( [ Function ] function )
  • function A function that returns content with which to replace the set of matched elements.

The method removes content from the DOM and inserts new content in its place with a single call. Consider this DOM structure:

<div class="container">
  <div class="inner first">Hello</div>
  <div class="inner second">And</div>
  <div class="inner third">Goodbye</div>
</div>

The second inner could be replaced with the specified HTML:

$('div.second').replaceWith('<h2>New heading</h2>');

This results in the structure:

<div class="container">
  <div class="inner first">Hello</div>
  <h2>New heading</h2>
  <div class="inner third">Goodbye</div>
</div>

inner elements could be targeted at once:

$('div.inner').replaceWith('<h2>New heading</h2>');

This causes all of them to be replaced:

<div class="container">
  <h2>New heading</h2>
  <h2>New heading</h2>
  <h2>New heading</h2>
</div>

An element could also be selected as the replacement:

$('div.third').replaceWith($('.first'));

This results in the DOM structure:

<div class="container">
  <div class="inner second">And</div>
  <div class="inner first">Hello</div>
</div>

This example demonstrates that the selected element replaces the target by being moved from its old location, not by being cloned.

The method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.

As of jQuery 1.4, can also work on disconnected DOM nodes. For example, with the following code, returns a jQuery set containing only a paragraph.:

$("<div/>").replaceWith("<p></p>");

The method can also take a function as its argument:

$('div.container').replaceWith(function() {
  return $(this).contents();
});

This results in being replaced by its three child s. The return value of the function may be an HTML string, DOM element, or jQuery object.

Examples:

Example:

On click, replace the button with a div containing the same word.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>button { display:block; margin:3px; color:red; width:200px; }
  div { color:red; border:2px solid blue; width:200px;
      margin:3px; text-align:center; }</style>
</head>
<body>

<button>First</button>
<button>Second</button>
<button>Third</button>

  <script>$("button").click(function () {
  $(this).replaceWith( "<div>" + $(this).text() + "</div>" );
});</script>
</body>
</html>

Demo:

Example:

Replace all paragraphs with bold words.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

<p>Hello</p>
<p>cruel</p>
<p>World</p>

  <script>$("p").replaceWith( "<b>Paragraph. </b>" );</script>
</body>
</html>

Demo:

Example:

Replace all paragraphs with empty div elements.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { border:2px solid blue; margin:3px; }</style>
</head>
<body>

<p>Hello</p>
<p>cruel</p>
<p>World</p>

  <script>$("p").replaceWith( document.createElement("div") );</script>
</body>
</html>

Demo:

Example:

On click, replace each paragraph with a div that is already in the DOM and selected with the function. Notice it doesn't clone the object but rather moves it to replace the paragraph.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { border:2px solid blue; color:red; margin:3px; }
  p { border:2px solid red; color:blue; margin:3px; cursor:pointer; }</style>
</head>
<body>

  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>

  <div>Replaced!</div>

  <script>$("p").click(function () {
  $(this).replaceWith( $("div") );
});</script>
</body>
</html>

Demo:

Example:

On button click, replace the containing div with its child divs and append the class name of the selected element to the paragraph.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>.container { background-color: #991; }
  .inner { color: #911; }</style>
</head>
<body>

<p>
  <button>Replace!</button>
</p>
<div class="container">
  <div class="inner">Scooby</div>
  <div class="inner">Dooby</div>
  <div class="inner">Doo</div>
</div>

  <script>$('button').bind("click", function() {
  var $container = $("div.container").replaceWith(function() {
    return $(this).contents();
  });

  $("p").append( $container.attr("class") );
});</script>
</body>
</html>

Demo:


General Attributes – jQuery API

General Attributes

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.

  • jQuery .removeAttr( [ String ] attributeName )

    New in 1.0 !

    Remove an attribute from each element in the set of matched elements.

  • jQuery .attr( [ String ] attributeName, [ Function ] function(index, attr) )

    New in 1.1 !

    Set one or more attributes for the set of matched elements.


Style Properties – jQuery API

Style Properties

  • Integer .outerWidth( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding and border.

  • Integer .outerHeight( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.

  • Integer .innerWidth( )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding but not border.

  • Integer .innerHeight( )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding but not border.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.

  • jQuery .scrollLeft( [ Number ] value )

    New in 1.2.6 !

    Set the current horizontal position of the scroll bar for each of the set of matched elements.

  • jQuery .scrollTop( [ Number ] value )

    New in 1.2.6 !

    Set the current vertical position of the scroll bar for each of the set of matched elements.

  • Object .position( )

    New in 1.2 !

    Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.

  • jQuery .css( [ Map ] map )

    New in 1.0 !

    Set one or more CSS properties for the set of matched elements.


Miscellaneous – jQuery API

Miscellaneous

  • jQuery .each( [ Function ] function(index, Element) )

    New in 1.0 !

    Iterate over a jQuery object, executing a function for each matched element.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

  • jQuery .removeData( [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • Array .toArray( )

    New in 1.4 !

    Retrieve all the DOM elements contained in the jQuery set, as an array.

  • Number .index( [ Element | jQuery ] element )

    New in 1.0 !

    Search for a given element from among the matched elements.

  • Element, Array .get( [ Number ] index )

    New in 1.0 !

    Retrieve the DOM elements matched by the jQuery object.

  • Number .size( )

    New in 1.0 !

    Return the number of elements in the jQuery object.

  • Object jQuery.noConflict( [ Boolean ] removeAll )

    New in 1.0 !

    Relinquish jQuery's control of the variable.


Collection Manipulation – jQuery API

Collection Manipulation

  • jQuery .each( [ Function ] function(index, Element) )

    New in 1.0 !

    Iterate over a jQuery object, executing a function for each matched element.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.


each – jQuery API

Returns: jQueryjQuery .each( [ Function ] function(index, Element) )

Categories: Collection Manipulation, Traversing, Version 1.0
Description: Iterate over a jQuery object, executing a function for each matched element.
  • version added: 1.0
  • .each( [ Function ] function(index, Element) )
  • function(index, Element) A function to execute for each matched element.

The method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword refers to the element.

Suppose we had a simple unordered list on the page:

<ul>
    <li>foo</li>
    <li>bar</li>
  </ul>

We can select the list items and iterate across them:

$('li').each(function(index) {
    alert(index + ': ' + $(this).text());
  });

A message is thus alerted for each item in the list:

We can stop the loop from within the callback function by returning .

Examples:

Example:

Iterates over three divs and sets their color property.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:red; text-align:center; cursor:pointer;
        font-weight:bolder; width:300px; }</style>
</head>
<body>
  <div>Click here</div>

  <div>to iterate through</div>
  <div>these divs.</div>
  <script>$(document.body).click(function () {
      $("div").each(function (i) {
        if (this.style.color != "blue") {
          this.style.color = "blue";
        } else {
          this.style.color = "";
        }
      });
    });</script>
</body>
</html>

Demo:

Example:

If you want to have the jQuery object instead of the regular DOM element, use the $(this) function, for example:
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>ul { font-size:18px; margin:0; }
  span { color:blue; text-decoration:underline; cursor:pointer; }
  .example { font-style:italic; }</style>
</head>
<body>
  To do list: <span>(click here to change)</span>
  <ul>
    <li>Eat</li>
    <li>Sleep</li>

    <li>Be merry</li>
  </ul>
  <script>$("span").click(function () {
      $("li").each(function(){
        $(this).toggleClass("example");
      });
    });</script>
</body>
</html>

Demo:

Example:

You can use 'return' to break out of each() loops early.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:40px; height:40px; margin:5px; float:left;
        border:2px blue solid; text-align:center; }
  span { color:red; }</style>
</head>
<body>
  <button>Change colors</button>
  <span></span>
  <div></div>
  <div></div>

  <div></div>
  <div></div>
  <div id="stop">Stop here</div>
  <div></div>

  <div></div>
  <div></div>
  <script>$("button").click(function () {
      $("div").each(function (index, domEle) {
        // domEle == this
        $(domEle).css("backgroundColor", "yellow");
        if ($(this).is("#stop")) {
          $("span").text("Stopped at div index #" + index);
          return false;
        }
      });
    });</script>
</body>
</html>

Demo:


Data Storage – jQuery API

Data Storage

  • jQuery .removeData( [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).


DOM Element Methods – jQuery API

DOM Element Methods

  • Array .toArray( )

    New in 1.4 !

    Retrieve all the DOM elements contained in the jQuery set, as an array.

  • Number .index( [ Element | jQuery ] element )

    New in 1.0 !

    Search for a given element from among the matched elements.

  • Element, Array .get( [ Number ] index )

    New in 1.0 !

    Retrieve the DOM elements matched by the jQuery object.

  • Number .size( )

    New in 1.0 !

    Return the number of elements in the jQuery object.


toArray – jQuery API

Returns: ArrayArray .toArray( )

Categories: DOM Element Methods, Version 1.4
Description: Retrieve all the DOM elements contained in the jQuery set, as an array.
  • version added: 1.4
  • .toArray( )

returns all of the elements in the jQuery set:

alert($('li').toArray());

All of the matched DOM nodes are returned by this call, contained in a standard array:

Examples:

Example:

Selects all divs in the document and returns the DOM Elements as an Array, then uses the built-in reverse-method to reverse that array.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span { color:red; }</style>
</head>
<body>
  Reversed - <span></span>

  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <script>function disp(divs) {
      var a = [];
      for (var i = 0; i < divs.length; i++) {
        a.push(divs[i].innerHTML);
      }
      $("span").text(a.join(" "));
    }

    disp( $("div").toArray().reverse() );</script>
</body>
</html>

Demo:


index – jQuery API

Returns: NumberNumber .index( [ Element | jQuery ] element )

Categories: DOM Element Methods, Version 1.0, Version 1.4
Description: Search for a given element from among the matched elements.
  • version added: 1.4
  • .index( )
  • version added: 1.4
  • .index( [ Selector ] selector )
  • selector A selector representing a jQuery collection in which to look for an element.
  • version added: 1.0
  • .index( [ Element | jQuery ] element )
  • element The DOM element or first element within the jQuery object to look for.

Return Values

If no argument is passed to the method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

If is called on a collection of elements and a DOM element or jQuery object is passed in, returns an integer indicating the position of the passed element relative to the original collection.

If a selector string is passed as an argument, returns an integer indicating the position of the original element relative to the elements matched by the selector. If the element is not found, will return -1.

Detail

The complementary operation to , which accepts an index and returns a DOM node, can take a DOM node and returns an index. Suppose we have a simple unordered list on the page:

<ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>

If we retrieve one of the three list items (for example, through a DOM function or as the context to an event handler), can search for this list item within the set of matched elements:

var listItem = document.getElementById('bar');
alert('Index: ' + $('li').index(listItem));
We get back the zero-based position of the list item:

Similarly, if we retrieve a jQuery object consisting of one of the three list items, will search for that list item:

var listItem = $('#bar');
alert('Index: ' + $('li').index(listItem));

We get back the zero-based position of the list item:

Note that if the jQuery collection used as the method's argument contains more than one element, the first element within the matched set of elements will be used.

var listItems = $('li:gt(0)');
alert('Index: ' + $('li').index(listItems));

We get back the zero-based position of the first list item within the matched set:

If we use a string as the method's argument, it is interpreted as a jQuery selector string. The first element among the object's matched elements which also matches this selector is located.

var listItem = $('#bar');
alert('Index: ' + listItem.index('li'));

We get back the zero-based position of the list item:

If we omit the argument, will return the position of the first element within the set of matched elements in relation to its siblings:

alert('Index: ' + $('#bar').index();

Again, we get back the zero-based position of the list item:

Examples:

Example:

On click, returns the index (based zero) of that div in the page.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { background:yellow; margin:5px; }
span { color:red; }</style>
</head>
<body>
  <span>Click a div!</span>
<div>First div</div>
<div>Second div</div>
<div>Third div</div>
  <script>$("div").click(function () {
  // this is the dom element clicked
  var index = $("div").index(this);
  $("span").text("That was div index #" + index);
});</script>
</body>
</html>

Demo:

Example:

Returns the index for the element with ID bar.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { font-weight: bold; color: #090; }</style>
</head>
<body>
  <ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>
<div></div>
  <script>var listItem = $('#bar');
    $('div').html( 'Index: ' + $('li').index(listItem) );</script>
</body>
</html>

Demo:

Example:

Returns the index for the first item in the jQuery collection.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { font-weight: bold; color: #090; }</style>
</head>
<body>
  <ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>
<div></div>
  <script>var listItems = $('li:gt(0)');
$('div').html( 'Index: ' + $('li').index(listItems) );</script>
</body>
</html>

Demo:

Example:

Returns the index for the element with ID bar in relation to all
  • elements.
    • <!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { font-weight: bold; color: #090; }</style>
</head>
<body>
  <ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>
<div></div>
  <script>$('div').html('Index: ' +  $('#bar').index('li') );</script>
</body>
</html>

    Demo:

    Example:

    Returns the index for the element with ID bar in relation to its siblings.
    <!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { font-weight: bold; color: #090; }</style>
</head>
<body>
  <ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>
<div></div>
  <script>var barIndex = $('#bar').index();
$('div').html( 'Index: ' +  barIndex );</script>
</body>
</html>

    Demo:

    Example:

    Returns -1, as there is no element with ID foobar.
    <!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { font-weight: bold; color: #090; }</style>
</head>
<body>
  <ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>
<div></div>
  <script>var foobar = $("li").index( $('#foobar') );
$('div').html('Index: ' + foobar);</script>
</body>
</html>

    Demo:


get – jQuery API

Returns: Element, ArrayElement, Array .get( [ Number ] index )

Categories: DOM Element Methods, Version 1.0
Description: Retrieve the DOM elements matched by the jQuery object.
  • version added: 1.0
  • .get( [ Number ] index )
  • index A zero-based integer indicating which element to retrieve.

The method grants us access to the DOM nodes underlying each jQuery object. Suppose we had a simple unordered list on the page:

<ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
</ul>

Without a parameter, returns all of the elements:

alert($('li').get());

All of the matched DOM nodes are returned by this call, contained in a standard array:

With an index specified, .get() will retrieve a single element:

($('li').get(0));

Since the index is zero-based, the first list item is returned:

Each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get at the list item instead:

alert($('li')[0]);

However, this syntax lacks some of the additional capabilities of .get(), such as specifying a negative index:

alert($('li').get(-1));

A negative index is counted from the end of the matched set, so this example will return the last item in the list:

Examples:

Example:

Selects all divs in the document and returns the DOM Elements as an Array, then uses the built-in reverse-method to reverse that array.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span { color:red; }</style>
</head>
<body>
  Reversed - <span></span>

  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <script>function disp(divs) {
      var a = [];
      for (var i = 0; i < divs.length; i++) {
        a.push(divs[i].innerHTML);
      }
      $("span").text(a.join(" "));
    }

    disp( $("div").get().reverse() );</script>
</body>
</html>

Demo:

Example:

Gives the tag name of the element clicked on.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span { color:red; }
  div { background:yellow; }</style>
</head>
<body>
  <span>&nbsp;</span>
  <p>In this paragraph is an <span>important</span> section</p>

  <div><input type="text" /></div>
  <script>$("*", document.body).click(function (e) {
      e.stopPropagation();
      var domEl = $(this).get(0);
      $("span:first").text("Clicked on - " + domEl.tagName);
    });</script>
</body>
</html>

Demo:


size – jQuery API

Returns: NumberNumber .size( )

Categories: DOM Element Methods, Version 1.0
Description: Return the number of elements in the jQuery object.
  • version added: 1.0
  • .size( )

The method is functionally equivalent to the property; however, because it does not have the overhead of a function call.

Given a simple unordered list on the page:

<ul>
  <li>foo</li>
  <li>bar</li>
</ul>

Both and identify the number of items:

alert( "Size: " + $("li").size() );
alert( "Size: " + $("li").length );

This results in two alerts:

Examples:

Example:

Count the divs. Click to add more.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { cursor:pointer; min-height: 100px; }
  div { width:50px; height:30px; margin:5px;
        float:left; background:blue; }
  span { color:red; }</style>
</head>
<body>

<span></span>
 <div></div>

  <script>$(document.body)
.click(function() {
  $(this).append( $("<div>") );
  var n = $("div").size();
  $("span").text("There are " + n + " divs. Click to add more.");
})
// trigger the click to start
.click();</script>
</body>
</html>

Demo:


Setup Methods – jQuery API

Setup Methods

  • Object jQuery.noConflict( [ Boolean ] removeAll )

    New in 1.0 !

    Relinquish jQuery's control of the variable.


Offset – jQuery API

Offset

  • jQuery .offsetParent( )

    New in 1.2.6 !

    Get the closest ancestor element that is positioned.

  • jQuery .scrollLeft( [ Number ] value )

    New in 1.2.6 !

    Set the current horizontal position of the scroll bar for each of the set of matched elements.

  • jQuery .scrollTop( [ Number ] value )

    New in 1.2.6 !

    Set the current vertical position of the scroll bar for each of the set of matched elements.

  • Object .position( )

    New in 1.2 !

    Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.


offsetParent – jQuery API

Returns: jQueryjQuery .offsetParent( )

Categories: Offset, Tree Traversal
Description: Get the closest ancestor element that is positioned.
  • version added: 1.2.6
  • .offsetParent( )

Given a jQuery object that represents a set of DOM elements, the method allows us to search through the ancestors of these elements in the DOM tree and construct a new jQuery object wrapped around the closest positioned ancestor. An element is said to be positioned if it has a CSS position attribute of , , or . This information is useful for calculating offsets for performing animations and placing objects on the page.

Consider a page with a basic nested list on it, with a positioned element:

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii" style="position: relative;">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

If we begin at item A, we can find its positioned ancestor:

$('li.item-a').offsetParent().css('background-color', 'red');

This will change the color of list item II, which is positioned.

Examples:

Example:

Find the offsetParent of item "A."
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

    <ul class="level-1">
      <li class="item-i">I</li>
      <li class="item-ii" style="position: relative;">II
        <ul class="level-2">
          <li class="item-a">A</li>
          <li class="item-b">B
            <ul class="level-3">
              <li class="item-1">1</li>
              <li class="item-2">2</li>
              <li class="item-3">3</li>
            </ul>
          </li>
          <li class="item-c">C</li>
        </ul>
      </li>
      <li class="item-iii">III</li>
    </ul>

  <script>$('li.item-a').offsetParent().css('background-color', 'red');</script>
</body>
</html>

Demo:


Properties – jQuery API

Properties

  • String jquery

    New in 1.0 !

    A string containing the jQuery version number.

  • Number length

    New in 1.0 !

    The number of elements in the jQuery object.

  • String selector

    New in 1.3 !

    A selector representing selector originally passed to jQuery().

  • Element context

    New in 1.3 !

    The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document.

  • Number jQuery.fx.interval

    New in 1.4.3 !

    The rate (in milliseconds) at which animations fire.

  • Boolean jQuery.fx.off

    New in 1.3 !

    Globally disable all animations.

  • Map jQuery.browser

    New in 1.0 !

    Contains flags for the useragent, read from navigator.userAgent.

  • String jQuery.browser.version

    New in 1.1.3 !

    The version number of the rendering engine for the user's browser.

  • Object jQuery.support

    New in 1.3 !

    A collection of properties that represent the presence of different browser features or bugs.


Properties of jQuery Object Instances – jQuery API

Properties of jQuery Object Instances

  • String jquery

    New in 1.0 !

    A string containing the jQuery version number.

  • Number length

    New in 1.0 !

    The number of elements in the jQuery object.

  • String selector

    New in 1.3 !

    A selector representing selector originally passed to jQuery().

  • Element context

    New in 1.3 !

    The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document.


length – jQuery API

Returns: NumberNumber length

Categories: Properties of jQuery Object Instances, Version 1.0
Description: The number of elements in the jQuery object.
  • version added: 1.0
  • length

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

Examples:

Example:

Count the divs. Click to add more.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { cursor:pointer; }
  div { width:50px; height:30px; margin:5px; float:left;
        background:green; }
  span { color:red; }</style>
</head>
<body>
  <span></span>
  <div></div>
  <script>$(document.body).click(function () {
      $(document.body).append($("<div>"));
      var n = $("div").length;
      $("span").text("There are " + n + " divs." +
                     "Click to add more.");
    }).trigger('click'); // trigger the click to start</script>
</body>
</html>

Demo:


selector – jQuery API

Returns: StringString selector

Categories: Internals, Properties of jQuery Object Instances, Version 1.3
Description: A selector representing selector originally passed to jQuery().
  • version added: 1.3
  • selector

Should be used in conjunction with context to determine the exact query used.

The method for binding event handlers uses this property to determine how to perform its searches. Plug-ins which perform similar tasks may also find the property useful. This property contains a string representing the matched set of elements, but if DOM traversal methods have been called on the object, the string may not be a valid jQuery selector expression. For this reason, the value of is generally most useful immediately following the original creation of the object. Consequently, the method should only be used in this scenario.

Examples:

Example:

Determine the selector used.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { cursor:pointer; }
  div { width:50px; height:30px; margin:5px; float:left;
        background:green; }
  span { color:red; }</style>
</head>
<body>
  Some selectors:<ul></ul>
  <script>$("ul")
  .append("<li>" + $("ul").selector + "</li>")
  .append("<li>" + $("ul li").selector + "</li>")
  .append("<li>" + $("div#foo ul:not([class])").selector + "</li>");</script>
</body>
</html>

Demo:

Example:

Collecting elements differently
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  Some selectors:<ul></ul>

  <script>$('<div>' + $('ul li.foo').selector + '</div>').appendTo('body');  // "ul li.foo"
   $('<div>' + $('ul').find('li').filter('.foo').selector + '</div>').appendTo('body'); // "ul li.filter(.foo)"</script>
</body>
</html>

Demo:


context – jQuery API

Returns: ElementElement context

Categories: Internals, Properties of jQuery Object Instances, Version 1.3
Description: The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document.
  • version added: 1.3
  • context

The method for binding event handlers uses this property to determine the root element to use for its event delegation needs. Plug-ins which perform similar tasks may also find the property useful.

The value of this property is typically equal to document, as this is the default context for jQuery objects if none is supplied. The context may differ if, for example, the object was created by searching within an or XML document.

Examples:

Example:

Determine the exact context used.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { cursor:pointer; }
  div { width:50px; height:30px; margin:5px; float:left;
        background:green; }
  span { color:red; }</style>
</head>
<body>
  Context:<ul></ul>
  <script>$("ul")
  .append("<li>" + $("ul").context + "</li>")
  .append("<li>" + $("ul", document.body).context.nodeName + "</li>");</script>
</body>
</html>

Demo:


Properties of the Global jQuery Object – jQuery API

Properties of the Global jQuery Object

  • Number jQuery.fx.interval

    New in 1.4.3 !

    The rate (in milliseconds) at which animations fire.

  • Boolean jQuery.fx.off

    New in 1.3 !

    Globally disable all animations.

  • Map jQuery.browser

    New in 1.0 !

    Contains flags for the useragent, read from navigator.userAgent.

  • String jQuery.browser.version

    New in 1.1.3 !

    The version number of the rendering engine for the user's browser.

  • Object jQuery.support

    New in 1.3 !

    A collection of properties that represent the presence of different browser features or bugs.


jQuery.browser – jQuery API

Returns: MapMap jQuery.browser

Categories: Properties of the Global jQuery Object, Utilities, Version 1.0, Version 1.1.3
Description: Contains flags for the useragent, read from navigator.userAgent.
  • version added: 1.0
  • jQuery.browser

The property provides information about the web browser that is accessing the page, as reported by the browser itself. It contains flags for each of the four most prevalent browser classes (Internet Explorer, Mozilla, Webkit, and Opera) as well as version information.

Available flags are:

This property is available immediately. It is therefore safe to use it to determine whether or not to call . The property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery.

Because uses to determine the platform, it is vulnerable to spoofing by the user or misrepresentation by the browser itself. It is always best to avoid browser-specific code entirely where possible. The property is available for detection of support for particular features rather than relying on .

Examples:

Example:

Show the browser info.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:green; font-weight:bolder; margin:3px 0 0 10px; }
  div { color:blue; margin-left:20px; font-size:14px; }
  span { color:red; }</style>
</head>
<body>

<p>Browser info:</p>

  <script>jQuery.each(jQuery.browser, function(i, val) {
      $("<div>" + i + " : <span>" + val + "</span>")
                .appendTo( document.body );
    });</script>
</body>
</html>

Demo:

Example:

Returns true if the current useragent is some version of Microsoft's Internet Explorer.
$.browser.msie;

Example:

Alerts "this is WebKit!" only for WebKit browsers
if ($.browser.webkit) {
    alert( "this is webkit!" );
  }

Example:

Alerts "Do stuff for Firefox 3" only for Firefox 3 browsers.
var ua = $.browser;
  if ( ua.mozilla && ua.version.slice(0,3) == "1.9" ) {
    alert( "Do stuff for firefox 3" );
  }

Example:

Set a CSS property that's specific to a particular browser.
if ( $.browser.msie ) {
    $("#div ul li").css( "display","inline" );
 } else {
    $("#div ul li").css( "display","inline-table" );
 }


jQuery.browser.version – jQuery API

Returns: StringString jQuery.browser.version

Categories: Properties of the Global jQuery Object, Utilities, Version 1.0, Version 1.1.3
Description: The version number of the rendering engine for the user's browser.
  • version added: 1.1.3
  • jQuery.browser.version

Here are some typical results:

Note that IE8 claims to be 7 in Compatibility View.

Examples:

Example:

Returns the version number of the rendering engine used by the user's current browser. For example, FireFox 4 returns 2.0 (the version of the Gecko rendering engine it utilizes).
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:blue; margin:20px; }
  span { color:red; }</style>
</head>
<body>

<p></p>

  <script>$("p").html( "The version number of the rendering engine your browser uses is: <span>" +
                $.browser.version + "</span>" );</script>
</body>
</html>

Demo:

Example:

Alerts the version of IE's rendering engine that is being used:
if ( $.browser.msie ) {
  alert( $.browser.version );
}

Example:

Often you only care about the "major number," the whole number, which you can get by using JavaScript's built-in function:
if ( $.browser.msie ) {
  alert( parseInt($.browser.version, 10) );
}


jQuery.support – jQuery API

Returns: ObjectObject jQuery.support

Categories: Properties of the Global jQuery Object, Utilities, Version 1.3, Version 1.5.1
Description: A collection of properties that represent the presence of different browser features or bugs.
  • version added: 1.3
  • jQuery.support

Rather than using to detect the current user agent and alter the page presentation based on which browser is running, it is a good practice to perform . This means that prior to executing code which relies on a browser feature, we test to ensure that the feature works properly. To make this process simpler, jQuery performs many such tests and makes the results available to us as properties of the object.

The values of all the support properties are determined using feature detection (and do not use any form of browser sniffing).

While jQuery includes a number of properties, developers should feel free to add their own as their needs dictate. Many of the properties are rather low-level, so they are most useful for plugin and jQuery core development, rather than general day-to-day development. Since jQuery requires these tests internally, they must be performed on page load; for that reason this list is kept short and limited to features needed by jQuery itself.

The tests included in are as follows:

Examples:

Example:

Returns the box model for the iframe.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:blue; margin:20px; }
  span { color:red; }</style>
</head>
<body>
  <p>
  </p>
  <script>$("p").html("This frame uses the W3C box model: <span>" +
                jQuery.support.boxModel + "</span>");</script>
</body>
</html>

Demo:

Example:

Returns false if the page is in QuirksMode in Internet Explorer
jQuery.support.boxModel


Selectors – jQuery API

Selectors

  • JQuery("[attribute|="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).

  • JQuery("[attribute~="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

  • JQuery("[attributeFilter1][attributeFilter2][attributeFilterN]")

    New in 1.0 !

    Matches elements that match all of the specified attribute filters.

  • JQuery("[attribute*="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value containing the a given substring.

  • JQuery("[attribute$="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.

  • JQuery("[attribute^="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value beginning exactly with a given string.

  • JQuery("[attribute!="value"]")

    New in 1.0 !

    Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.

  • JQuery("[attribute="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value exactly equal to a certain value.

  • JQuery("[attribute]")

    New in 1.0 !

    Selects elements that have the specified attribute, with any value.

  • JQuery("selector1, selector2, selectorN")

    New in 1.0 !

    Selects the combined results of all the specified selectors.

  • JQuery("*")

    New in 1.0 !

    Selects all elements.

  • JQuery(".class")

    New in 1.0 !

    Selects all elements with the given class.

  • JQuery("element")

    New in 1.0 !

    Selects all elements with the given tag name.

  • JQuery("#id")

    New in 1.0 !

    Selects a single element with the given id attribute.

  • JQuery(":animated")

    New in 1.2 !

    Select all elements that are in the progress of an animation at the time the selector is run.

  • JQuery(":header")

    New in 1.2 !

    Selects all elements that are headers, like h1, h2, h3 and so on.

  • JQuery(":lt(index)")

    New in 1.0 !

    Select all elements at an index less than within the matched set.

  • JQuery(":gt(index)")

    New in 1.0 !

    Select all elements at an index greater than within the matched set.

  • JQuery(":eq(index)")

    New in 1.0 !

    Select the element at index within the matched set.

  • JQuery(":odd")

    New in 1.0 !

    Selects odd elements, zero-indexed. See also .

  • JQuery(":even")

    New in 1.0 !

    Selects even elements, zero-indexed. See also .

  • JQuery(":not(selector)")

    New in 1.0 !

    Selects all elements that do not match the given selector.

  • JQuery(":last")

    New in 1.0 !

    Selects the last matched element.

  • JQuery(":first")

    New in 1.0 !

    Selects the first matched element.

  • JQuery(":only-child")

    New in 1.1.4 !

    Selects all elements that are the only child of their parent.

  • JQuery(":last-child")

    New in 1.1.4 !

    Selects all elements that are the last child of their parent.

  • JQuery(":first-child")

    New in 1.1.4 !

    Selects all elements that are the first child of their parent.

  • JQuery(":nth-child(index/even/odd/equation)")

    New in 1.1.4 !

    Selects all elements that are the nth-child of their parent.

  • JQuery(":parent")

    New in 1.0 !

    Select all elements that are the parent of another element, including text nodes.

  • JQuery(":has(selector)")

    New in 1.1.4 !

    Selects elements which contain at least one element that matches the specified selector.

  • JQuery(":empty")

    New in 1.0 !

    Select all elements that have no children (including text nodes).

  • JQuery(":contains(text)")

    New in 1.1.4 !

    Select all elements that contain the specified text.

  • JQuery(":selected")

    New in 1.0 !

    Selects all elements that are selected.

  • JQuery(":checked")

    New in 1.0 !

    Matches all elements that are checked.

  • JQuery(":disabled")

    New in 1.0 !

    Selects all elements that are disabled.

  • JQuery(":enabled")

    New in 1.0 !

    Selects all elements that are enabled.

  • JQuery(":file")

    New in 1.0 !

    Selects all elements of type file.

  • JQuery(":button")

    New in 1.0 !

    Selects all button elements and elements of type button.

  • JQuery(":reset")

    New in 1.0 !

    Selects all elements of type reset.

  • JQuery(":image")

    New in 1.0 !

    Selects all elements of type image.

  • JQuery(":submit")

    New in 1.0 !

    Selects all elements of type submit.

  • JQuery(":checkbox")

    New in 1.0 !

    Selects all elements of type checkbox.

  • JQuery(":radio")

    New in 1.0 !

    Selects all elements of type radio.

  • JQuery(":password")

    New in 1.0 !

    Selects all elements of type password.

  • JQuery(":text")

    New in 1.0 !

    Selects all elements of type text.

  • JQuery(":input")

    New in 1.0 !

    Selects all input, textarea, select and button elements.

  • JQuery("prev ~ siblings")

    New in 1.0 !

    Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.

  • JQuery("prev + next")

    New in 1.0 !

    Selects all next elements matching "next" that are immediately preceded by a sibling "prev".

  • child")" rel="bookmark">JQuery("parent > child")

    New in 1.0 !

    Selects all direct child elements specified by "child" of elements specified by "parent".

  • JQuery("ancestor descendant")

    New in 1.0 !

    Selects all elements that are descendants of a given ancestor.

  • JQuery(":visible")

    New in 1.0 !

    Selects all elements that are visible.

  • JQuery(":hidden")

    New in 1.0 !

    Selects all elements that are hidden.


Attribute – jQuery API

Attribute

  • JQuery("[attribute|="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).

  • JQuery("[attribute~="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

  • JQuery("[attributeFilter1][attributeFilter2][attributeFilterN]")

    New in 1.0 !

    Matches elements that match all of the specified attribute filters.

  • JQuery("[attribute*="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value containing the a given substring.

  • JQuery("[attribute$="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.

  • JQuery("[attribute^="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value beginning exactly with a given string.

  • JQuery("[attribute!="value"]")

    New in 1.0 !

    Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.

  • JQuery("[attribute="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value exactly equal to a certain value.

  • JQuery("[attribute]")

    New in 1.0 !

    Selects elements that have the specified attribute, with any value.


attributeContainsPrefix – jQuery API

Returns: JQuery("[attribute|="value"]")

Categories: Attribute, Version 1.0
Description: Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).
  • version added: 1.0
  • JQuery("[attribute|="value"]")
  • attribute An attribute name.
  • value An attribute value. Quotes are mandatory.

This selector was introduced into the CSS specification to handle language attributes.

Examples:

Example:

Finds all links with an hreflang attribute that is english.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

  <a href="example.html" hreflang="en">Some text</a>

  <a href="example.html" hreflang="en-UK">Some other text</a>

  <script>$('a[hreflang|="en"]').css('border','3px dotted green');</script>
</body>
</html>

Demo:


attributeContainsWord – jQuery API

Returns: JQuery("[attribute~="value"]")

Categories: Attribute, Version 1.0
Description: Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.
  • version added: 1.0
  • JQuery("[attribute~="value"]")
  • attribute An attribute name.
  • value An attribute value. Quotes are mandatory.

This selector matches the test string against each word in the attribute value, where a "word" is defined as a string delimited by whitespace. The selector matches if the test string is exactly equal to any of the words.

Examples:

Example:

Finds all inputs with a name attribute that contains the word 'man' and sets the value with some text.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <input name="man-news" />

  <input name="milk man" />
  <input name="letterman2" />
  <input name="newmilk" />
  <script>$('input[name~="man"]').val('mr. man is in it!');</script>
</body>
</html>

Demo:


attributeMultiple – jQuery API

Returns: JQuery("[attributeFilter1][attributeFilter2][attributeFilterN]")

Categories: Attribute, Version 1.0
Description: Matches elements that match all of the specified attribute filters.
  • version added: 1.0
  • JQuery("[attributeFilter1][attributeFilter2][attributeFilterN]")
  • attributeFilter1 An attribute filter.
  • attributeFilter2 Another attribute filter, reducing the selection even more
  • attributeFilterN As many more attribute filters as necessary

Examples:

Example:

Finds all inputs that have an id attribute and whose name attribute ends with man and sets the value.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <input id="man-news" name="man-news" />

  <input name="milkman" />
  <input id="letterman" name="new-letterman" />
  <input name="newmilk" />
  <script>$('input[id][name$="man"]').val('only this one');</script>
</body>
</html>

Demo:


attributeContains – jQuery API

Returns: JQuery("[attribute*="value"]")

Categories: Attribute, Version 1.0
Description: Selects elements that have the specified attribute with a value containing the a given substring.
  • version added: 1.0
  • JQuery("[attribute*="value"]")
  • attribute An attribute name.
  • value An attribute value. Quotes are mandatory.

This is the most generous of the jQuery attribute selectors that match against a value. It will select an element if the selector's string appears anywhere within the element's attribute value. Compare this selector with the Attribute Contains Word selector (e.g. [attr~="word"]), which is more appropriate in many cases.

Examples:

Example:

Finds all inputs with a name attribute that contains 'man' and sets the value with some text.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <input name="man-news" />

  <input name="milkman" />
  <input name="letterman2" />
  <input name="newmilk" />
  <script>$('input[name*="man"]').val('has man in it!');</script>
</body>
</html>

Demo:


attributeEndsWith – jQuery API

Returns: JQuery("[attribute$="value"]")

Categories: Attribute, Version 1.0
Description: Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.
  • version added: 1.0
  • JQuery("[attribute$="value"]")
  • attribute An attribute name.
  • value An attribute value. Quotes are mandatory.

Examples:

Example:

Finds all inputs with an attribute name that ends with 'letter' and puts text in them.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <input name="newsletter" />

  <input name="milkman" />
  <input name="jobletter" />
  <script>$('input[name$="letter"]').val('a letter');</script>
</body>
</html>

Demo:


attributeStartsWith – jQuery API

Returns: JQuery("[attribute^="value"]")

Categories: Attribute, Version 1.0
Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.
  • version added: 1.0
  • JQuery("[attribute^="value"]")
  • attribute An attribute name.
  • value An attribute value. Quotes are mandatory.

This selector can be useful for identifying elements in pages produced by server-side frameworks that produce HTML with systematic element IDs. However it will be slower than using a class selector so leverage classes, if you can, to group like elements.

Examples:

Example:

Finds all inputs with an attribute name that starts with 'news' and puts text in them.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <input name="newsletter" />

  <input name="milkman" />
  <input name="newsboy" />
  <script>$('input[name^="news"]').val('news here!');</script>
</body>
</html>

Demo:


attributeNotEqual – jQuery API

Returns: JQuery("[attribute!="value"]")

Categories: Attribute, Version 1.0
Description: Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.
  • version added: 1.0
  • JQuery("[attribute!="value"]")
  • attribute An attribute name.
  • value An attribute value. Quotes are mandatory.

This selector is equivalent to .

Examples:

Example:

Finds all inputs that don't have the name 'newsletter' and appends text to the span next to it.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <div>

    <input type="radio" name="newsletter" value="Hot Fuzz" />
    <span>name is newsletter</span>

  </div>
  <div>
    <input type="radio" value="Cold Fusion" />
    <span>no name</span>

  </div>
  <div>
    <input type="radio" name="accept" value="Evil Plans" />

    <span>name is accept</span>
  </div>
  <script>$('input[name!="newsletter"]').next().append('<b>; not newsletter</b>');</script>
</body>
</html>

Demo:


attributeEquals – jQuery API

Returns: JQuery("[attribute="value"]")

Categories: Attribute, Version 1.0
Description: Selects elements that have the specified attribute with a value exactly equal to a certain value.
  • version added: 1.0
  • JQuery("[attribute="value"]")
  • attribute An attribute name.
  • value An attribute value.

Examples:

Example:

Finds all inputs with name "newsletter" and changes the text of the span next to it.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <div>
    <label>
      <input type="radio" name="newsletter" value="Hot Fuzz" />
      <span>name?</span>
    </label>
  </div>
  <div>
    <label>
      <input type="radio" name="newsletter" value="Cold Fusion" />
      <span>value?</span>
    </label>
  </div>
  <div>
    <label>
      <input type="radio" name="newsletter" value="Evil Plans" />
      <span>value?</span>
    </label>
  </div>
  <script>$('input[value="Hot Fuzz"]').next().text(" Hot Fuzz");</script>
</body>
</html>

Demo:


attributeHas – jQuery API

Returns: JQuery("[attribute]")

Categories: Attribute, Version 1.0
Description: Selects elements that have the specified attribute, with any value.
  • version added: 1.0
  • JQuery("[attribute]")
  • attribute An attribute name.

Examples:

Example:

Bind a single click that adds the div id to its text.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <div>no id</div>
  <div id="hey">with id</div>

  <div id="there">has an id</div>
  <div>nope</div>
  <script>$('div[id]').one('click', function(){
      var idString = $(this).text() + ' = ' + $(this).attr('id');
      $(this).text(idString);
    });</script>
</body>
</html>

Demo:


Basic – jQuery API

Basic

  • JQuery("selector1, selector2, selectorN")

    New in 1.0 !

    Selects the combined results of all the specified selectors.

  • JQuery("*")

    New in 1.0 !

    Selects all elements.

  • JQuery(".class")

    New in 1.0 !

    Selects all elements with the given class.

  • JQuery("element")

    New in 1.0 !

    Selects all elements with the given tag name.

  • JQuery("#id")

    New in 1.0 !

    Selects a single element with the given id attribute.


multiple – jQuery API

Returns: JQuery("selector1, selector2, selectorN")

Categories: Basic, Version 1.0
Description: Selects the combined results of all the specified selectors.
  • version added: 1.0
  • JQuery("selector1, selector2, selectorN")
  • selector1 Any valid selector.
  • selector2 Another valid selector.
  • selectorN As many more valid selectors as you like.

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order. An alternative to this combinator is the . method.

Examples:

Example:

Finds the elements that match any of these three selectors.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div,span,p {
    width: 126px;
    height: 60px;
    float:left;
    padding: 3px;
    margin: 2px;
    background-color: #EEEEEE;
    font-size:14px;
  }</style>
</head>
<body>
  <div>div</div>

  <p class="myClass">p class="myClass"</p>
  <p class="notMyClass">p class="notMyClass"</p>
  <span>span</span>
  <script>$("div,span,p.myClass").css("border","3px solid red");</script>
</body>
</html>

Demo:

Example:

Show the order in the jQuery object.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>b { color:red; font-size:16px; display:block; clear:left; }
  div,span,p { width: 40px; height: 40px; float:left;
               margin: 10px; background-color: blue;
               padding:3px; color:white;
             }</style>
</head>
<body>
  <span>span</span>

  <p>p</p>
  <p>p</p>
  <div>div</div>
  <span>span</span>

  <p>p</p>
  <div>div</div>
  <b></b>
  <script>var list = $("div,p,span").map(function () {
      return this.tagName;
    }).get().join(", ");
    $("b").append(document.createTextNode(list));</script>
</body>
</html>

Demo:


all – jQuery API

Returns: JQuery("*")

Categories: Basic, Version 1.0
Description: Selects all elements.
  • version added: 1.0
  • JQuery("*")

Caution: The all, or universal, selector is extremely slow, except when used by itself.

Examples:

Example:

Finds every element (including head, body, etc) in the document.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>h3 { margin: 0; }
  div,span,p {
    width: 80px;
    height: 40px;
    float:left;
    padding: 10px;
    margin: 10px;
    background-color: #EEEEEE;
  }</style>
</head>
<body>
  <div>DIV</div>

  <span>SPAN</span>
  <p>P <button>Button</button></p>
  <script>var elementCount = $("*").css("border","3px solid red").length;
$("body").prepend("<h3>" + elementCount + " elements found</h3>");</script>
</body>
</html>

Demo:

Example:

A common way to select all elements is to find within document.body so elements like head, script, etc are left out.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>h3 { margin: 0; }
  div,span,p {
    width: 80px;
    height: 40px;
    float:left;
    padding: 10px;
    margin: 10px;
    background-color: #EEEEEE;
  }
  #test {
    width: auto; height: auto; background-color: transparent;
  }</style>
</head>
<body>
  <div id="test">
  <div>DIV</div>
  <span>SPAN</span>
  <p>P <button>Button</button></p>
</div>
  <script>var elementCount = $("#test").find("*").css("border","3px solid red").length;
$("body").prepend("<h3>" + elementCount + " elements found</h3>");</script>
</body>
</html>

Demo:


class – jQuery API

Returns: JQuery(".class")

Categories: Basic, Version 1.0
Description: Selects all elements with the given class.
  • version added: 1.0
  • JQuery(".class")
  • class A class to search for. An element can have multiple classes; only one of them must match.

For class selectors, jQuery uses JavaScript's native function if the browser supports it.

Examples:

Example:

Finds the element with the class "myClass".
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div,span {
    width: 100px;
    height: 40px;
    float:left;
    padding: 10px;
    margin: 10px;
    background-color: #EEEEEE;
  }</style>
</head>
<body>
  <div class="notMe">div class="notMe"</div>

  <div class="myClass">div class="myClass"</div>
  <span class="myClass">span class="myClass"</span>
  <script>$(".myClass").css("border","3px solid red");</script>
</body>
</html>

Demo:

Example:

Finds the element with both "myclass" and "otherclass" classes.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div,span {
    width: 100px;
    height: 40px;
    float:left;
    padding: 10px;
    margin: 10px;
    background-color: #EEEEEE;
  }</style>
</head>
<body>
  <div class="myclass">div class="notMe"</div>

  <div class="myclass otherclass">div class="myClass"</div>
  <span class="myclass otherclass">span class="myClass"</span>
  <script>$(".myclass.otherclass").css("border","13px solid red");</script>
</body>
</html>

Demo:


element – jQuery API

Returns: JQuery("element")

Categories: Basic, Version 1.0
Description: Selects all elements with the given tag name.
  • version added: 1.0
  • JQuery("element")
  • element An element to search for. Refers to the tagName of DOM nodes.

JavaScript's function is called to return the appropriate elements when this expression is used.

Examples:

Example:

Finds every DIV element.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div,span {
    width: 60px;
    height: 60px;
    float:left;
    padding: 10px;
    margin: 10px;
    background-color: #EEEEEE;
  }</style>
</head>
<body>
  <div>DIV1</div>

  <div>DIV2</div>
  <span>SPAN</span>
  <script>$("div").css("border","9px solid red");</script>
</body>
</html>

Demo:


id – jQuery API

Returns: JQuery("#id")

Categories: Basic, Version 1.0
Description: Selects a single element with the given id attribute.
  • version added: 1.0
  • JQuery("#id")
  • id An ID to search for, specified via the id attribute of an element.

For id selectors, jQuery uses the JavaScript function , which is extremely efficient. When another selector is attached to the id selector, such as , jQuery performs an additional check before identifying the element as a match.

Each value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.

If the id contains characters like periods or colons you have to .

Examples:

Example:

Finds the element with the id "myDiv".
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div {
    width: 90px;
    height: 90px;
    float:left;
    padding: 5px;
    margin: 5px;
    background-color: #EEEEEE;
  }</style>
</head>
<body>
  <div id="notMe"><p>id="notMe"</p></div>

  <div id="myDiv">id="myDiv"</div>
  <script>$("#myDiv").css("border","3px solid red");</script>
</body>
</html>

Demo:

Example:

Finds the element with the id "myID.entry[1]". See how certain characters must be escaped with backslashes.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div {
    width: 300px;
    float:left;
    padding: 2px;
    margin: 3px;
    background-color: #EEEEEE;
  }</style>
</head>
<body>
  <div id="myID.entry[0]">id="myID.entry[0]"</div>

  <div id="myID.entry[1]">id="myID.entry[1]"</div>
  <div id="myID.entry[2]">id="myID.entry[2]"</div>
  <script>$("#myID\\.entry\\[1\\]").css("border","3px solid red");</script>
</body>
</html>

Demo:


Basic Filter – jQuery API

Basic Filter

  • JQuery(":animated")

    New in 1.2 !

    Select all elements that are in the progress of an animation at the time the selector is run.

  • JQuery(":header")

    New in 1.2 !

    Selects all elements that are headers, like h1, h2, h3 and so on.

  • JQuery(":lt(index)")

    New in 1.0 !

    Select all elements at an index less than within the matched set.

  • JQuery(":gt(index)")

    New in 1.0 !

    Select all elements at an index greater than within the matched set.

  • JQuery(":eq(index)")

    New in 1.0 !

    Select the element at index within the matched set.

  • JQuery(":odd")

    New in 1.0 !

    Selects odd elements, zero-indexed. See also .

  • JQuery(":even")

    New in 1.0 !

    Selects even elements, zero-indexed. See also .

  • JQuery(":not(selector)")

    New in 1.0 !

    Selects all elements that do not match the given selector.

  • JQuery(":last")

    New in 1.0 !

    Selects the last matched element.

  • JQuery(":first")

    New in 1.0 !

    Selects the first matched element.


animated – jQuery API

Returns: JQuery(":animated")

Categories: Basic Filter, Version 1.2
Description: Select all elements that are in the progress of an animation at the time the selector is run.
  • version added: 1.2
  • JQuery(":animated")

Examples:

Example:

Change the color of any div that is animated.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { background:yellow; border:1px solid #AAA; width:80px; height:80px; margin:0 5px; float:left; }
  div.colored { background:green; }</style>
</head>
<body>
  <button id="run">Run</button>

  <div></div>
  <div id="mover"></div>
  <div></div>
  <script>$("#run").click(function(){
      $("div:animated").toggleClass("colored");
    });
    function animateIt() {
      $("#mover").slideToggle("slow", animateIt);
    }
    animateIt();</script>
</body>
</html>

Demo:


header – jQuery API

Returns: JQuery(":header")

Categories: Basic Filter, Version 1.2
Description: Selects all elements that are headers, like h1, h2, h3 and so on.
  • version added: 1.2
  • JQuery(":header")

Examples:

Example:

Adds a background and text color to all the headers on the page.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { font-size: 10px; font-family: Arial; }
  h1, h2 { margin: 3px 0; }</style>
</head>
<body>
  <h1>Header 1</h1>

  <p>Contents 1</p>
  <h2>Header 2</h2>
  <p>Contents 2</p>
  <script>$(":header").css({ background:'#CCC', color:'blue' });</script>
</body>
</html>

Demo:


lt – jQuery API

Returns: JQuery(":lt(index)")

Categories: Basic Filter, Version 1.0
Description: Select all elements at an index less than within the matched set.
  • version added: 1.0
  • JQuery(":lt(index)")
  • index Zero-based index.

The index-related selectors (including this "less than" selector) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set. For example, if elements are first selected with a class selector () and four elements are returned, these elements are given indices 0 through 3 for the purposes of these selectors.

Note that since JavaScript arrays use , these selectors reflect that fact. This is why selects the first element in the document with the class , rather than selecting no elements. In contrast, uses to conform to the CSS specification.

Examples:

Example:

Finds TDs less than the one with the 4th index (TD#4).
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <table border="1">

  <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
  <tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>

  <tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</table>
  <script>$("td:lt(4)").css("color", "red");</script>
</body>
</html>

Demo:


gt – jQuery API

Returns: JQuery(":gt(index)")

Categories: Basic Filter, Version 1.0
Description: Select all elements at an index greater than within the matched set.
  • version added: 1.0
  • JQuery(":gt(index)")
  • index Zero-based index.

The index-related selector expressions (including this "greater than" selector) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set. For example, if elements are first selected with a class selector () and four elements are returned, these elements are given indices 0 through 3 for the purposes of these selectors.

Note that since JavaScript arrays use , these selectors reflect that fact. This is why selects elements after the second element in the document with the class , rather than after the first. In contrast, uses to conform to the CSS specification.

Examples:

Example:

Finds TD #5 and higher. Reminder: the indexing starts at 0.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <table border="1">

    <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
    <tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>

    <tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
  </table>
  <script>$("td:gt(4)").css("text-decoration", "line-through");</script>
</body>
</html>

Demo:


eq – jQuery API

  • eq ( [ Number ] index )

    • 1.0eq ( [ Number ] index )

  • eq ( [ Integer ] index )

    • 1.1.2eq ( [ Integer ] index )
    • 1.4eq ( [ Integer ] -index )

Returns: JQuery(":eq(index)")

Categories: Basic Filter, Version 1.0
Description: Select the element at index within the matched set.
  • version added: 1.0
  • JQuery(":eq(index)")
  • index Zero-based index of the element to match.

The index-related selectors (, , , , ) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set. For example, if elements are first selected with a class selector () and four elements are returned, these elements are given indices through for the purposes of these selectors.

Note that since JavaScript arrays use , these selectors reflect that fact. This is why selects the second element in the document with the class myclass, rather than the first. In contrast, uses to conform to the CSS specification.

Unlike the method, the selector does accept a negative value for . For example, while selects the last element, selects nothing.

Examples:

Example:

Finds the third td.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <table border="1">
  <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
  <tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
  <tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</table>
  <script>$("td:eq(2)").css("color", "red");</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .eq( [ Integer ] -index )

Categories: Filtering, Version 1.1.2
Description: Reduce the set of matched elements to the one at the specified index.
  • version added: 1.1.2
  • .eq( [ Integer ] index )
  • index An integer indicating the 0-based position of the element.
  • version added: 1.4
  • .eq( [ Integer ] -index )
  • -index An integer indicating the position of the element, counting backwards from the last element in the set.

Given a jQuery object that represents a set of DOM elements, the method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.

Consider a page with a simple list on it:

  <ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
    <li>list item 4</li>
    <li>list item 5</li>
  </ul>

We can apply this method to the set of list items:

  $('li').eq(2).css('background-color', 'red');

The result of this call is a red background for item 3. Note that the supplied index is zero-based, and refers to the position of the element within the jQuery object, not within the DOM tree.

Providing a negative number indicates a position starting from the end of the set, rather than the beginning. For example:

  $('li').eq(-2).css('background-color', 'red');

This time list item 4 is turned red, since it is two from the end of the set.

If an element cannot be found at the specified zero-based index, the method constructs a new jQuery object with an empty set and a property of 0.

  $('li').eq(5).css('background-color', 'red');

Here, none of the list items is turned red, since indicates the sixth of five list items.

Examples:

Example:

Turn the div with index 2 blue by adding an appropriate class.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:60px; height:60px; margin:10px; float:left;
        border:2px solid blue; }
  .blue { background:blue; }</style>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>

  <div></div>
  <div></div>
  <div></div>
  <script>$("body").find("div").eq(2).addClass("blue");</script>
</body>
</html>

Demo:


odd – jQuery API

Returns: JQuery(":odd")

Categories: Basic Filter, Version 1.0
Description: Selects odd elements, zero-indexed. See also .
  • version added: 1.0
  • JQuery(":odd")

In particular, note that the means that, counter-intuitively, selects the second element, fourth element, and so on within the matched set.

Examples:

Example:

Finds odd table rows, matching the second, fourth and so on (index 1, 3, 5 etc.).
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>table {
    background:#f3f7f5;
  }</style>
</head>
<body>
  <table border="1">
    <tr><td>Row with Index #0</td></tr>
    <tr><td>Row with Index #1</td></tr>

    <tr><td>Row with Index #2</td></tr>
    <tr><td>Row with Index #3</td></tr>
  </table>
  <script>$("tr:odd").css("background-color", "#bbbbff");</script>
</body>
</html>

Demo:


even – jQuery API

Returns: JQuery(":even")

Categories: Basic Filter, Version 1.0
Description: Selects even elements, zero-indexed. See also .
  • version added: 1.0
  • JQuery(":even")

In particular, note that the means that, counter-intuitively, selects the first element, third element, and so on within the matched set.

Examples:

Example:

Finds even table rows, matching the first, third and so on (index 0, 2, 4 etc.).
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>table {
    background:#eeeeee;
  }</style>
</head>
<body>
  <table border="1">
    <tr><td>Row with Index #0</td></tr>
    <tr><td>Row with Index #1</td></tr>

    <tr><td>Row with Index #2</td></tr>
    <tr><td>Row with Index #3</td></tr>
  </table>
  <script>$("tr:even").css("background-color", "#bbbbff");</script>
</body>
</html>

Demo:


not – jQuery API

  • not ( [ Selector ] selector )

    • 1.0not ( [ Selector ] selector )

  • not ( [ Selector ] selector )

    • 1.0not ( [ Selector ] selector )
    • 1.0not ( [ Elements ] elements )
    • 1.4not ( [ Function ] function(index) )

Returns: JQuery(":not(selector)")

Categories: Basic Filter, Version 1.0
Description: Selects all elements that do not match the given selector.
  • version added: 1.0
  • JQuery(":not(selector)")
  • selector A selector with which to filter by.

All selectors are accepted inside , for example: and .

Additional Notes

The method will end up providing you with more readable selections than pushing complex selectors or variables into a selector filter. In most cases, it is a better choice.

Examples:

Example:

Finds all inputs that are not checked and highlights the next sibling span. Notice there is no change when clicking the checkboxes since no click events have been linked.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <div>
  <input type="checkbox" name="a" />
  <span>Mary</span>
</div>

<div>
  <input type="checkbox" name="b" />
  <span>lcm</span>

</div>
<div>
  <input type="checkbox" name="c" checked="checked" />

  <span>Peter</span>
</div>
  <script>$("input:not(:checked) + span").css("background-color", "yellow");
  $("input").attr("disabled", "disabled");</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .not( [ Function ] function(index) )

Categories: Filtering, Version 1.0, Version 1.4
Description: Remove elements from the set of matched elements.
  • version added: 1.0
  • .not( [ Selector ] selector )
  • selector A string containing a selector expression to match elements against.
  • version added: 1.0
  • .not( [ Elements ] elements )
  • elements One or more DOM elements to remove from the matched set.
  • version added: 1.4
  • .not( [ Function ] function(index) )
  • function(index) A function used as a test for each element in the set. is the current DOM element.

Given a jQuery object that represents a set of DOM elements, the method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; the elements that don't match the selector will be included in the result.

Consider a page with a simple list on it:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

We can apply this method to the set of list items:

$('li').not(':even').css('background-color', 'red');

The result of this call is a red background for items 2 and 4, as they do not match the selector (recall that :even and :odd use 0-based indexing).

Removing Specific Elements

The second version of the method allows us to remove elements from the matched set, assuming we have found those elements previously by some other means. For example, suppose our list had an id applied to one of its items:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li id="notli">list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

We can fetch the third list item using the native JavaScript function, then remove it from a jQuery object:

$('li').not(document.getElementById('notli'))
  .css('background-color', 'red');

This statement changes the color of items 1, 2, 4, and 5. We could have accomplished the same thing with a simpler jQuery expression, but this technique can be useful when, for example, other libraries provide references to plain DOM nodes.

As of jQuery 1.4, the method can take a function as its argument in the same way that does. Elements for which the function returns are excluded from the filtered set; all other elements are included.

Examples:

Example:

Adds a border to divs that are not green or blue.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:50px; height:50px; margin:10px; float:left;
        background:yellow; border:2px solid white; }
  .green { background:#8f8; }
  .gray { background:#ccc; }
  #blueone { background:#99f; }</style>
</head>
<body>
  <div></div>
  <div id="blueone"></div>
  <div></div>
  <div class="green"></div>

  <div class="green"></div>
  <div class="gray"></div>
  <div></div>
  <script>$("div").not(".green, #blueone")
            .css("border-color", "red");</script>
</body>
</html>

Demo:

Example:

Removes the element with the ID "selected" from the set of all paragraphs.
$("p").not( $("#selected")[0] )

Example:

Removes the element with the ID "selected" from the set of all paragraphs.
$("p").not("#selected")

Example:

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


last – jQuery API

  • last ( )

    • 1.0last ( )

  • last ( )

    • 1.4last ( )

Returns: JQuery(":last")

Categories: Basic Filter, Version 1.0
Description: Selects the last matched element.
  • version added: 1.0
  • JQuery(":last")

Note that selects a single element by filtering the current jQuery collection and matching the last element within it.

Examples:

Example:

Finds the last table row.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <table>

    <tr><td>First Row</td></tr>
    <tr><td>Middle Row</td></tr>
    <tr><td>Last Row</td></tr>

  </table>
  <script>$("tr:last").css({backgroundColor: 'yellow', fontWeight: 'bolder'});</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .last( )

Categories: Filtering, Version 1.4
Description: Reduce the set of matched elements to the final one in the set.
  • version added: 1.4
  • .last( )

Given a jQuery object that represents a set of DOM elements, the method constructs a new jQuery object from the last matching element.

Consider a page with a simple list on it:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

We can apply this method to the set of list items:

$('li').last().css('background-color', 'red');

The result of this call is a red background for the final item.

Examples:

Example:

Highlight the last span in a paragraph.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>.highlight{background-color: yellow}</style>
</head>
<body>
  <p><span>Look:</span> <span>This is some text in a paragraph.</span> <span>This is a note about it.</span></p>
  <script>$("p span").last().addClass('highlight');</script>
</body>
</html>

Demo:


first – jQuery API

  • first ( )

    • 1.0first ( )

  • first ( )

    • 1.4first ( )

Returns: JQuery(":first")

Categories: Basic Filter, Version 1.0
Description: Selects the first matched element.
  • version added: 1.0
  • JQuery(":first")

The pseudo-class is equivalent to . It could also be written as . While this matches only a single element, can match more than one: One for each parent.

Examples:

Example:

Finds the first table row.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>td { color:blue; font-weight:bold; }</style>
</head>
<body>
  <table>
    <tr><td>Row 1</td></tr>
    <tr><td>Row 2</td></tr>

    <tr><td>Row 3</td></tr>
  </table>
  <script>$("tr:first").css("font-style", "italic");</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .first( )

Categories: Filtering, Version 1.4
Description: Reduce the set of matched elements to the first in the set.
  • version added: 1.4
  • .first( )

Given a jQuery object that represents a set of DOM elements, the method constructs a new jQuery object from the first matching element.

Consider a page with a simple list on it:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

We can apply this method to the set of list items:

$('li').first().css('background-color', 'red');

The result of this call is a red background for the first item.

Examples:

Example:

Highlight the first span in a paragraph.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>.highlight{background-color: yellow}</style>
</head>
<body>
  <p><span>Look:</span> <span>This is some text in a paragraph.</span> <span>This is a note about it.</span></p>
  <script>$("p span").first().addClass('highlight');</script>
</body>
</html>

Demo:


Child Filter – jQuery API

Child Filter

  • JQuery(":only-child")

    New in 1.1.4 !

    Selects all elements that are the only child of their parent.

  • JQuery(":last-child")

    New in 1.1.4 !

    Selects all elements that are the last child of their parent.

  • JQuery(":first-child")

    New in 1.1.4 !

    Selects all elements that are the first child of their parent.

  • JQuery(":nth-child(index/even/odd/equation)")

    New in 1.1.4 !

    Selects all elements that are the nth-child of their parent.


only-child – jQuery API

Returns: JQuery(":only-child")

Categories: Child Filter, Version 1.1.4
Description: Selects all elements that are the only child of their parent.
  • version added: 1.1.4
  • JQuery(":only-child")

If the parent has other child elements, nothing is matched.

Examples:

Example:

Finds the button with no siblings in each matched div and modifies look.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:100px; height:80px; margin:5px; float:left; background:#b9e }</style>
</head>
<body>
  <div>
    <button>Sibling!</button>
    <button>Sibling!</button>
  </div>

  <div>
    <button>Sibling!</button>
  </div>
  <div>
    None
  </div>

  <div>
    <button>Sibling!</button>
    <button>Sibling!</button>
    <button>Sibling!</button>

  </div>
  <div>
    <button>Sibling!</button>
  </div>
  <script>$("div button:only-child").text("Alone").css("border", "2px blue solid");</script>
</body>
</html>

Demo:


last-child – jQuery API

Returns: JQuery(":last-child")

Categories: Child Filter, Version 1.1.4
Description: Selects all elements that are the last child of their parent.
  • version added: 1.1.4
  • JQuery(":last-child")

While matches only a single element, can match more than one: one for each parent.

Examples:

Example:

Finds the last span in each matched div and adds some css plus a hover state.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span.solast { text-decoration:line-through; }</style>
</head>
<body>
  <div>
    <span>John,</span>
    <span>Karl,</span>
    <span>Brandon,</span>

    <span>Sam</span>
  </div>
  <div>
    <span>Glen,</span>
    <span>Tane,</span>

    <span>Ralph,</span>
    <span>David</span>
  </div>
  <script>$("div span:last-child")
        .css({color:"red", fontSize:"80%"})
        .hover(function () {
              $(this).addClass("solast");
            }, function () {
              $(this).removeClass("solast");
            });</script>
</body>
</html>

Demo:


first-child – jQuery API

Returns: JQuery(":first-child")

Categories: Child Filter, Version 1.1.4
Description: Selects all elements that are the first child of their parent.
  • version added: 1.1.4
  • JQuery(":first-child")

While matches only a single element, the selector can match more than one: one for each parent. This is equivalent to .

Examples:

Example:

Finds the first span in each matched div to underline and add a hover state.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span { color:#008; }
  span.sogreen { color:green; font-weight: bolder; }</style>
</head>
<body>
  <div>
    <span>John,</span>
    <span>Karl,</span>
    <span>Brandon</span>

  </div>
  <div>
    <span>Glen,</span>
    <span>Tane,</span>
    <span>Ralph</span>

  </div>
  <script>$("div span:first-child")
        .css("text-decoration", "underline")
        .hover(function () {
              $(this).addClass("sogreen");
            }, function () {
              $(this).removeClass("sogreen");
            });</script>
</body>
</html>

Demo:


nth-child – jQuery API

Returns: JQuery(":nth-child(index/even/odd/equation)")

Categories: Child Filter, Version 1.1.4
Description: Selects all elements that are the nth-child of their parent.
  • version added: 1.1.4
  • JQuery(":nth-child(index/even/odd/equation)")
  • index The index of each child to match, starting with , the string or , or an equation ( eg. , )

Because jQuery's implementation of is strictly derived from the CSS specification, the value of is "1-indexed", meaning that the counting starts at 1. For all other selector expressions, however, jQuery follows JavaScript's "0-indexed" counting. Therefore, given a single containing two s, selects the first while selects the second.

The pseudo-class is easily confused with , even though the two can result in dramatically different matched elements. With , all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the (n+1)th one (n is 0-based) is selected.

Further discussion of this unusual usage can be found in the .

Examples:

Example:

Finds the second li in each matched ul and notes it.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { float:left; }
  span { color:blue; }</style>
</head>
<body>
  <div><ul>
    <li>John</li>
    <li>Karl</li>
    <li>Brandon</li>

  </ul></div>
  <div><ul>
    <li>Sam</li>
  </ul></div>

  <div><ul>
    <li>Glen</li>
    <li>Tane</li>
    <li>Ralph</li>

    <li>David</li>
  </ul></div>
  <script>$("ul li:nth-child(2)").append("<span> - 2nd!</span>");</script>
</body>
</html>

Demo:

Example:

This is a playground to see how the selector works with different strings. Notice that this is different from the :even and :odd which have no regard for parent and just filter the list of elements to every other one. The :nth-child, however, counts the index of the child to its particular parent. In any case, it's easier to see than explain so...
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>button { display:block; font-size:12px; width:100px; }
  div { float:left; margin:10px; font-size:10px;
        border:1px solid black; }
  span { color:blue; font-size:18px; }
  #inner { color:red; }
  td { width:50px; text-align:center; }</style>
</head>
<body>
  <div>
    <button>:nth-child(even)</button>
    <button>:nth-child(odd)</button>
    <button>:nth-child(3n)</button>

    <button>:nth-child(2)</button>
  </div>
  <div>
    <button>:nth-child(3n+1)</button>
    <button>:nth-child(3n+2)</button>

    <button>:even</button>
    <button>:odd</button>
  </div>
  <div><table>

    <tr><td>John</td></tr>
    <tr><td>Karl</td></tr>
    <tr><td>Brandon</td></tr>

    <tr><td>Benjamin</td></tr>
  </table></div>
  <div><table>
    <tr><td>Sam</td></tr>

  </table></div>
  <div><table>
    <tr><td>Glen</td></tr>
    <tr><td>Tane</td></tr>

    <tr><td>Ralph</td></tr>
    <tr><td>David</td></tr>
    <tr><td>Mike</td></tr>

    <tr><td>Dan</td></tr>
  </table></div>
  <span>
    tr<span id="inner"></span>

  </span>
  <script>$("button").click(function () {
      var str = $(this).text();
      $("tr").css("background", "white");
      $("tr" + str).css("background", "#ff0000");
      $("#inner").text(str);
    });</script>
</body>
</html>

Demo:


Content Filter – jQuery API

Content Filter

  • JQuery(":parent")

    New in 1.0 !

    Select all elements that are the parent of another element, including text nodes.

  • JQuery(":has(selector)")

    New in 1.1.4 !

    Selects elements which contain at least one element that matches the specified selector.

  • JQuery(":empty")

    New in 1.0 !

    Select all elements that have no children (including text nodes).

  • JQuery(":contains(text)")

    New in 1.1.4 !

    Select all elements that contain the specified text.


parent – jQuery API

  • parent ( )

    • 1.0parent ( )

  • parent ( [ Selector ] selector )

    • 1.0parent ( [ Selector ] selector )

Returns: JQuery(":parent")

Categories: Content Filter, Version 1.0
Description: Select all elements that are the parent of another element, including text nodes.
  • version added: 1.0
  • JQuery(":parent")

This is the inverse of .

One important thing to note regarding the use of (and ) is that child elements include text nodes.

The W3C recommends that the element have at least one child node, even if that child is merely text (see ). Some other elements, on the other hand, are empty (i.e. have no children) by definition:, , , and , for example.

Examples:

Example:

Finds all tds with children, including text.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>td { width:40px; background:green; }</style>
</head>
<body>
  <table border="1">

  <tr><td>Value 1</td><td></td></tr>
  <tr><td>Value 2</td><td></td></tr>

</table>
  <script>$("td:parent").fadeTo(1500, 0.3);</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .parent( [ Selector ] selector )

Categories: Tree Traversal, Version 1.0
Description: Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
  • version added: 1.0
  • .parent( [ Selector ] selector )
  • selector A string containing a selector expression to match elements against.

Given a jQuery object that represents a set of DOM elements, the method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements. The and methods are similar, except that the latter only travels a single level up the DOM tree.

The method optionally accepts a selector expression of the same type that we can pass to the function. If the selector is supplied, the elements will be filtered by testing whether they match it.

Consider a page with a basic nested list on it:

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

If we begin at item A, we can find its parents:

$('li.item-a').parent().css('background-color', 'red');

The result of this call is a red background for the level-2 list. Since we do not supply a selector expression, the parent element is unequivocally included as part of the object. If we had supplied one, the element would be tested for a match before it was included.

Examples:

Example:

Shows the parent of each element as (parent > child). Check the View Source to see the raw html.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div,p { margin:10px; }</style>
</head>
<body>
  <div>div,
    <span>span, </span>
    <b>b </b>

  </div>
  <p>p,
    <span>span,
      <em>em </em>
    </span>
  </p>

  <div>div,
    <strong>strong,
      <span>span, </span>
      <em>em,
        <b>b, </b>
      </em>

    </strong>
    <b>b </b>
  </div>
  <script>$("*", document.body).each(function () {
      var parentTag = $(this).parent().get(0).tagName;
      $(this).prepend(document.createTextNode(parentTag + " > "));
    });</script>
</body>
</html>

Demo:

Example:

Find the parent element of each paragraph with a class "selected".
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <div><p>Hello</p></div>

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

  <script>$("p").parent(".selected").css("background", "yellow");</script>
</body>
</html>

Demo:


has – jQuery API

  • has ( [ String ] selector )

    • 1.4has ( [ String ] selector )
    • 1.4has ( [ Element ] contained )

  • has ( [ Selector ] selector )

    • 1.1.4has ( [ Selector ] selector )

Returns: jQueryjQuery .has( [ Element ] contained )

Categories: Filtering, Version 1.4
Description: Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
  • version added: 1.4
  • .has( [ String ] selector )
  • selector A string containing a selector expression to match elements against.
  • version added: 1.4
  • .has( [ Element ] contained )
  • contained A DOM element to match elements against.

Given a jQuery object that represents a set of DOM elements, the method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against the descendants of the matching elements; the element will be included in the result if any of its descendant elements matches the selector.

Consider a page with a nested list as follows:

 <ul>
  <li>list item 1</li>
  <li>list item 2
    <ul>
      <li>list item 2-a</li>
      <li>list item 2-b</li>
    </ul>
  </li>
  <li>list item 3</li>
  <li>list item 4</li>
</ul>

We can apply this method to the set of list items as follows:

$('li').has('ul').css('background-color', 'red');

The result of this call is a red background for item 2, as it is the only that has a among its descendants.

Examples:

Example:

Check if an element is inside another.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>.full { border: 1px solid red; }</style>
</head>
<body>

<ul><li>Does the UL contain an LI?</li></ul>

  <script>$("ul").append("<li>" + ($("ul").has("li").length ? "Yes" : "No") + "</li>");
  $("ul").has("li").addClass("full");</script>
</body>
</html>

Demo:

Returns: JQuery(":has(selector)")

Categories: Content Filter, Version 1.1.4
Description: Selects elements which contain at least one element that matches the specified selector.
  • version added: 1.1.4
  • JQuery(":has(selector)")
  • selector Any selector.

The expression matches a if a exists anywhere among its descendants, not just as a direct child.

Examples:

Example:

Adds the class "test" to all divs that have a paragraph inside of them.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>.test{ border: 3px inset red; }</style>
</head>
<body>
  <div><p>Hello in a paragraph</p></div>

  <div>Hello again! (with no paragraph)</div>
  <script>$("div:has(p)").addClass("test");</script>
</body>
</html>

Demo:


contains – jQuery API

Returns: JQuery(":contains(text)")

Categories: Content Filter, Version 1.1.4
Description: Select all elements that contain the specified text.
  • version added: 1.1.4
  • JQuery(":contains(text)")
  • text A string of text to look for. It's case sensitive.

The matching text can appear directly within the selected element, in any of that element's descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of can be written as bare words or surrounded by quotation marks. The text must have matching case to be selected.

Examples:

Example:

Finds all divs containing "John" and underlines them.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

<div>John Resig</div>

<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>

  <script>$("div:contains('John')").css("text-decoration", "underline");</script>
</body>
</html>

Demo:


Form – jQuery API

Form

  • JQuery(":selected")

    New in 1.0 !

    Selects all elements that are selected.

  • JQuery(":checked")

    New in 1.0 !

    Matches all elements that are checked.

  • JQuery(":disabled")

    New in 1.0 !

    Selects all elements that are disabled.

  • JQuery(":enabled")

    New in 1.0 !

    Selects all elements that are enabled.

  • JQuery(":file")

    New in 1.0 !

    Selects all elements of type file.

  • JQuery(":button")

    New in 1.0 !

    Selects all button elements and elements of type button.

  • JQuery(":reset")

    New in 1.0 !

    Selects all elements of type reset.

  • JQuery(":image")

    New in 1.0 !

    Selects all elements of type image.

  • JQuery(":submit")

    New in 1.0 !

    Selects all elements of type submit.

  • JQuery(":checkbox")

    New in 1.0 !

    Selects all elements of type checkbox.

  • JQuery(":radio")

    New in 1.0 !

    Selects all elements of type radio.

  • JQuery(":password")

    New in 1.0 !

    Selects all elements of type password.

  • JQuery(":text")

    New in 1.0 !

    Selects all elements of type text.

  • JQuery(":input")

    New in 1.0 !

    Selects all input, textarea, select and button elements.


selected – jQuery API

Returns: JQuery(":selected")

Categories: Form, Version 1.0
Description: Selects all elements that are selected.
  • version added: 1.0
  • JQuery(":selected")

The selector works for elements. It does not work for checkboxes or radio inputs; use for them.

Examples:

Example:

Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:red; }</style>
</head>
<body>
  <select name="garden" multiple="multiple">

    <option>Flowers</option>
    <option selected="selected">Shrubs</option>
    <option>Trees</option>
    <option selected="selected">Bushes</option>

    <option>Grass</option>
    <option>Dirt</option>
  </select>
  <div></div>
  <script>$("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " ";
              });
          $("div").text(str);
        })
        .trigger('change');</script>
</body>
</html>

Demo:


checked – jQuery API

Returns: JQuery(":checked")

Categories: Form, Version 1.0
Description: Matches all elements that are checked.
  • version added: 1.0
  • JQuery(":checked")

The selector works for checkboxes and radio buttons. For select elements, use the selector.

Examples:

Example:

Finds all input elements that are checked.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:red; }</style>
</head>
<body>
  <form>
    <input type="checkbox" name="newsletter" checked="checked" value="Hourly" />

    <input type="checkbox" name="newsletter" value="Daily" />
    <input type="checkbox" name="newsletter" value="Weekly" />

    <input type="checkbox" name="newsletter" checked="checked" value="Monthly" />
    <input type="checkbox" name="newsletter" value="Yearly" />

  </form>
  <div></div>
  <script>function countChecked() {
      var n = $("input:checked").length;
      $("div").text(n + (n <= 1 ? " is" : " are") + " checked!");
    }
    countChecked();
    $(":checkbox").click(countChecked);</script>
</body>
</html>

Demo:


disabled – jQuery API

Returns: JQuery(":disabled")

Categories: Form, Version 1.0
Description: Selects all elements that are disabled.
  • version added: 1.0
  • JQuery(":disabled")

As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare is equivalent to , so should be used instead.

Examples:

Example:

Finds all input elements that are disabled.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <form>

    <input name="email" disabled="disabled" />
    <input name="id" />
  </form>
  <script>$("input:disabled").val("this is it");</script>
</body>
</html>

Demo:


enabled – jQuery API

Returns: JQuery(":enabled")

Categories: Form, Version 1.0
Description: Selects all elements that are enabled.
  • version added: 1.0
  • JQuery(":enabled")

As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare is equivalent to , so should be used instead.

Examples:

Example:

Finds all input elements that are enabled.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <form>

    <input name="email" disabled="disabled" />
    <input name="id" />
  </form>
  <script>$("input:enabled").val("this is it");</script>
</body>
</html>

Demo:


file – jQuery API

Returns: JQuery(":file")

Categories: Form, Version 1.0
Description: Selects all elements of type file.
  • version added: 1.0
  • JQuery(":file")

As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare is equivalent to , so should be used instead.

Examples:

Example:

Finds all file inputs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>textarea { height:45px; }</style>
</head>
<body>
  <form>
    <input type="button" value="Input Button"/>
    <input type="checkbox" />

    <input type="file" />
    <input type="hidden" />
    <input type="image" />

    <input type="password" />
    <input type="radio" />
    <input type="reset" />

    <input type="submit" />
    <input type="text" />
    <select><option>Option<option/></select>

    <textarea></textarea>
    <button>Button</button>
  </form>
  <div>
  </div>
  <script>var input = $("input:file").css({background:"yellow", border:"3px red solid"});
    $("div").text("For this type jQuery found " + input.length + ".")
            .css("color", "red");
    $("form").submit(function () { return false; }); // so it won't submit</script>
</body>
</html>

Demo:


button – jQuery API

Returns: JQuery(":button")

Categories: Form, Version 1.0
Description: Selects all button elements and elements of type button.
  • version added: 1.0
  • JQuery(":button")

Examples:

Example:

Finds all button inputs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>textarea { height:45px; }</style>
</head>
<body>
  <form>
    <input type="button" value="Input Button"/>
    <input type="checkbox" />

    <input type="file" />
    <input type="hidden" />
    <input type="image" />

    <input type="password" />
    <input type="radio" />
    <input type="reset" />

    <input type="submit" />
    <input type="text" />
    <select><option>Option<option/></select>

    <textarea></textarea>
    <button>Button</button>
  </form>
  <div>
  </div>
  <script>var input = $(":button").css({background:"yellow", border:"3px red solid"});
    $("div").text("For this type jQuery found " + input.length + ".")
            .css("color", "red");
    $("form").submit(function () { return false; }); // so it won't submit</script>
</body>
</html>

Demo:


reset – jQuery API

Returns: JQuery(":reset")

Categories: Form, Version 1.0
Description: Selects all elements of type reset.
  • version added: 1.0
  • JQuery(":reset")

Examples:

Example:

Finds all reset inputs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>textarea { height:45px; }</style>
</head>
<body>
  <form>
    <input type="button" value="Input Button"/>
    <input type="checkbox" />

    <input type="file" />
    <input type="hidden" />
    <input type="image" />

    <input type="password" />
    <input type="radio" />
    <input type="reset" />

    <input type="submit" />
    <input type="text" />
    <select><option>Option<option/></select>

    <textarea></textarea>
    <button>Button</button>
  </form>
  <div>
  </div>
  <script>var input = $("input:reset").css({background:"yellow", border:"3px red solid"});
    $("div").text("For this type jQuery found " + input.length + ".")
            .css("color", "red");
    $("form").submit(function () { return false; }); // so it won't submit</script>
</body>
</html>

Demo:


image – jQuery API

Returns: JQuery(":image")

Categories: Form, Version 1.0
Description: Selects all elements of type image.
  • version added: 1.0
  • JQuery(":image")

Examples:

Example:

Finds all image inputs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>textarea { height:45px; }</style>
</head>
<body>
  <form>
    <input type="button" value="Input Button"/>
    <input type="checkbox" />

    <input type="file" />
    <input type="hidden" />
    <input type="image" />

    <input type="password" />
    <input type="radio" />
    <input type="reset" />

    <input type="submit" />
    <input type="text" />
    <select><option>Option<option/></select>

    <textarea></textarea>
    <button>Button</button>
  </form>
  <div>
  </div>
  <script>var input = $("input:image").css({background:"yellow", border:"3px red solid"});
    $("div").text("For this type jQuery found " + input.length + ".")
            .css("color", "red");
    $("form").submit(function () { return false; }); // so it won't submit</script>
</body>
</html>

Demo:


checkbox – jQuery API

Returns: JQuery(":checkbox")

Categories: Form, Version 1.0
Description: Selects all elements of type checkbox.
  • version added: 1.0
  • JQuery(":checkbox")

is equivalent to . As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare is equivalent to , so should be used instead.

Examples:

Example:

Finds all checkbox inputs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>textarea { height:25px; }</style>
</head>
<body>
  <form>
    <input type="button" value="Input Button"/>
    <input type="checkbox" />

    <input type="checkbox" />
    <input type="file" />
    <input type="hidden" />

    <input type="image" />
    <input type="password" />
    <input type="radio" />

    <input type="reset" />
    <input type="submit" />
    <input type="text" />

    <select><option>Option<option/></select>
    <textarea></textarea>
    <button>Button</button>
  </form>

  <div>
  </div>
  <script>var input = $("form input:checkbox").wrap('<span></span>').parent().css({background:"yellow", border:"3px red solid"});
    $("div").text("For this type jQuery found " + input.length + ".")
            .css("color", "red");
    $("form").submit(function () { return false; }); // so it won't submit</script>
</body>
</html>

Demo:


radio – jQuery API

Returns: JQuery(":radio")

Categories: Form, Version 1.0
Description: Selects all elements of type radio.
  • version added: 1.0
  • JQuery(":radio")

is equivalent to . As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare is equivalent to , so should be used instead.

To select a set of associated radio buttons, you might use:

Examples:

Example:

Finds all radio inputs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>textarea { height:25px; }</style>
</head>
<body>
  <form>
    <input type="button" value="Input Button"/>
    <input type="checkbox" />

    <input type="file" />
    <input type="hidden" />
    <input type="image" />

    <input type="password" />
    <input type="radio" name="asdf" />
    <input type="radio" name="asdf" />

    <input type="reset" />
    <input type="submit" />
    <input type="text" />

    <select><option>Option<option/></select>
    <textarea></textarea>
    <button>Button</button>
  </form>

  <div>
  </div>
  <script>var input = $("form input:radio").wrap('<span></span>').parent().css({background:"yellow", border:"3px red solid"});
    $("div").text("For this type jQuery found " + input.length + ".")
            .css("color", "red");
    $("form").submit(function () { return false; }); // so it won't submit</script>
</body>
</html>

Demo:


password – jQuery API

Returns: JQuery(":password")

Categories: Form, Version 1.0
Description: Selects all elements of type password.
  • version added: 1.0
  • JQuery(":password")

is equivalent to . As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare is equivalent to , so should be used instead.

Examples:

Example:

Finds all password inputs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>textarea { height:45px; }</style>
</head>
<body>
  <form>
    <input type="button" value="Input Button"/>
    <input type="checkbox" />

    <input type="file" />
    <input type="hidden" />
    <input type="image" />

    <input type="password" />
    <input type="radio" />
    <input type="reset" />

    <input type="submit" />
    <input type="text" />
    <select><option>Option<option/></select>

    <textarea></textarea>
    <button>Button</button>
  </form>
  <div>
  </div>
  <script>var input = $("input:password").css({background:"yellow", border:"3px red solid"});
    $("div").text("For this type jQuery found " + input.length + ".")
            .css("color", "red");
    $("form").submit(function () { return false; }); // so it won't submit</script>
</body>
</html>

Demo:


input – jQuery API

Returns: JQuery(":input")

Categories: Form, Version 1.0
Description: Selects all input, textarea, select and button elements.
  • version added: 1.0
  • JQuery(":input")

The selector basically selects all form controls.

Examples:

Example:

Finds all input elements.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>textarea { height:25px; }</style>
</head>
<body>
  <form>
    <input type="button" value="Input Button"/>
    <input type="checkbox" />

    <input type="file" />
    <input type="hidden" />
    <input type="image" />

    <input type="password" />
    <input type="radio" />
    <input type="reset" />

    <input type="submit" />
    <input type="text" />
    <select><option>Option</option></select>

    <textarea></textarea>
    <button>Button</button>
  </form>
  <div id="messages">
  </div>
  <script>var allInputs = $(":input");
    var formChildren = $("form > *");
    $("#messages").text("Found " + allInputs.length + " inputs and the form has " +
                             formChildren.length + " children.");

    // so it won't submit
    $("form").submit(function () { return false; });</script>
</body>
</html>

Demo:


Hierarchy – jQuery API

Hierarchy

  • JQuery("prev ~ siblings")

    New in 1.0 !

    Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.

  • JQuery("prev + next")

    New in 1.0 !

    Selects all next elements matching "next" that are immediately preceded by a sibling "prev".

  • child")" rel="bookmark">JQuery("parent > child")

    New in 1.0 !

    Selects all direct child elements specified by "child" of elements specified by "parent".

  • JQuery("ancestor descendant")

    New in 1.0 !

    Selects all elements that are descendants of a given ancestor.


next siblings – jQuery API

Returns: JQuery("prev ~ siblings")

Categories: Hierarchy, Version 1.0
Description: Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.
  • version added: 1.0
  • JQuery("prev ~ siblings")
  • prev Any valid selector.
  • siblings A selector to filter elements that are the following siblings of the first selector.

The notable difference between () and () is their respective reach. While the former reaches only to the immediately following sibling element, the latter extends that reach to all following sibling elements.

Examples:

Example:

Finds all divs that are siblings after the element with #prev as its id. Notice the span isn't selected since it is not a div and the "niece" isn't selected since it is a child of a sibling, not an actual sibling.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div,span {
    display:block;
    width:80px;
    height:80px;
    margin:5px;
    background:#bbffaa;
    float:left;
    font-size:14px;
  }
  div#small {
    width:60px;
    height:25px;
    font-size:12px;
    background:#fab;
  }</style>
</head>
<body>
  <div>div (doesn't match since before #prev)</div>
  <span id="prev">span#prev</span>
  <div>div sibling</div>

  <div>div sibling <div id="small">div niece</div></div>
  <span>span sibling (not div)</span>
  <div>div sibling</div>
  <script>$("#prev ~ div").css("border", "3px groove blue");</script>
</body>
</html>

Demo:


next adjacent – jQuery API

Returns: JQuery("prev + next")

Categories: Hierarchy, Version 1.0
Description: Selects all next elements matching "next" that are immediately preceded by a sibling "prev".
  • version added: 1.0
  • JQuery("prev + next")
  • prev Any valid selector.
  • next A selector to match the element that is next to the first selector.

One important point to consider with both the next adjacent sibling selector () and the general sibling selector () is that the elements on either side of the combinator must share the same parent.

Examples:

Example:

Finds all inputs that are next to a label.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <form>

    <label>Name:</label>
    <input name="name" />
    <fieldset>
      <label>Newsletter:</label>

      <input name="newsletter" />
    </fieldset>
  </form>
  <input name="none" />
  <script>$("label + input").css("color", "blue").val("Labeled!")</script>
</body>
</html>

Demo:


child – jQuery API

Returns: JQuery("parent > child")

Categories: Hierarchy, Version 1.0
Description: Selects all direct child elements specified by "child" of elements specified by "parent".
  • version added: 1.0
  • JQuery("parent > child")
  • parent Any valid selector.
  • child A selector to filter the child elements.

As a CSS selector, the child combinator is supported by all modern web browsers including Safari, Firefox, Opera, Chrome, and Internet Explorer 7 and above, but notably not by Internet Explorer versions 6 and below. However, in jQuery, this selector (along with all others) works across all supported browsers, including IE6.

The child combinator (E F) can be thought of as a more specific form of the descendant combinator (E F) in that it selects only first-level descendants.

Examples:

Example:

Places a border around all list items that are children of
    .
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { font-size:14px; }</style>
</head>
<body>

<ul class="topnav">
    <li>Item 1</li>
    <li>Item 2
        <ul><li>Nested item 1</li><li>Nested item 2</li><li>Nested item 3</li></ul>
       </li>
    <li>Item 3</li>
</ul>

  <script>$("ul.topnav > li").css("border", "3px double red");</script>
</body>
</html>

Demo:


descendant – jQuery API

Returns: JQuery("ancestor descendant")

Categories: Hierarchy, Version 1.0
Description: Selects all elements that are descendants of a given ancestor.
  • version added: 1.0
  • JQuery("ancestor descendant")
  • ancestor Any valid selector.
  • descendant A selector to filter the descendant elements.

A descendant of an element could be a child, grandchild, great-grandchild, and so on, of that element.

Examples:

Example:

Finds all input descendants of forms.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { font-size:14px; }
  form { border:2px green solid; padding:2px; margin:0;
         background:#efe; }
  div { color:red; }
  fieldset { margin:1px; padding:3px; }</style>
</head>
<body>
  <form>
    <div>Form is surrounded by the green outline</div>
    <label>Child:</label>
    <input name="name" />

    <fieldset>
      <label>Grandchild:</label>
      <input name="newsletter" />
    </fieldset>

  </form>
  Sibling to form: <input name="none" />
  <script>$("form input").css("border", "2px dotted blue");</script>
</body>
</html>

Demo:


Visibility Filter – jQuery API

Visibility Filter

  • JQuery(":visible")

    New in 1.0 !

    Selects all elements that are visible.

  • JQuery(":hidden")

    New in 1.0 !

    Selects all elements that are hidden.


visible – jQuery API

Returns: JQuery(":visible")

Categories: Version 1.0, Visibility Filter
Description: Selects all elements that are visible.
  • version added: 1.0
  • JQuery(":visible")

Elements can be considered hidden for several reasons:

Elements with or are considered to be visible, since they still consume space in the layout. During animations that hide an element, the element is considered to be visible until the end of the animation. During animations to show an element, the element is considered to be visible at the start at the animation.

How is calculated was changed in jQuery 1.3.2. The outline the changes in more detail.

Examples:

Example:

Make all visible divs turn yellow on click.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:50px; height:40px; margin:5px; border:3px outset green; float:left; }
  .starthidden { display:none; }</style>
</head>
<body>
  <button>Show hidden to see they don't change</button>
  <div></div>
  <div class="starthidden"></div>
  <div></div>

  <div></div>
  <div style="display:none;"></div>
  <script>$("div:visible").click(function () {
      $(this).css("background", "yellow");
    });
    $("button").click(function () {
      $("div:hidden").show("fast");
    });</script>
</body>
</html>

Demo:


hidden – jQuery API

Returns: JQuery(":hidden")

Categories: Version 1.0, Visibility Filter
Description: Selects all elements that are hidden.
  • version added: 1.0
  • JQuery(":hidden")

Elements can be considered hidden for several reasons:

Elements with or are considered to be visible, since they still consume space in the layout. During animations that hide an element, the element is considered to be visible until the end of the animation. During animations to show an element, the element is considered to be visible at the start of the animation.

How is determined was changed in jQuery 1.3.2. An element is assumed to be hidden if it or any of its parents consumes no space in the document. CSS visibility isn't taken into account (therefore ). The outline the changes in more detail.

Examples:

Example:

Shows all hidden divs and counts hidden inputs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:70px; height:40px; background:#ee77ff; margin:5px; float:left; }
  span { display:block; clear:left; color:red; }
  .starthidden { display:none; }</style>
</head>
<body>
  <span></span>
  <div></div>
  <div style="display:none;">Hider!</div>
  <div></div>

  <div class="starthidden">Hider!</div>
  <div></div>
  <form>
    <input type="hidden" />

    <input type="hidden" />
    <input type="hidden" />
  </form>
  <span>

  </span>
  <script>// in some browsers :hidden includes head, title, script, etc... so limit to body
    $("span:first").text("Found " + $(":hidden", document.body).length +
                         " hidden elements total.");
    $("div:hidden").show(3000);
    $("span:last").text("Found " + $("input:hidden").length + " hidden inputs.");</script>
</body>
</html>

Demo:


Traversing – jQuery API

Traversing

  • jQuery .has( [ Element ] contained )

    New in 1.4 !

    Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

  • jQuery .first( )

    New in 1.4 !

    Reduce the set of matched elements to the first in the set.

  • jQuery .last( )

    New in 1.4 !

    Reduce the set of matched elements to the final one in the set.

  • jQuery .slice( [ Integer ] start, [ Integer ] end )

    New in 1.1.4 !

    Reduce the set of matched elements to a subset specified by a range of indices.

  • jQuery .not( [ Function ] function(index) )

    New in 1.4 !

    Remove elements from the set of matched elements.

  • jQuery .map( [ Function ] callback(index, domElement) )

    New in 1.2 !

    Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

  • Boolean .is( [ Selector ] selector )

    New in 1.0 !

    Check the current matched set of elements against a selector and return true if at least one of these elements matches the selector.

  • jQuery .eq( [ Integer ] -index )

    New in 1.4 !

    Reduce the set of matched elements to the one at the specified index.

  • jQuery .filter( [ Object ] jQuery object )

    New in 1.4 !

    Reduce the set of matched elements to those that match the selector or pass the function's test.

  • jQuery .end( )

    New in 1.0 !

    End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.

  • jQuery .andSelf( )

    New in 1.2 !

    Add the previous set of elements on the stack to the current set.

  • jQuery .contents( )

    New in 1.2 !

    Get the children of each element in the set of matched elements, including text and comment nodes.

  • jQuery .add( [ Selector ] selector, [ Element ] context )

    New in 1.4 !

    Add elements to the set of matched elements.

  • jQuery .parentsUntil( [ Selector ] selector )

    New in 1.4 !

    Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.

  • jQuery .prevUntil( [ Selector ] selector )

    New in 1.4 !

    Get all preceding siblings of each element up to but not including the element matched by the selector.

  • jQuery .nextUntil( [ Selector ] selector )

    New in 1.4 !

    Get all following siblings of each element up to but not including the element matched by the selector.

  • jQuery .siblings( [ Selector ] selector )

    New in 1.0 !

    Get the siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .prevAll( [ Selector ] selector )

    New in 1.2 !

    Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .prev( [ Selector ] selector )

    New in 1.0 !

    Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .parents( [ Selector ] selector )

    New in 1.0 !

    Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

  • jQuery .parent( [ Selector ] selector )

    New in 1.0 !

    Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

  • jQuery .offsetParent( )

    New in 1.2.6 !

    Get the closest ancestor element that is positioned.

  • jQuery .nextAll( [ String ] selector )

    New in 1.2 !

    Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .next( [ Selector ] selector )

    New in 1.0 !

    Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

  • jQuery .find( [ Selector ] selector )

    New in 1.0 !

    Get the descendants of each element in the current set of matched elements, filtered by a selector.

  • Array .closest( [ Array ] selectors, [ Element ] context )

    New in 1.4 !

    Gets an array of all the elements and selectors matched against the current element up through the DOM tree.

  • jQuery .children( [ Selector ] selector )

    New in 1.0 !

    Get the children of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .each( [ Function ] function(index, Element) )

    New in 1.0 !

    Iterate over a jQuery object, executing a function for each matched element.


Filtering – jQuery API

Filtering

  • jQuery .has( [ Element ] contained )

    New in 1.4 !

    Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

  • jQuery .first( )

    New in 1.4 !

    Reduce the set of matched elements to the first in the set.

  • jQuery .last( )

    New in 1.4 !

    Reduce the set of matched elements to the final one in the set.

  • jQuery .slice( [ Integer ] start, [ Integer ] end )

    New in 1.1.4 !

    Reduce the set of matched elements to a subset specified by a range of indices.

  • jQuery .not( [ Function ] function(index) )

    New in 1.4 !

    Remove elements from the set of matched elements.

  • jQuery .map( [ Function ] callback(index, domElement) )

    New in 1.2 !

    Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

  • Boolean .is( [ Selector ] selector )

    New in 1.0 !

    Check the current matched set of elements against a selector and return true if at least one of these elements matches the selector.

  • jQuery .eq( [ Integer ] -index )

    New in 1.4 !

    Reduce the set of matched elements to the one at the specified index.

  • jQuery .filter( [ Object ] jQuery object )

    New in 1.4 !

    Reduce the set of matched elements to those that match the selector or pass the function's test.


slice – jQuery API

Returns: jQueryjQuery .slice( [ Integer ] start, [ Integer ] end )

Categories: Filtering, Version 1.1.4
Description: Reduce the set of matched elements to a subset specified by a range of indices.
  • version added: 1.1.4
  • .slice( [ Integer ] start, [ Integer ] end )
  • start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.
  • end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set.

Given a jQuery object that represents a set of DOM elements, the method constructs a new jQuery object from a subset of the matching elements. The supplied index identifies the position of one of the elements in the set; if is omitted, all elements after this one will be included in the result.

Consider a page with a simple list on it:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

We can apply this method to the set of list items:

$('li').slice(2).css('background-color', 'red');

The result of this call is a red background for items 3, 4, and 5. Note that the supplied index is zero-based, and refers to the position of elements within the jQuery object, not within the DOM tree.

The end parameter allows us to limit the selected range even further. For example:

$('li').slice(2, 4).css('background-color', 'red');

Now only items 3 and 4 are selected. The index is once again zero-based; the range extends up to but not including the specified index.

Negative Indices

The jQuery method is patterned after the JavaScript .slice() method for arrays. One of the features that it mimics is the ability for negative numbers to be passed as either the or parameter. If a negative number is provided, this indicates a position starting from the end of the set, rather than the beginning. For example:

$('li').slice(-2, -1).css('background-color', 'red');

This time only list item 4 is turned red, since it is the only item in the range between two from the end () and one from the end ().

Examples:

Example:

Turns divs yellow based on a random slice.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:40px; height:40px; margin:10px; float:left;
        border:2px solid blue; }
  span { color:red; font-weight:bold; }
  button { margin:5px; }</style>
</head>
<body>
  <p><button>Turn slice yellow</button>
  <span>Click the button!</span></p>
  <div></div>
  <div></div>

  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>

  <div></div>
  <div></div>
  <script>function colorEm() {
      var $div = $("div");
      var start = Math.floor(Math.random() *
                             $div.length);
      var end = Math.floor(Math.random() *
                           ($div.length - start)) +
                           start + 1;
      if (end == $div.length) end = undefined;
      $div.css("background", "");
      if (end)
        $div.slice(start, end).css("background", "yellow");
       else
        $div.slice(start).css("background", "yellow");

      $("span").text('$("div").slice(' + start +
                     (end ? ', ' + end : '') +
                     ').css("background", "yellow");');
    }

    $("button").click(colorEm);</script>
</body>
</html>

Demo:

Example:

Selects all paragraphs, then slices the selection to include only the first element.
$("p").slice(0, 1).wrapInner("<b></b>");

Example:

Selects all paragraphs, then slices the selection to include only the first and second element.
$("p").slice(0, 2).wrapInner("<b></b>");

Example:

Selects all paragraphs, then slices the selection to include only the second element.
$("p").slice(1, 2).wrapInner("<b></b>");

Example:

Selects all paragraphs, then slices the selection to include only the second and third element.
$("p").slice(1).wrapInner("<b></b>");

Example:

Selects all paragraphs, then slices the selection to include only the third element.
$("p").slice(-1).wrapInner("<b></b>");


map – jQuery API

Returns: jQueryjQuery .map( [ Function ] callback(index, domElement) )

Categories: Filtering, Version 1.2
Description: Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
  • version added: 1.2
  • .map( [ Function ] callback(index, domElement) )
  • callback(index, domElement) A function object that will be invoked for each element in the current set.

As the return value is a jQuery-wrapped array, it's very common to the returned object to work with a basic array.

The method is particularly useful for getting or setting the value of a collection of elements. Consider a form with a set of checkboxes in it:

<form method="post" action="">
  <fieldset>
    <div>
      <label for="two">2</label>
      <input type="checkbox" value="2" id="two" name="number[]">
    </div>
    <div>
      <label for="four">4</label>
      <input type="checkbox" value="4" id="four" name="number[]">
    </div>
    <div>
      <label for="six">6</label>
      <input type="checkbox" value="6" id="six" name="number[]">
    </div>
    <div>
      <label for="eight">8</label>
      <input type="checkbox" value="8" id="eight" name="number[]">
    </div>
  </fieldset>
</form>

We can get a comma-separated list of checkbox s:

$(':checkbox').map(function() {
  return this.id;
}).get().join(',');

The result of this call is the string, .

Within the callback function, refers to the current DOM element for each iteration. The function can return an individual data item or an array of data items to be inserted into the resulting set. If an array is returned, the elements inside the array are inserted into the set. If the function returns or , no element will be inserted.

Examples:

Example:

Build a list of all the values within a form.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:red; }</style>
</head>
<body>
  <p><b>Values: </b></p>
  <form>
    <input type="text" name="name" value="John"/>

    <input type="text" name="password" value="password"/>
    <input type="text" name="url" value="http://ejohn.org/"/>

  </form>
  <script>$("p").append( $("input").map(function(){
      return $(this).val();
    }).get().join(", ") );</script>
</body>
</html>

Demo:

Example:

A contrived example to show some functionality.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { font-size:16px; }
  ul { float:left; margin:0 30px; color:blue; }
  #results { color:red; }</style>
</head>
<body>
  <ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>

    <li>Fourth</li>
    <li>Fifth</li>
  </ul>
  <ul id="results">

  </ul>
  <script>var mappedItems = $("li").map(function (index) {
      var replacement = $("<li>").text($(this).text()).get(0);
      if (index == 0) {
        // make the first item all caps
        $(replacement).text($(replacement).text().toUpperCase());
      } else if (index == 1 || index == 3) {
        // delete the second and fourth items
        replacement = null;
      } else if (index == 2) {
        // make two of the third item and add some text
        replacement = [replacement,$("<li>").get(0)];
        $(replacement[0]).append("<b> - A</b>");
        $(replacement[1]).append("Extra <b> - B</b>");
      }

      // replacement will be an dom element, null,
      // or an array of dom elements
      return replacement;
    });
    $("#results").append(mappedItems);</script>
</body>
</html>

Demo:

Example:

Equalize the heights of the divs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width: 40px; float:left; }
input { clear:left}</style>
</head>
<body>

<input type="button" value="equalize div heights">

<div style="background:red; height: 40px; "></div>
<div style="background:green; height: 70px;"></div>
<div style="background:blue; height: 50px; "></div>

  <script>$.fn.equalizeHeights = function(){
  return this.height( Math.max.apply(this, $(this).map(function(i,e){ return $(e).height() }).get() ) )
}
$('input').click(function(){
  $('div').equalizeHeights();
});</script>
</body>
</html>

Demo:


is – jQuery API

Returns: BooleanBoolean .is( [ Selector ] selector )

Categories: Filtering, Version 1.0
Description: Check the current matched set of elements against a selector and return true if at least one of these elements matches the selector.
  • version added: 1.0
  • .is( [ Selector ] selector )
  • selector A string containing a selector expression to match elements against.

Unlike the other filtering methods, does not create a new jQuery object. Instead, it allows you to test the contents of a jQuery object without modification. This is often useful inside callbacks, such as event handlers.

Suppose you have a list, with two of its items containing a child element:

<ul>
  <li>list <strong>item 1</strong></li>
  <li><span>list item 2</span></li>
  <li>list item 3</li>
</ul>

You can attach a click handler to the <ul> element, and then limit the code to be triggered only when a list item itself, not one of its children, is clicked:

$('ul').click(function(event) {
  if ($(event.target).is('li') ) {
    $(event.target).css('background-color', 'red');
  }
});

Now, when the user clicks on the word "list" in the first item or anywhere in the third item, the clicked list item will be given a red background. However, when the user clicks on item 1 in the first item or anywhere in the second item, nothing will occur, because in those cases the target of the event would be or , respectively.

Examples:

Example:

Shows a few ways is() can be used inside an event handler.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:60px; height:60px; margin:5px; float:left;
        border:4px outset; background:green; text-align:center;
        font-weight:bolder; cursor:pointer; }
  .blue { background:blue; }
  .red { background:red; }
  span { color:white; font-size:16px; }
  p { color:red; font-weight:bolder; background:yellow;
      margin:3px; clear:left; display:none; }</style>
</head>
<body>
  <div></div>
  <div class="blue"></div>
  <div></div>
  <div class="red"></div>

  <div><br/><span>Peter</span></div>
  <div class="blue"></div>
  <p>&nbsp;</p>
  <script>$("div").one('click', function () {
      if ($(this).is(":first-child")) {
        $("p").text("It's the first div.");
      } else if ($(this).is(".blue,.red")) {
        $("p").text("It's a blue or red div.");
      } else if ($(this).is(":contains('Peter')")) {
        $("p").text("It's Peter!");
      } else {
        $("p").html("It's nothing <em>special</em>.");
      }
      $("p").hide().slideDown("slow");
      $(this).css({"border-style": "inset", cursor:"default"});
    });</script>
</body>
</html>

Demo:

Example:

Returns true, because the parent of the input is a form element
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:red; }</style>
</head>
<body>
  <form><input type="checkbox" /></form>

  <div></div>
  <script>var isFormParent = $("input[type='checkbox']").parent().is("form");
    $("div").text("isFormParent = " + isFormParent);</script>
</body>
</html>

Demo:

Example:

Returns false, because the parent of the input is a p element
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:red; }</style>
</head>
<body>
  <form><p><input type="checkbox" /></p></form>

  <div></div>
  <script>var isFormParent = $("input[type='checkbox']").parent().is("form")
    $("div").text("isFormParent = " + isFormParent);</script>
</body>
</html>

Demo:


filter – jQuery API

Returns: jQueryjQuery .filter( [ Object ] jQuery object )

Categories: Filtering, Version 1.0
Description: Reduce the set of matched elements to those that match the selector or pass the function's test.
  • version added: 1.0
  • .filter( [ Selector ] selector )
  • selector A string containing a selector expression to match the current set of elements against.
  • version added: 1.0
  • .filter( [ Function ] function(index) )
  • function(index) A function used as a test for each element in the set. is the current DOM element.
  • version added: 1.4
  • .filter( [ Element ] element )
  • element An element to match the current set of elements against.
  • version added: 1.4
  • .filter( [ Object ] jQuery object )
  • jQuery object An existing jQuery object to match the current set of elements against.

Given a jQuery object that represents a set of DOM elements, the method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; all elements matching the selector will be included in the result.

Consider a page with a simple list on it:

We can apply this method to the set of list items:

  $('li').filter(':even').css('background-color', 'red');

The result of this call is a red background for items 1, 3, and 5, as they match the selector (recall that and use 0-based indexing).

Using a Filter Function

The second form of this method allows us to filter elements against a function rather than a selector. For each element, if the function returns , the element will be included in the filtered set; otherwise, it will be excluded. Suppose we have a somewhat more involved HTML snippet:

<ul>
  <li><strong>list</strong> item 1 -
    one strong tag</li>
  <li><strong>list</strong> item <strong>2</strong> -
    two <span>strong tags</span></li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
  <li>list item 6</li>
</ul>

We can select the list items, then filter them based on their contents:

$('li').filter(function(index) {
  return $('strong', this).length == 1;
}).css('background-color', 'red');

This code will alter the first list item only, as it contains exactly one tag. Within the filter function, refers to each DOM element in turn. The parameter passed to the function tells us the index of that DOM element within the set matched by the jQuery object.

We can also take advantage of the passed through the function, which indicates the 0-based position of the element within the unfiltered set of matched elements:

$('li').filter(function(index) {
  return index % 3 == 2;
}).css('background-color', 'red');

This alteration to the code will cause the third and sixth list items to be highlighted, as it uses the modulus operator () to select every item with an value that, when divided by 3, has a remainder of .

Examples:

Example:

Change the color of all divs then put a border around only some of them.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:60px; height:60px; margin:5px; float:left;
        border:2px white solid;}</style>
</head>
<body>
  <div></div>

  <div class="middle"></div>
  <div class="middle"></div>
  <div class="middle"></div>
  <div class="middle"></div>

  <div></div>
  <script>$("div").css("background", "#c8ebcc")
            .filter(".middle")
            .css("border-color", "red");</script>
</body>
</html>

Demo:

Example:

Selects all paragraphs and removes those without a class "selected".
$("p").filter(".selected")

Example:

Selects all paragraphs and removes those that aren't of class "selected" or the first one.
$("p").filter(".selected, :first")

Example:

Change the color of all divs then put a border to specific ones.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:60px; height:60px; margin:5px; float:left;
        border:3px white solid; }</style>
</head>
<body>
  <div id="first"></div>
  <div id="second"></div>
  <div id="third"></div>

  <div id="fourth"></div>
  <div id="fifth"></div>
  <div id="sixth"></div>
  <script>$("div").css("background", "#b4b0da")
            .filter(function (index) {
                  return index == 1 || $(this).attr("id") == "fourth";
                })
            .css("border", "3px double red");</script>
</body>
</html>

Demo:

Example:

Remove all elements that have a descendant ol element
$("div").filter(function(index) {
   return $("ol", this).length == 0;
 });


Miscellaneous Traversing – jQuery API

Miscellaneous Traversing

  • jQuery .end( )

    New in 1.0 !

    End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.

  • jQuery .andSelf( )

    New in 1.2 !

    Add the previous set of elements on the stack to the current set.

  • jQuery .contents( )

    New in 1.2 !

    Get the children of each element in the set of matched elements, including text and comment nodes.

  • jQuery .add( [ Selector ] selector, [ Element ] context )

    New in 1.4 !

    Add elements to the set of matched elements.


end – jQuery API

Returns: jQueryjQuery .end( )

Categories: Miscellaneous Traversing, Version 1.0
Description: End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
  • version added: 1.0
  • .end( )

Most of jQuery's methods operate on a jQuery object instance and produce a new one, matching a different set of DOM elements. When this happens, it is as if the new set of elements is pushed onto a stack that is maintained inside the object. Each successive filtering method pushes a new element set onto the stack. If we need an older element set, we can use to pop the sets back off of the stack.

Suppose we have a couple short lists on a page:

<ul class="first">
   <li class="foo">list item 1</li>
   <li>list item 2</li>
   <li class="bar">list item 3</li>
</ul>
<ul class="second">
   <li class="foo">list item 1</li>
   <li>list item 2</li>
   <li class="bar">list item 3</li>
</ul>

The method is useful primarily when exploiting jQuery's chaining properties. When not using chaining, we can usually just call up a previous object by variable name, so we don't need to manipulate the stack. With , though, we can string all the method calls together:

$('ul.first').find('.foo').css('background-color', 'red')
  .find('.bar').css('background-color', 'green');

This chain searches for items with the class within the first list only and turns their backgrounds red. Then returns the object to its state before the call to , so the second looks for '.bar' inside , not just inside that list's , and turns the matching elements' backgrounds green. The net result is that items 1 and 3 of the first list have a colored background, and none of the items from the second list do.

A long jQuery chain can be visualized as a structured code block, with filtering methods providing the openings of nested blocks and methods closing them:

$('ul.first').find('.foo')
  .css('background-color', 'red')
.end().find('.bar')
  .css('background-color', 'green')
.end();

The last is unnecessary, as we are discarding the jQuery object immediately thereafter. However, when the code is written in this form, the provides visual symmetry and a sense of completion —making the program, at least to the eyes of some developers, more readable, at the cost of a slight hit to performance as it is an additional function call.

Examples:

Example:

Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p, div { margin:1px; padding:1px; font-weight:bold;
           font-size:16px; }
  div { color:blue; }
  b { color:red; }</style>
</head>
<body>
  <p>
    Hi there <span>how</span> are you <span>doing</span>?
  </p>

  <p>
    This <span>span</span> is one of
    several <span>spans</span> in this
    <span>sentence</span>.
  </p>

  <div>
    Tags in jQuery object initially: <b></b>
  </div>
  <div>
    Tags in jQuery object after find: <b></b>

  </div>
  <div>
    Tags in jQuery object after end: <b></b>
  </div>
  <script>jQuery.fn.showTags = function (n) {
      var tags = this.map(function () {
                              return this.tagName;
                            })
                        .get().join(", ");
      $("b:eq(" + n + ")").text(tags);
      return this;
    };

    $("p").showTags(0)
          .find("span")
          .showTags(1)
          .css("background", "yellow")
          .end()
          .showTags(2)
          .css("font-style", "italic");</script>
</body>
</html>

Demo:

Example:

Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { margin:10px; padding:10px; }</style>
</head>
<body>
  <p><span>Hello</span>, how are you?</p>
  <script>$("p").find("span").end().css("border", "2px red solid");</script>
</body>
</html>

Demo:


andSelf – jQuery API

Returns: jQueryjQuery .andSelf( )

Categories: Miscellaneous Traversing, Version 1.2
Description: Add the previous set of elements on the stack to the current set.
  • version added: 1.2
  • .andSelf( )

As described in the discussion for , jQuery objects maintain an internal stack that keeps track of changes to the matched set of elements. When one of the DOM traversal methods is called, the new set of elements is pushed onto the stack. If the previous set of elements is desired as well, can help.

Consider a page with a simple list on it:

<ul>
   <li>list item 1</li>
   <li>list item 2</li>
   <li class="third-item">list item 3</li>
   <li>list item 4</li>
   <li>list item 5</li>
</ul>

The result of the following code is a red background behind items 3, 4 and 5:

$('li.third-item').nextAll().andSelf()
  .css('background-color', 'red');

First, the initial selector locates item 3, initializing the stack with the set containing just this item. The call to then pushes the set of items 4 and 5 onto the stack. Finally, the invocation merges these two sets together, creating a jQuery object that points to all three items in document order: .

Examples:

Example:

Find all s, and all the paragraphs inside of them, and give them both class names. Notice the doesn't have the yellow background color since it didn't use .
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p, div { margin:5px; padding:5px; }
  .border { border: 2px solid red; }
  .background { background:yellow; }</style>
</head>
<body>
  <div>
    <p>First Paragraph</p>
    <p>Second Paragraph</p>
  </div>
  <script>$("div").find("p").andSelf().addClass("border");
    $("div").find("p").addClass("background");</script>
</body>
</html>

Demo:


contents – jQuery API

Returns: jQueryjQuery .contents( )

Categories: Miscellaneous Traversing, Version 1.2
Description: Get the children of each element in the set of matched elements, including text and comment nodes.
  • version added: 1.2
  • .contents( )

Given a jQuery object that represents a set of DOM elements, the method allows us to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The and methods are similar, except that the former includes text nodes as well as HTML elements in the resulting jQuery object.

The method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.

Consider a simple with a number of text nodes, each of which is separated by two line break elements ():

<div class="container">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
  do eiusmod tempor incididunt ut labore et dolore magna aliqua.
  <br /><br />
  Ut enim ad minim veniam, quis nostrud exercitation ullamco
  laboris nisi ut aliquip ex ea commodo consequat.
  <br /> <br />
  Duis aute irure dolor in reprehenderit in voluptate velit
  esse cillum dolore eu fugiat nulla pariatur.
</div>

We can employ the method to help convert this blob of text into three well-formed paragraphs:

$('.container').contents().filter(function() {
  return this.nodeType == 3;
})
  .wrap('<p></p>')
.end()
.filter('br')
  .remove();

This code first retrieves the contents of and then filters it for text nodes, which are wrapped in paragraph tags. This is accomplished by testing the of the element. This DOM property holds a numeric code indicating the node's type; text nodes use the code 3. The contents are again filtered, this time for elements, and these elements are removed.

Examples:

Example:

Find all the text nodes inside a paragraph and wrap them with a bold tag.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>Hello <a href="http://ejohn.org/">John</a>, how are you doing?</p>
  <script>$("p").contents().filter(function(){ return this.nodeType != 1; }).wrap("<b/>");</script>
</body>
</html>

Demo:

Example:

Change the background colour of links inside of an iframe.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <iframe src="http://api.jquery.com/" width="80%" height="600" id='frameDemo'></iframe>
  <script>$("#frameDemo").contents().find("a").css("background-color","#BADA55");</script>
</body>
</html>

Demo:


add – jQuery API

Returns: jQueryjQuery .add( [ Selector ] selector, [ Element ] context )

Categories: Miscellaneous Traversing, Version 1.0, Version 1.4
Description: Add elements to the set of matched elements.
  • version added: 1.0
  • .add( [ Selector ] selector )
  • selector A string representing a selector expression to find additional elements to add to the set of matched elements.
  • version added: 1.0
  • .add( [ Elements ] elements )
  • elements One or more elements to add to the set of matched elements.
  • version added: 1.0
  • .add( [ HTML ] html )
  • html An HTML fragment to add to the set of matched elements.
  • version added: 1.4
  • .add( [ Selector ] selector, [ Element ] context )
  • selector A string representing a selector expression to find additional elements to add to the set of matched elements.
  • context The point in the document at which the selector should begin matching; similar to the context argument of the method.

Given a jQuery object that represents a set of DOM elements, the method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to can be pretty much anything that accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.

The updated set of elements can be used in a following (chained) method, or assigned to a variable for later use. For example:

$("p").add("div").addClass("widget");
var pdiv = $("p").add("div");

The following will save the added elements, because the method creates a new set and leaves the original set in pdiv unchanged:

var pdiv = $("p");
pdiv.add("div");  // WRONG, pdiv will not change

Consider a page with a simple list and a paragraph following it:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
</ul>
<p>a paragraph</p>

We can select the list items and then the paragraph by using either a selector or a reference to the DOM element itself as the method's argument:

$('li').add('p').css('background-color', 'red');

Or:

$('li').add(document.getElementsByTagName('p')[0])
  .css('background-color', 'red');

The result of this call is a red background behind all four elements. Using an HTML snippet as the method's argument (as in the third version), we can create additional elements on the fly and add those elements to the matched set of elements. Let's say, for example, that we want to alter the background of the list items along with a newly created paragraph:

$('li').add('<p id="new">new paragraph</p>')
  .css('background-color', 'red');

Although the new paragraph has been created and its background color changed, it still does not appear on the page. To place it on the page, we could add one of the insertion methods to the chain.

As of jQuery 1.4 the results from .add() will always be returned in document order (rather than a simple concatenation).

Examples:

Example:

Finds all divs and makes a border. Then adds all paragraphs to the jQuery object to set their backgrounds yellow.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:60px; height:60px; margin:10px; float:left; }
 p { clear:left; font-weight:bold; font-size:16px;
     color:blue; margin:0 10px; padding:2px; }</style>
</head>
<body>
  <div></div>

  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>

  <p>Added this... (notice no border)</p>
  <script>$("div").css("border", "2px solid red")
        .add("p")
        .css("background", "yellow");</script>
</body>
</html>

Demo:

Example:

Adds more elements, matched by the given expression, to the set of matched elements.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>Hello</p><span>Hello Again</span>
  <script>$("p").add("span").css("background", "yellow");</script>
</body>
</html>

Demo:

Example:

Adds more elements, created on the fly, to the set of matched elements.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>Hello</p>
  <script>$("p").clone().add("<span>Again</span>").appendTo(document.body);</script>
</body>
</html>

Demo:

Example:

Adds one or more Elements to the set of matched elements.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>Hello</p><span id="a">Hello Again</span>
  <script>$("p").add(document.getElementById("a")).css("background", "yellow");</script>
</body>
</html>

Demo:

Example:

Demonstrates how to add (or push) elements to an existing collection
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>Hello</p><span id="a">Hello Again</span>
  <script>var collection = $("p");
// capture the new collection
collection = collection.add(document.getElementById("a"));
collection.css("background", "yellow");</script>
</body>
</html>

Demo:


Tree Traversal – jQuery API

Tree Traversal

  • jQuery .parentsUntil( [ Selector ] selector )

    New in 1.4 !

    Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.

  • jQuery .prevUntil( [ Selector ] selector )

    New in 1.4 !

    Get all preceding siblings of each element up to but not including the element matched by the selector.

  • jQuery .nextUntil( [ Selector ] selector )

    New in 1.4 !

    Get all following siblings of each element up to but not including the element matched by the selector.

  • jQuery .siblings( [ Selector ] selector )

    New in 1.0 !

    Get the siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .prevAll( [ Selector ] selector )

    New in 1.2 !

    Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .prev( [ Selector ] selector )

    New in 1.0 !

    Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .parents( [ Selector ] selector )

    New in 1.0 !

    Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

  • jQuery .parent( [ Selector ] selector )

    New in 1.0 !

    Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

  • jQuery .offsetParent( )

    New in 1.2.6 !

    Get the closest ancestor element that is positioned.

  • jQuery .nextAll( [ String ] selector )

    New in 1.2 !

    Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .next( [ Selector ] selector )

    New in 1.0 !

    Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

  • jQuery .find( [ Selector ] selector )

    New in 1.0 !

    Get the descendants of each element in the current set of matched elements, filtered by a selector.

  • Array .closest( [ Array ] selectors, [ Element ] context )

    New in 1.4 !

    Gets an array of all the elements and selectors matched against the current element up through the DOM tree.

  • jQuery .children( [ Selector ] selector )

    New in 1.0 !

    Get the children of each element in the set of matched elements, optionally filtered by a selector.


parentsUntil – jQuery API

Returns: jQueryjQuery .parentsUntil( [ Selector ] selector )

Categories: Tree Traversal, Version 1.4
Description: Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.
  • version added: 1.4
  • .parentsUntil( [ Selector ] selector )
  • selector A string containing a selector expression to indicate where to stop matching ancestor elements.

Given a jQuery object that represents a set of DOM elements, the method traverses through the ancestors of these elements until it reaches an element matched by the selector passed in the method's argument. The resulting jQuery object contains all of the ancestors up to but not including the one matched by the selector. Consider a page with a basic nested list as follows:

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

If we begin at item A, we can find its ancestors up to but not including as follows:

$('li.item-a').parentsUntil('.level-1')
    .css('background-color', 'red');

The result of this call is a red background for the level-2 list and the item II.

If the .parentsUntil() selector is not matched, or if no selector is supplied, the returned jQuery object contains all of the previous jQuery object's ancestors. For example, let's say we begin at item A again, but this time we use a selector that is not matched by any of its ancestors:

$('li.item-a').parentsUntil('.not-here')
    .css('background-color', 'red');

The result of this call is a red background-color style applied to the level-2 list, the item II, the level-1 list, the element, and the element.

Examples:

Example:

Find the ancestors of
  • up to
      and give them a red background color.
    • <!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>
  <script>$('li.item-a').parentsUntil('.level-1')
      .css('background-color', 'red');</script>
</body>
</html>

    Demo:


prevUntil – jQuery API

Returns: jQueryjQuery .prevUntil( [ Selector ] selector )

Categories: Tree Traversal, Version 1.4
Description: Get all preceding siblings of each element up to but not including the element matched by the selector.
  • version added: 1.4
  • .prevUntil( [ Selector ] selector )
  • selector A string containing a selector expression to indicate where to stop matching preceding sibling elements.

Given a jQuery object that represents a set of DOM elements, the method searches through the predecessors of these elements in the DOM tree, stopping when it reaches an element matched by the method's argument. The new jQuery object that is returned contains all previous siblings up to but not including the one matched by the selector; the elements are returned in order from the closest sibling to the farthest.

If the selector is not matched or is not supplied, all previous siblings will be selected; in these cases it selects the same elements as the method does when no filter selector is provided.

Consider a page with a simple definition list as follows:

<dl>
  <dt>term 1</dt>
  <dd>definition 1-a</dd>
  <dd>definition 1-b</dd>
  <dd>definition 1-c</dd>
  <dd>definition 1-d</dd>

  <dt id="term-2">term 2</dt>
  <dd>definition 2-a</dd>
  <dd>definition 2-b</dd>
  <dd>definition 2-c</dd>

  <dt>term 3</dt>
  <dd>definition 3-a</dd>
  <dd>definition 3-b</dd>
</dl>

If we begin at the second term, we can find the elements which come after it until a preceding .

$('#term-2').prevUntil('dt').css('background-color', 'red');

The result of this call is a red background behind definitions , , , and .

Examples:

Example:

Find the siblings that precede
up to the preceding
and give them a red background color.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <dl>
  <dt>term 1</dt>
  <dd>definition 1-a</dd>
  <dd>definition 1-b</dd>
  <dd>definition 1-c</dd>
  <dd>definition 1-d</dd>

  <dt id="term-2">term 2</dt>
  <dd>definition 2-a</dd>
  <dd>definition 2-b</dd>
  <dd>definition 2-c</dd>

  <dt>term 3</dt>
  <dd>definition 3-a</dd>
  <dd>definition 3-b</dd>
</dl>
  <script>$("#term-2").prevUntil("dt")
      .css("background-color", "red")</script>
</body>
</html>

Demo:


nextUntil – jQuery API

Returns: jQueryjQuery .nextUntil( [ Selector ] selector )

Categories: Tree Traversal, Version 1.4
Description: Get all following siblings of each element up to but not including the element matched by the selector.
  • version added: 1.4
  • .nextUntil( [ Selector ] selector )
  • selector A string containing a selector expression to indicate where to stop matching following sibling elements.

Given a jQuery object that represents a set of DOM elements, the method allows us to search through the successors of these elements in the DOM tree, stopping when it reaches an element matched by the method's argument. The new jQuery object that is returned contains all following siblings up to but not including the one matched by the selector.

If the selector is not matched or is not supplied, all following siblings will be selected; in these cases it selects the same elements as the method does when no filter selector is provided.

Consider a page with a simple definition list as follows:

<dl>
  <dt>term 1</dt>
  <dd>definition 1-a</dd>
  <dd>definition 1-b</dd>
  <dd>definition 1-c</dd>
  <dd>definition 1-d</dd>

  <dt id="term-2">term 2</dt>
  <dd>definition 2-a</dd>
  <dd>definition 2-b</dd>
  <dd>definition 2-c</dd>

  <dt>term 3</dt>
  <dd>definition 3-a</dd>
  <dd>definition 3-b</dd>
</dl>

If we begin at the second term, we can find the elements which come after it until a following .

$('#term-2').nextUntil('dt').css('background-color', 'red');

The result of this call is a red background behind definitions , , and .

Examples:

Example:

Find the siblings that follow
up to the next
and give them a red background color.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <dl>
  <dt>term 1</dt>
  <dd>definition 1-a</dd>
  <dd>definition 1-b</dd>
  <dd>definition 1-c</dd>
  <dd>definition 1-d</dd>

  <dt id="term-2">term 2</dt>
  <dd>definition 2-a</dd>
  <dd>definition 2-b</dd>
  <dd>definition 2-c</dd>

  <dt>term 3</dt>
  <dd>definition 3-a</dd>
  <dd>definition 3-b</dd>
</dl>
  <script>$("#term-2").nextUntil("dt")
      .css("background-color", "red")</script>
</body>
</html>

Demo:


siblings – jQuery API

Returns: jQueryjQuery .siblings( [ Selector ] selector )

Categories: Tree Traversal, Version 1.0
Description: Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
  • version added: 1.0
  • .siblings( [ Selector ] selector )
  • selector A string containing a selector expression to match elements against.

Given a jQuery object that represents a set of DOM elements, the method allows us to search through the siblings of these elements in the DOM tree and construct a new jQuery object from the matching elements.

The method optionally accepts a selector expression of the same type that we can pass to the function. If the selector is supplied, the elements will be filtered by testing whether they match it.

Consider a page with a simple list on it:

<ul>
   <li>list item 1</li>
   <li>list item 2</li>
   <li class="third-item">list item 3</li>
   <li>list item 4</li>
   <li>list item 5</li>
</ul>

If we begin at the third item, we can find its siblings:

$('li.third-item').siblings().css('background-color', 'red');

The result of this call is a red background behind items 1, 2, 4, and 5. Since we do not supply a selector expression, all of the siblings are part of the object. If we had supplied one, only the matching items among these four would be included.

The original element is not included among the siblings, which is important to remember when we wish to find all elements at a particular level of the DOM tree.

Examples:

Example:

Find the unique siblings of all yellow li elements in the 3 lists (including other yellow li elements if appropriate).
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>ul { float:left; margin:5px; font-size:16px; font-weight:bold; }
  p { color:blue; margin:10px 20px; font-size:16px; padding:5px;
      font-weight:bolder; }
  .hilite { background:yellow; }</style>
</head>
<body>
  <ul>
    <li>One</li>

    <li>Two</li>
    <li class="hilite">Three</li>
    <li>Four</li>
  </ul>

  <ul>
    <li>Five</li>
    <li>Six</li>
    <li>Seven</li>

  </ul>
  <ul>
    <li>Eight</li>
    <li class="hilite">Nine</li>

    <li>Ten</li>
    <li class="hilite">Eleven</li>
  </ul>
  <p>Unique siblings: <b></b></p>
  <script>var len = $(".hilite").siblings()
                          .css("color", "red")
                          .length;
    $("b").text(len);</script>
</body>
</html>

Demo:

Example:

Find all siblings with a class "selected" of each div.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <div><span>Hello</span></div>

  <p class="selected">Hello Again</p>
  <p>And Again</p>
  <script>$("p").siblings(".selected").css("background", "yellow");</script>
</body>
</html>

Demo:


prevAll – jQuery API

Returns: jQueryjQuery .prevAll( [ Selector ] selector )

Categories: Tree Traversal, Version 1.2
Description: Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.
  • version added: 1.2
  • .prevAll( [ Selector ] selector )
  • selector A string containing a selector expression to match elements against.

Given a jQuery object that represents a set of DOM elements, the method searches through the predecessors of these elements in the DOM tree and construct a new jQuery object from the matching elements; the elements are returned in order beginning with the closest sibling.

The method optionally accepts a selector expression of the same type that we can pass to the function. If the selector is supplied, the elements will be filtered by testing whether they match it.

Consider a page with a simple list on it:

<ul>
   <li>list item 1</li>
   <li>list item 2</li>
   <li class="third-item">list item 3</li>
   <li>list item 4</li>
   <li>list item 5</li>
</ul>

If we begin at the third item, we can find the elements which come before it:

$('li.third-item').prevAll().css('background-color', 'red');

The result of this call is a red background behind items 1 and 2. Since we do not supply a selector expression, these preceding elements are unequivocally included as part of the object. If we had supplied one, the elements would be tested for a match before they were included.

Examples:

Example:

Locate all the divs preceding the last div and give them a class.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:70px; height:70px; background:#abc;
        border:2px solid black; margin:10px; float:left; }
  div.before { border-color: red; }</style>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <script>$("div:last").prevAll().addClass("before");</script>
</body>
</html>

Demo:


prev – jQuery API

Returns: jQueryjQuery .prev( [ Selector ] selector )

Categories: Tree Traversal, Version 1.0
Description: Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
  • version added: 1.0
  • .prev( [ Selector ] selector )
  • selector A string containing a selector expression to match elements against.

Given a jQuery object that represents a set of DOM elements, the method allows us to search through the predecessors of these elements in the DOM tree and construct a new jQuery object from the matching elements.

The method optionally accepts a selector expression of the same type that we can pass to the function. If the selector is supplied, the elements will be filtered by testing whether they match it.

Consider a page with a simple list on it:

<ul>
   <li>list item 1</li>
   <li>list item 2</li>
   <li class="third-item">list item 3</li>
   <li>list item 4</li>
   <li>list item 5</li>
</ul>

If we begin at the third item, we can find the element which comes just before it:

$('li.third-item').prev().css('background-color', 'red');

The result of this call is a red background behind item 2. Since we do not supply a selector expression, this preceding element is unequivocally included as part of the object. If we had supplied one, the element would be tested for a match before it was included.

Examples:

Example:

Find the very previous sibling of each div.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width:40px; height:40px; margin:10px;
        float:left; border:2px blue solid;
        padding:2px; }
  span { font-size:14px; }
  p { clear:left; margin:10px; }</style>
</head>
<body>
  <div></div>
  <div></div>
  <div><span>has child</span></div>

  <div></div>
  <div></div>
  <div></div>
  <div id="start"></div>

  <div></div>
  <p><button>Go to Prev</button></p>
  <script>var $curr = $("#start");
    $curr.css("background", "#f99");
    $("button").click(function () {
      $curr = $curr.prev();
      $("div").css("background", "");
      $curr.css("background", "#f99");
    });</script>
</body>
</html>

Demo:

Example:

For each paragraph, find the very previous sibling that has a class "selected".
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <div><span>Hello</span></div>

  <p class="selected">Hello Again</p>
  <p>And Again</p>
  <script>$("p").prev(".selected").css("background", "yellow");</script>
</body>
</html>

Demo:


parents – jQuery API

Returns: jQueryjQuery .parents( [ Selector ] selector )

Categories: Tree Traversal, Version 1.0
Description: Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
  • version added: 1.0
  • .parents( [ Selector ] selector )
  • selector A string containing a selector expression to match elements against.

Given a jQuery object that represents a set of DOM elements, the method allows us to search through the ancestors of these elements in the DOM tree and construct a new jQuery object from the matching elements ordered from immediate parent on up; the elements are returned in order from the closest parent to the outer ones. The and methods are similar, except that the latter only travels a single level up the DOM tree.

The method optionally accepts a selector expression of the same type that we can pass to the function. If the selector is supplied, the elements will be filtered by testing whether they match it.

Consider a page with a basic nested list on it:

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

If we begin at item A, we can find its ancestors:

$('li.item-a').parents().css('background-color', 'red');

The result of this call is a red background for the level-2 list, item II, and the level-1 list (and on up the DOM tree all the way to the element). Since we do not supply a selector expression, all of the ancestors are part of the returned jQuery object. If we had supplied one, only the matching items among these would be included.

Examples:

Example:

Find all parent elements of each b.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>b, span, p, html body {
    padding: .5em;
    border: 1px solid;
  }
  b { color:blue; }
  strong { color:red; }</style>
</head>
<body>
  <div>
    <p>
      <span>
        <b>My parents are: </b>
      </span>

    </p>
  </div>
  <script>var parentEls = $("b").parents()
            .map(function () {
                  return this.tagName;
                })
            .get().join(", ");
$("b").append("<strong>" + parentEls + "</strong>");</script>
</body>
</html>

Demo:

Example:

Click to find all unique div parent elements of each span.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p, div, span {margin:2px; padding:1px; }
  div { border:2px white solid; }
  span { cursor:pointer; font-size:12px; }
  .selected { color:blue; }
  b { color:red; display:block; font-size:14px; }</style>
</head>
<body>
  <p>
    <div>
      <div><span>Hello</span></div>
      <span>Hello Again</span>

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

  <b>Click Hellos to toggle their parents.</b>
  <script>function showParents() {
  $("div").css("border-color", "white");
  var len = $("span.selected")
                   .parents("div")
                   .css("border", "2px red solid")
                   .length;
  $("b").text("Unique div parents: " + len);
}
$("span").click(function () {
  $(this).toggleClass("selected");
  showParents();
});</script>
</body>
</html>

Demo:


nextAll – jQuery API

Returns: jQueryjQuery .nextAll( [ String ] selector )

Categories: Tree Traversal, Version 1.2
Description: Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.
  • version added: 1.2
  • .nextAll( [ String ] selector )
  • selector A string containing a selector expression to match elements against.

Given a jQuery object that represents a set of DOM elements, the method allows us to search through the successors of these elements in the DOM tree and construct a new jQuery object from the matching elements.

The method optionally accepts a selector expression of the same type that we can pass to the function. If the selector is supplied, the elements will be filtered by testing whether they match it.

Consider a page with a simple list on it:

<ul>
   <li>list item 1</li>
   <li>list item 2</li>
   <li class="third-item">list item 3</li>
   <li>list item 4</li>
   <li>list item 5</li>
</ul>

If we begin at the third item, we can find the elements which come after it:

$('li.third-item').nextAll().css('background-color', 'red');

The result of this call is a red background behind items 4 and 5. Since we do not supply a selector expression, these following elements are unequivocally included as part of the object. If we had supplied one, the elements would be tested for a match before they were included.

Examples:

Example:

Locate all the divs after the first and give them a class.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { width: 80px; height: 80px; background: #abc;
        border: 2px solid black; margin: 10px; float: left; }
  div.after { border-color: red; }</style>
</head>
<body>
  <div>first</div>
  <div>sibling<div>child</div></div>
  <div>sibling</div>

  <div>sibling</div>
  <script>$("div:first").nextAll().addClass("after");</script>
</body>
</html>

Demo:

Example:

Locate all the paragraphs after the second child in the body and give them a class.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div, p { width: 60px; height: 60px; background: #abc;
           border: 2px solid black; margin: 10px; float: left; }
  .after { border-color: red; }</style>
</head>
<body>
  <p>p</p>

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

  <p>p</p>
  <div>div</div>
  <script>$(":nth-child(1)").nextAll("p").addClass("after");</script>
</body>
</html>

Demo:


next – jQuery API

Returns: jQueryjQuery .next( [ Selector ] selector )

Categories: Tree Traversal, Version 1.0
Description: Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
  • version added: 1.0
  • .next( [ Selector ] selector )
  • selector A string containing a selector expression to match elements against.

Given a jQuery object that represents a set of DOM elements, the method allows us to search through the immediately following sibling of these elements in the DOM tree and construct a new jQuery object from the matching elements.

The method optionally accepts a selector expression of the same type that we can pass to the function. If the immediately following sibling matches the selector, it remains in the newly constructed jQuery object; otherwise, it is excluded.

Consider a page with a simple list on it:

<ul>
   <li>list item 1</li>
   <li>list item 2</li>
   <li class="third-item">list item 3</li>
   <li>list item 4</li>
   <li>list item 5</li>
</ul>

If we begin at the third item, we can find the element which comes just after it:

$('li.third-item').next().css('background-color', 'red');

The result of this call is a red background behind item 4. Since we do not supply a selector expression, this following element is unequivocally included as part of the object. If we had supplied one, the element would be tested for a match before it was included.

Examples:

Example:

Find the very next sibling of each disabled button and change its text "this button is disabled".
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>span { color:blue; font-weight:bold; }
  button { width:100px; }</style>
</head>
<body>
  <div><button disabled="disabled">First</button> - <span></span></div>
  <div><button>Second</button> - <span></span></div>

  <div><button disabled="disabled">Third</button> - <span></span></div>
  <script>$("button[disabled]").next().text("this button is disabled");</script>
</body>
</html>

Demo:

Example:

Find the very next sibling of each paragraph. Keep only the ones with a class "selected".
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p>Hello</p>

  <p class="selected">Hello Again</p>
  <div><span>And Again</span></div>
  <script>$("p").next(".selected").css("background", "yellow");</script>
</body>
</html>

Demo:


find – jQuery API

Returns: jQueryjQuery .find( [ Selector ] selector )

Categories: Tree Traversal, Version 1.0
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector.
  • version added: 1.0
  • .find( [ Selector ] selector )
  • selector A string containing a selector expression to match elements against.

Given a jQuery object that represents a set of DOM elements, the method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The and methods are similar, except that the latter only travels a single level down the DOM tree.

The method accepts a selector expression of the same type that we can pass to the function. The elements will be filtered by testing whether they match this selector.

Consider a page with a basic nested list on it:

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

If we begin at item II, we can find list items within it:

$('li.item-ii').find('li').css('background-color', 'red');

The result of this call is a red background on items A, B, 1, 2, 3, and C. Even though item II matches the selector expression, it is not included in the results; only descendants are considered candidates for the match.

is implemented with the therefore, is equivalent to .

Examples:

Example:

Starts with all paragraphs and searches for descendant span elements, same as $("p span")
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <p><span>Hello</span>, how are you?</p>
<p>Me? I'm <span>good</span>.</p>
  <script>$("p").find("span").css('color','red');</script>
</body>
</html>

Demo:

Example:

Add spans around each word then add a hover and italicize words with the letter .
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { font-size:20px; width:200px; cursor:default;
      color:blue; font-weight:bold; margin:0 10px; }
  .hilite { background:yellow; }</style>
</head>
<body>
  <p>
  When the day is short
  find that which matters to you
  or stop believing
  </p>
  <script>var newText = $("p").text().split(" ").join("</span> <span>");
  newText = "<span>" + newText + "</span>";

  $("p").html(newText)
    .find('span')
    .hover(function() {
      $(this).addClass("hilite");
    },
      function() { $(this).removeClass("hilite");
    })
  .end()
    .find(":contains('t')")
    .css({"font-style":"italic", "font-weight":"bolder"});</script>
</body>
</html>

Demo:


closest – jQuery API

  • closest ( [ Selector ] selector )

    • 1.3closest ( [ Selector ] selector )
    • 1.4closest ( [ Selector ] selector, [ Element ] context )

  • closest ( [ Array ] selectors, [ Element ] context )

    • 1.4closest ( [ Array ] selectors, [ Element ] context )

Returns: jQueryjQuery .closest( [ Selector ] selector, [ Element ] context )

Categories: Tree Traversal, Version 1.3, Version 1.4
Description: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.
  • version added: 1.3
  • .closest( [ Selector ] selector )
  • selector A string containing a selector expression to match elements against.
  • version added: 1.4
  • .closest( [ Selector ] selector, [ Element ] context )
  • selector A string containing a selector expression to match elements against.
  • context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.

Given a jQuery object that represents a set of DOM elements, the method allows us to search through these elements and their ancestors in the DOM tree and construct a new jQuery object from the matching elements. The and methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:

  <ul id="one" class="level-1">
    <li class="item-i">I</li>
    <li id="ii" class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

Suppose we perform a search for elements starting at item A:

$('li.item-a').closest('ul')
  .css('background-color', 'red');

This will change the color of the level-2 , since it is the first encountered when traveling up the DOM tree.

Suppose we search for an element instead:

$('li.item-a').closest('li')
  .css('background-color', 'red');

This will change the color of list item A. The method begins its search with the element itself before progressing up the DOM tree, and stops when item A matches the selector.

We can pass in a DOM element as the context within which to search for the closest element.

var listItemII = document.getElementById('ii');
$('li.item-a').closest('ul', listItemII)
  .css('background-color', 'red');
$('li.item-a').closest('#one', listItemII)
  .css('background-color', 'green');

This will change the color of the level-2 , because it is both the first ancestor of list item A and a descendant of list item II. It will not change the color of the level-1 , however, because it is not a descendant of list item II.

Examples:

Example:

Show how event delegation can be done with closest.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>li { margin: 3px; padding: 3px; background: #EEEEEE; }
  li.hilight { background: yellow; }</style>
</head>
<body>
  <ul>
<li><b>Click me!</b></li>
<li>You can also <b>Click me!</b></li>
</ul>
  <script>$(document).bind("click", function (e) {
      $(e.target).closest("li").toggleClass("hilight");
    });</script>
</body>
</html>

Demo:

Returns: ArrayArray .closest( [ Array ] selectors, [ Element ] context )

Categories: Tree Traversal, Version 1.3, Version 1.4
Description: Gets an array of all the elements and selectors matched against the current element up through the DOM tree.
  • version added: 1.4
  • .closest( [ Array ] selectors, [ Element ] context )
  • selectors An array or string containing a selector expression to match elements against (can also be a jQuery object).
  • context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.

This method is primarily meant to be used internally or by plugin authors.

Examples:

Example:

Show how event delegation can be done with closest.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <ul><li></li><li></li></ul>
  <script>var close = $("li:first").closest(["ul", "body"]);
        $.each(close, function(i){
  $("li").eq(i).html( this.selector + ": " + this.elem.nodeName );
});</script>
</body>
</html>

Demo:


children – jQuery API

Returns: jQueryjQuery .children( [ Selector ] selector )

Categories: Tree Traversal, Version 1.0
Description: Get the children of each element in the set of matched elements, optionally filtered by a selector.
  • version added: 1.0
  • .children( [ Selector ] selector )
  • selector A string containing a selector expression to match elements against.

Given a jQuery object that represents a set of DOM elements, the method allows us to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The and methods are similar, except that the latter only travels a single level down the DOM tree. Note also that like most jQuery methods, does not return text nodes; to get children including text and comment nodes, use .

The method optionally accepts a selector expression of the same type that we can pass to the function. If the selector is supplied, the elements will be filtered by testing whether they match it.

Consider a page with a basic nested list on it:

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

If we begin at the level-2 list, we can find its children:

$('ul.level-2').children().css('background-color', 'red');

The result of this call is a red background behind items A, B, and C. Since we do not supply a selector expression, all of the children are part of the returned jQuery object. If we had supplied one, only the matching items among these three would be included.

Examples:

Example:

Find all children of the clicked element.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { font-size:16px; font-weight:bolder; }
  div { width:130px; height:82px; margin:10px; float:left;
        border:1px solid blue; padding:4px; }
  #container { width:auto; height:105px; margin:0; float:none;
        border:none; }
  .hilite { border-color:red; }
  #results { display:block; color:red; }
  p { margin:10px; border:1px solid transparent; }
  span { color:blue; border:1px solid transparent; }
  input { width:100px; }
  em { border:1px solid transparent; }
  a { border:1px solid transparent; }
  b { border:1px solid transparent; }
  button { border:1px solid transparent; }</style>
</head>
<body>
  <div id="container">

    <div>
      <p>This <span>is the <em>way</em> we</span>
      write <em>the</em> demo,</p>

    </div>
    <div>
      <a href="#"><b>w</b>rit<b>e</b></a> the <span>demo,</span> <button>write
      the</button> demo,
    </div>

    <div>
      This <span>the way we <em>write</em> the <em>demo</em> so</span>

      <input type="text" value="early" /> in
    </div>
    <p>
      <span>t</span>he <span>m</span>orning.
      <span id="results">Found <span>0</span> children in <span>TAG</span>.</span>

    </p>
  </div>
  <script>$("#container").click(function (e) {
      $("*").removeClass("hilite");
      var $kids = $(e.target).children();
      var len = $kids.addClass("hilite").length;

      $("#results span:first").text(len);
      $("#results span:last").text(e.target.tagName);

      e.preventDefault();
      return false;
    });</script>
</body>
</html>

Demo:

Example:

Find all children of each div.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { font-size:16px; font-weight:bolder; }
  span { color:blue; }
  p { margin:5px 0; }</style>
</head>
<body>
  <p>Hello (this is a paragraph)</p>

  <div><span>Hello Again (this span is a child of the a div)</span></div>
  <p>And <span>Again</span> (in another paragraph)</p>

  <div>And One Last <span>Time</span> (most text directly in a div)</div>
  <script>$("div").children().css("border-bottom", "3px double red");</script>
</body>
</html>

Demo:

Example:

Find all children with a class "selected" of each div.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>body { font-size:16px; font-weight:bolder; }
  p { margin:5px 0; }</style>
</head>
<body>
  <div>
    <span>Hello</span>
    <p class="selected">Hello Again</p>
    <div class="selected">And Again</div>

    <p>And One Last Time</p>
  </div>
  <script>$("div").children(".selected").css("color", "blue");</script>
</body>
</html>

Demo:


Utilities – jQuery API

Utilities

  • Number jQuery.now( )

    New in 1.4.3 !

    Return a number representing the current time.

  • XMLDocument jQuery.parseXML( [ String ] data )

    New in 1.5 !

    Parses a string into an XML document.

  • String jQuery.type( [ Object ] obj )

    New in 1.4.3 !

    Determine the internal JavaScript [[Class]] of an object.

  • boolean jQuery.isWindow( [ Object ] obj )

    New in 1.4.3 !

    Determine whether the argument is a window.

  • Object jQuery.parseJSON( [ String ] json )

    New in 1.4.1 !

    Takes a well-formed JSON string and returns the resulting JavaScript object.

  • Function jQuery.proxy( [ Object ] context, [ String ] name )

    New in 1.4 !

    Takes a function and returns a new one that will always have a particular context.

  • Boolean jQuery.contains( [ Element ] container, [ Element ] contained )

    New in 1.4 !

    Check to see if a DOM node is within another DOM node.

  • Function jQuery.noop( )

    New in 1.4 !

    An empty function.

  • jQuery.globalEval( [ String ] code )

    New in 1.0.4 !

    Execute some JavaScript code globally.

  • Boolean jQuery.isXMLDoc( [ Element ] node )

    New in 1.1.4 !

    Check to see if a DOM node is within an XML document (or is an XML document).

  • jQuery jQuery.removeData( [ Element ] element, [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery jQuery.dequeue( [ Element ] element, [ String ] queueName )

    New in 1.3 !

    Execute the next function on the queue for the matched element.

  • jQuery jQuery.queue( [ Element ] element, [ String ] queueName, [ Function ] callback() )

    New in 1.3 !

    Manipulate the queue of functions to be executed on the matched element.

  • jQuery .clearQueue( [ String ] queueName )

    New in 1.4 !

    Remove from the queue all items that have not yet been run.

  • Boolean jQuery.isEmptyObject( [ Object ] object )

    New in 1.4 !

    Check to see if an object is empty (contains no properties).

  • Boolean jQuery.isPlainObject( [ Object ] object )

    New in 1.4 !

    Check to see if an object is a plain object (created using "{}" or "new Object").

  • jQuery .dequeue( [ String ] queueName )

    New in 1.2 !

    Execute the next function on the queue for the matched elements.

  • jQuery .queue( [ String ] queueName, [ Function ] callback( next ) )

    New in 1.2 !

    Manipulate the queue of functions to be executed on the matched elements.

  • Map jQuery.browser

    New in 1.0 !

    Contains flags for the useragent, read from navigator.userAgent.

  • String jQuery.browser.version

    New in 1.1.3 !

    The version number of the rendering engine for the user's browser.

  • String jQuery.trim( [ String ] str )

    New in 1.0 !

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

  • boolean jQuery.isFunction( [ Object ] obj )

    New in 1.2 !

    Determine if the argument passed is a Javascript function object.

  • boolean jQuery.isArray( [ Object ] obj )

    New in 1.3 !

    Determine whether the argument is an array.

  • Array jQuery.unique( [ Array ] array )

    New in 1.1.3 !

    Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.

  • Array jQuery.merge( [ Array ] first, [ Array ] second )

    New in 1.0 !

    Merge the contents of two arrays together into the first array.

  • Number jQuery.inArray( [ Any ] value, [ Array ] array )

    New in 1.2 !

    Search for a specified value within an array and return its index (or -1 if not found).

  • Array jQuery.map( [ Array ] array, [ Function ] callback(elementOfArray, indexInArray) )

    New in 1.0 !

    Translate all items in an array or array-like object to another array of items.

  • Array jQuery.makeArray( [ Object ] obj )

    New in 1.2 !

    Convert an array-like object into a true JavaScript array.

  • Array jQuery.grep( [ Array ] array, [ Function ] function(elementOfArray, indexInArray), [ Boolean ] invert )

    New in 1.0 !

    Finds the elements of an array which satisfy a filter function. The original array is not affected.

  • Object jQuery.extend( [ Boolean ] deep, [ Object ] target, [ Object ] object1, [ Object ] objectN )

    New in 1.1.4 !

    Merge the contents of two or more objects together into the first object.

  • Object jQuery.each( [ Object ] collection, [ Function ] callback(indexInArray, valueOfElement) )

    New in 1.0 !

    A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

  • Boolean jQuery.boxModel

    New in 1.0 !

    . States if the current page, in the user's browser, is being rendered using the .

  • Object jQuery.support

    New in 1.3 !

    A collection of properties that represent the presence of different browser features or bugs.


jQuery.now – jQuery API

Returns: NumberNumber jQuery.now( )

Categories: Utilities, Version 1.4.3
Description: Return a number representing the current time.
  • version added: 1.4.3
  • jQuery.now( )

The method is a shorthand for the number returned by the expression .

Examples:


jQuery.parseXML – jQuery API

Returns: XMLDocumentXMLDocument jQuery.parseXML( [ String ] data )

Categories: Utilities, Version 1.5
Description: Parses a string into an XML document.
  • version added: 1.5
  • jQuery.parseXML( [ String ] data )
  • data a well-formed XML string to be parsed

uses the native parsing function of the browser to create a valid XML Document. This document can then be passed to to create a typical jQuery object that can be traversed and manipulated.

Examples:

Example:

Create a jQuery object using an XML string and obtain the value of the title node.
var xml = '<rss version="2.0"><channel><title>RSS Title</title></channel></rss>',
    xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc ),
    $title = $xml.find( 'title' );

// append "RSS Title" to #someElement
$( '#someElement' ).append( $title.text() );

// change the title to "XML Title"
$title.text( 'XML Title' );

// append "XML Title" to #anotherElement
$( '#anotherElement' ).append( $title.text() );


jQuery.type – jQuery API

Returns: StringString jQuery.type( [ Object ] obj )

Categories: Utilities, Version 1.4.3
Description: Determine the internal JavaScript [[Class]] of an object.
  • version added: 1.4.3
  • jQuery.type( [ Object ] obj )
  • obj Object to get the internal JavaScript [[Class]] of.

A number of techniques are used to determine the exact return value for an object. The [[Class]] is determined as follows:

Examples:

Example:

Find out if the parameter is a RegExp.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  Is it a RegExp? <b></b>
  <script>$("b").append( "" + jQuery.type(/test/) );</script>
</body>
</html>

Demo:


jQuery.isWindow – jQuery API

Returns: booleanboolean jQuery.isWindow( [ Object ] obj )

Categories: Utilities, Version 1.4.3
Description: Determine whether the argument is a window.
  • version added: 1.4.3
  • jQuery.isWindow( [ Object ] obj )
  • obj Object to test whether or not it is a window.

This is used in a number of places in jQuery to determine if we're operating against a browser window (such as the current window or an iframe).

Examples:

Example:

Finds out if the parameter is a window.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  Is 'window' a window? <b></b>
  <script>$("b").append( "" + $.isWindow(window) );</script>
</body>
</html>

Demo:


jQuery.parseJSON – jQuery API

Returns: ObjectObject jQuery.parseJSON( [ String ] json )

Categories: Utilities, Version 1.4.1
Description: Takes a well-formed JSON string and returns the resulting JavaScript object.
  • version added: 1.4.1
  • jQuery.parseJSON( [ String ] json )
  • json The JSON string to parse.

Passing in a malformed JSON string may result in an exception being thrown. For example, the following are all malformed JSON strings:

Additionally if you pass in nothing, an empty string, null, or undefined, 'null' will be returned from parseJSON. Where the browser provides a native implementation of , jQuery uses it to parse the string. For details on the JSON format, see .

Examples:

Example:

Parse a JSON string.
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );


jQuery.contains – jQuery API

Returns: BooleanBoolean jQuery.contains( [ Element ] container, [ Element ] contained )

Categories: Utilities, Version 1.4
Description: Check to see if a DOM node is within another DOM node.
  • version added: 1.4
  • jQuery.contains( [ Element ] container, [ Element ] contained )
  • container The DOM element that may contain the other element.
  • contained The DOM node that may be contained by the other element.

Examples:

Example:

Check if an element is inside another.
jQuery.contains(document.documentElement, document.body); // true
jQuery.contains(document.body, document.documentElement); // false


jQuery.noop – jQuery API

Returns: FunctionFunction jQuery.noop( )

Categories: Utilities, Version 1.4
Description: An empty function.
  • version added: 1.4
  • jQuery.noop( )

You can use this empty function when you wish to pass around a function that will do nothing.

This is useful for plugin authors who offer optional callbacks; in the case that no callback is given, something like could execute.

Examples:


jQuery.globalEval – jQuery API

Returns: jQuery.globalEval( [ String ] code )

Categories: Utilities, Version 1.0.4
Description: Execute some JavaScript code globally.
  • version added: 1.0.4
  • jQuery.globalEval( [ String ] code )
  • code The JavaScript code to execute.

This method behaves differently from using a normal JavaScript in that it's executed within the global context (which is important for loading external scripts dynamically).

Examples:

Example:

Execute a script in the global context.
function test(){
    jQuery.globalEval("var newVar = true;")
}
test();
// newVar === true

© 2010 The jQuery Project


jQuery.isXMLDoc – jQuery API

Returns: BooleanBoolean jQuery.isXMLDoc( [ Element ] node )

Categories: Utilities, Version 1.1.4
Description: Check to see if a DOM node is within an XML document (or is an XML document).
  • version added: 1.1.4
  • jQuery.isXMLDoc( [ Element ] node )
  • node The DOM node that will be checked to see if it's in an XML document.

Examples:

Example:

Check an object to see if it's in an XML document.
jQuery.isXMLDoc(document) // false
jQuery.isXMLDoc(document.body) // false


jQuery.isEmptyObject – jQuery API

Returns: BooleanBoolean jQuery.isEmptyObject( [ Object ] object )

Categories: Utilities, Version 1.4
Description: Check to see if an object is empty (contains no properties).
  • version added: 1.4
  • jQuery.isEmptyObject( [ Object ] object )
  • object The object that will be checked to see if it's empty.

As of jQuery 1.4 this method checks both properties on the object itself and properties inherited from prototypes (in that it doesn't use hasOwnProperty).

Examples:

Example:

Check an object to see if it's empty.
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false


jQuery.isPlainObject – jQuery API

Returns: BooleanBoolean jQuery.isPlainObject( [ Object ] object )

Categories: Utilities, Version 1.4
Description: Check to see if an object is a plain object (created using "{}" or "new Object").
  • version added: 1.4
  • jQuery.isPlainObject( [ Object ] object )
  • object The object that will be checked to see if it's a plain object.

Examples:

Example:

Check an object to see if it's a plain object.
jQuery.isPlainObject({}) // true
jQuery.isPlainObject("test") // false


jQuery.trim – jQuery API

Returns: StringString jQuery.trim( [ String ] str )

Categories: Utilities, Version 1.0
Description: Remove the whitespace from the beginning and end of a string.
  • version added: 1.0
  • jQuery.trim( [ String ] str )
  • str The string to trim.

The function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.

Examples:

Example:

Remove the two white spaces at the start and at the end of the string.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  <button>Show Trim Example</button>
  <script>$("button").click(function () {
var str = "     lots of spaces before and after     ";
alert("'" + str + "'");

str = jQuery.trim(str);
alert("'" + str + "' - no longer");
});</script>
</body>
</html>

Demo:

Example:

Remove the two white spaces at the start and at the end of the string.
$.trim("  hello, how are you?  ");


jQuery.isFunction – jQuery API

Returns: booleanboolean jQuery.isFunction( [ Object ] obj )

Categories: Utilities, Version 1.2
Description: Determine if the argument passed is a Javascript function object.
  • version added: 1.2
  • jQuery.isFunction( [ Object ] obj )
  • obj Object to test whether or not it is a function.

As of jQuery 1.3, functions provided by the browser like and DOM element methods like are not guaranteed to be detected as functions in browsers such as Internet Explorer.

Examples:

Example:

Test a few parameter examples.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:blue; margin:2px; font-size:14px; }
  span { color:red; }</style>
</head>
<body>

  <div>jQuery.isFunction(objs[0]) = <span></span></div>

  <div>jQuery.isFunction(objs[1]) = <span></span></div>
  <div>jQuery.isFunction(objs[2]) = <span></span></div>
  <div>jQuery.isFunction(objs[3]) = <span></span></div>

  <div>jQuery.isFunction(objs[4]) = <span></span></div>

  <script>function stub() {
    }
    var objs = [
          function () {},
          { x:15, y:20 },
          null,
          stub,
          "function"
        ];

    jQuery.each(objs, function (i) {
      var isFunc = jQuery.isFunction(objs[i]);
      $("span").eq(i).text(isFunc);
    });</script>
</body>
</html>

Demo:

Example:

Finds out if the parameter is a funcion.
$.isFunction(function(){});


jQuery.isArray – jQuery API

Returns: booleanboolean jQuery.isArray( [ Object ] obj )

Categories: Utilities, Version 1.3
Description: Determine whether the argument is an array.
  • version added: 1.3
  • jQuery.isArray( [ Object ] obj )
  • obj Object to test whether or not it is an array.

returns a Boolean indicating whether the object is a JavaScript array (not an array-like object, such as a jQuery object).

Examples:

Example:

Finds out if the parameter is an array.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  Is [] an Array? <b></b>
  <script>$("b").append( "" + $.isArray([]) );</script>
</body>
</html>

Demo:


jQuery.unique – jQuery API

Returns: ArrayArray jQuery.unique( [ Array ] array )

Categories: Utilities, Version 1.1.3
Description: Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.
  • version added: 1.1.3
  • jQuery.unique( [ Array ] array )
  • array The Array of DOM elements.

The function searches through an array of objects, sorting the array, and removing any duplicate nodes. This function only works on plain JavaScript arrays of DOM elements, and is chiefly used internally by jQuery.

As of jQuery 1.4 the results will always be returned in document order.

Examples:

Example:

Removes any duplicate elements from the array of divs.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:blue; }</style>
</head>
<body>
  <div>There are 6 divs in this document.</div>
  <div></div>
  <div class="dup"></div>
  <div class="dup"></div>

  <div class="dup"></div>
  <div></div>
  <script>var divs = $("div").get(); // unique() must take a native array

    // add 3 elements of class dup too (they are divs)
    divs = divs.concat($(".dup").get());
    $("div:eq(1)").text("Pre-unique there are " + divs.length + " elements.");

    divs = jQuery.unique(divs);
    $("div:eq(2)").text("Post-unique there are " + divs.length + " elements.")
                  .css("color", "red");</script>
</body>
</html>

Demo:


jQuery.merge – jQuery API

Returns: ArrayArray jQuery.merge( [ Array ] first, [ Array ] second )

Categories: Utilities, Version 1.0
Description: Merge the contents of two arrays together into the first array.
  • version added: 1.0
  • jQuery.merge( [ Array ] first, [ Array ] second )
  • first The first array to merge, the elements of second added.
  • second The second array to merge into the first, unaltered.

The operation forms an array that contains all elements from the two arrays. The orders of items in the arrays are preserved, with items from the second array appended. The function is destructive. It alters the first parameter to add the items from the second.

If you need the original first array, make a copy of it before calling . Fortunately, itself can be used for this duplication:

var newArray = $.merge([], oldArray);

This shortcut creates a new, empty array and merges the contents of oldArray into it, effectively cloning the array.

Prior to jQuery 1.4, the arguments should be true Javascript Array objects; use if they are not.

Examples:

Example:

Merges two arrays, altering the first argument.
$.merge( [0,1,2], [2,3,4] )

Example:

Merges two arrays, altering the first argument.
$.merge( [3,2,1], [4,3,2] )

Example:

Merges two arrays, but uses a copy, so the original isn't altered.
var first = ['a','b','c'];
var second = ['d','e','f'];
$.merge( $.merge([],first), second);


jQuery.inArray – jQuery API

Returns: NumberNumber jQuery.inArray( [ Any ] value, [ Array ] array )

Categories: Utilities, Version 1.2
Description: Search for a specified value within an array and return its index (or -1 if not found).
  • version added: 1.2
  • jQuery.inArray( [ Any ] value, [ Array ] array )
  • value The value to search for.
  • array An array through which to search.

The method is similar to JavaScript's native method in that it returns -1 when it doesn't find a match. If the first element within the array matches , returns 0.

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of within , we need to check if it's not equal to (or greater than) -1.

Examples:

Example:

Report the index of some elements in the array.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:blue; }
  span { color:red; }</style>
</head>
<body>

<div>"John" found at <span></span></div>
<div>4 found at <span></span></div>
<div>"Karl" not found, so <span></span></div>
  <script>var arr = [ 4, "Pete", 8, "John" ];

$("span:eq(0)").text(jQuery.inArray("John", arr));
$("span:eq(1)").text(jQuery.inArray(4, arr));
$("span:eq(2)").text(jQuery.inArray("Karl", arr));</script>
</body>
</html>

Demo:


jQuery.map – jQuery API

Returns: ArrayArray jQuery.map( [ Array ] array, [ Function ] callback(elementOfArray, indexInArray) )

Categories: Utilities, Version 1.0
Description: Translate all items in an array or array-like object to another array of items.
  • version added: 1.0
  • jQuery.map( [ Array ] array, [ Function ] callback(elementOfArray, indexInArray) )
  • array The Array to translate.
  • callback(elementOfArray, indexInArray) The function to process each item against. The first argument to the function is the list item, the second argument is the index in array The function can return any value. will be the global window object.

The $.map() method applies a function to each item in an array, collecting the results into a new array.

The translation function that is provided to this method is called for each item in the array and is passed two arguments: The item to be translated, and the index within the array.

The function can return:

Map can iterate through Array-like objects, like a jQuery object, that have a length property.

Examples:

Example:

A couple examples of using .map()
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:blue; }
  p { color:green; margin:0; }
  span { color:red; }</style>
</head>
<body>
  <div></div>
  <p></p>
  <span></span>

  <script>var arr = [ "a", "b", "c", "d", "e" ];
    $("div").text(arr.join(", "));

    arr = jQuery.map(arr, function(n, i){
      return (n.toUpperCase() + i);
    });
    $("p").text(arr.join(", "));

    arr = jQuery.map(arr, function (a) { return a + a; });
    $("span").text(arr.join(", "));</script>
</body>
</html>

Demo:

Example:

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

Example:

Maps the original array to a new one and adds 1 to each value if it is bigger then zero, otherwise it's removed.
$.map( [0,1,2], function(n){
   return n > 0 ? n + 1 : null;
 });

Example:

Maps the original array to a new one, each element is added with it's original value and the value plus one.
$.map( [0,1,2], function(n){
   return [ n, n + 1 ];
 });

Example:

Maps the original array to a new one, each element is squared.
$.map( [0,1,2,3], function (a) { return a * a; } );

Example:

Remove items by returning from the function. This removes any numbers less than 50, and the rest are decreased by 45.
$.map( [0, 1, 52, 97], function (a) { return (a > 50 ? a - 45 : null); } );

Example:

Augmenting the resulting array by returning an array inside the function.
var array = [0, 1, 52, 97];
array = $.map(array, function(a, index) {
  return [a - 45, index];
});


jQuery.makeArray – jQuery API

Returns: ArrayArray jQuery.makeArray( [ Object ] obj )

Categories: Utilities, Version 1.2
Description: Convert an array-like object into a true JavaScript array.
  • version added: 1.2
  • jQuery.makeArray( [ Object ] obj )
  • obj Any object to turn into a native Array.

Many methods, both in jQuery and in JavaScript in general, return objects that are array-like. For example, the jQuery factory function returns a jQuery object that has many of the properties of an array (a length, the array access operator, etc.), but is not exactly the same as an array and lacks some of an array's built-in methods (such as and ).

Note that after the conversion, any special features the object had (such as the jQuery methods in our example) will no longer be present. The object is now a plain array.

Examples:

Example:

Turn a collection of HTMLElements into an Array of them.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:red; }</style>
</head>
<body>
  <div>First</div>
  <div>Second</div>
  <div>Third</div>

  <div>Fourth</div>
  <script>var elems = document.getElementsByTagName("div"); // returns a nodeList
    var arr = jQuery.makeArray(elems);
    arr.reverse(); // use an Array method on list of dom elements
    $(arr).appendTo(document.body);</script>
</body>
</html>

Demo:

Example:

Turn a jQuery object into an array
var obj = $('li');
    var arr = $.makeArray(obj);


jQuery.grep – jQuery API

Returns: ArrayArray jQuery.grep( [ Array ] array, [ Function ] function(elementOfArray, indexInArray), [ Boolean ] invert )

Categories: Utilities, Version 1.0
Description: Finds the elements of an array which satisfy a filter function. The original array is not affected.
  • version added: 1.0
  • jQuery.grep( [ Array ] array, [ Function ] function(elementOfArray, indexInArray), [ Boolean ] invert )
  • array The array to search through.
  • function(elementOfArray, indexInArray) The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. will be the global window object.
  • invert If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false.

The method removes items from an array as necessary so that all remaining items pass a provided test. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

The filter function will be passed two arguments: the current array item and its index. The filter function must return 'true' to include the item in the result array.

Examples:

Example:

Filters the original array of numbers leaving that are not 5 and have an index greater than 4. Then it removes all 9s.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:blue; }
  p { color:green; margin:0; }
  span { color:red; }</style>
</head>
<body>
  <div></div>
  <p></p>
  <span></span>

  <script>var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];
$("div").text(arr.join(", "));

arr = jQuery.grep(arr, function(n, i){
  return (n != 5 && i > 4);
});
$("p").text(arr.join(", "));

arr = jQuery.grep(arr, function (a) { return a != 9; });
$("span").text(arr.join(", "));</script>
</body>
</html>

Demo:

Example:

Filter an array of numbers to include only numbers bigger then zero.
$.grep( [0,1,2], function(n,i){
   return n > 0;
 });

Example:

Filter an array of numbers to include numbers that are not bigger than zero.
$.grep( [0,1,2], function(n,i){
    return n > 0;
},true);


jQuery.extend – jQuery API

Returns: ObjectObject jQuery.extend( [ Boolean ] deep, [ Object ] target, [ Object ] object1, [ Object ] objectN )

Categories: Utilities, Version 1.0
Description: Merge the contents of two or more objects together into the first object.
  • version added: 1.0
  • jQuery.extend( [ Object ] target, [ Object ] object1, [ Object ] objectN )
  • target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument.
  • object1 An object containing additional properties to merge in.
  • objectN Additional objects containing properties to merge in.
  • version added: 1.1.4
  • jQuery.extend( [ Boolean ] deep, [ Object ] target, [ Object ] object1, [ Object ] objectN )
  • deep If true, the merge becomes recursive (aka. deep copy).
  • target The object to extend. It will receive the new properties.
  • object1 An object containing additional properties to merge in.
  • objectN Additional objects containing properties to merge in.

When we supply two or more objects to , properties from all of the objects are added to the target object.

If only one argument is supplied to , this means the target argument was omitted. In this case, the jQuery object itself is assumed to be the target. By doing this, we can add new functions to the jQuery namespace. This can be useful for plugin authors wishing to add new methods to JQuery.

Keep in mind that the target object (first argument) will be modified, and will also be returned from . If, however, we want to preserve both of the original objects, we can do so by passing an empty object as the target:

var object = $.extend({}, object1, object2);

The merge performed by is not recursive by default; if a property of the first object is itself an object or array, it will be completely overwritten by a property with the same key in the second object. The values are not merged. This can be seen in the example below by examining the value of banana. However, by passing for the first function argument, objects will be recursively merged.

Undefined properties are not copied. However, properties inherited from the object's prototype be copied over.

Examples:

Example:

Merge two objects, modifying the first.
var object1 = {
  apple: 0,
  banana: {weight: 52, price: 100},
  cherry: 97
};
var object2 = {
  banana: {price: 200},
  durian: 100
};

$.extend(object1, object2);

Example:

Merge two objects recursively, modifying the first.
var object1 = {
  apple: 0,
  banana: {weight: 52, price: 100},
  cherry: 97
};
var object2 = {
  banana: {price: 200},
  lime: 100
};

$.extend(true, object1, object2);

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

Example:

Merge defaults and options, without modifying the defaults. This is a common plugin development pattern.
var empty = {}
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = $.extend(empty, defaults, options);


jQuery.each – jQuery API

Returns: ObjectObject jQuery.each( [ Object ] collection, [ Function ] callback(indexInArray, valueOfElement) )

Categories: Utilities, Version 1.0
Description: A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
  • version added: 1.0
  • jQuery.each( [ Object ] collection, [ Function ] callback(indexInArray, valueOfElement) )
  • collection The object or array to iterate over.
  • callback(indexInArray, valueOfElement) The function that will be executed on every object.

The function is not the same as , which is used to iterate, exclusively, over a jQuery object. The function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the keyword, but Javascript will always wrap the value as an even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

$.each([52, 97], function(index, value) {
  alert(index + ': ' + value);
});

This produces two messages:

If a map is used as the collection, the callback is passed a key-value pair each time:

var map = {
  'flammable': 'inflammable',
  'duh': 'no duh'
};
$.each(map, function(key, value) {
  alert(key + ': ' + value);
});

Once again, this produces two messages:

We can break the loop at a particular iteration by making the callback function return . Returning is the same as a statement in a for loop; it will skip immediately to the next iteration.

Examples:

Example:

Iterates through the array displaying each number as both a word and numeral
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:blue; }
  div#five { color:red; }</style>
</head>
<body>

  <div id="one"></div>
  <div id="two"></div>
  <div id="three"></div>
  <div id="four"></div>
  <div id="five"></div>
  <script>var arr = [ "one", "two", "three", "four", "five" ];
    var obj = { one:1, two:2, three:3, four:4, five:5 };

    jQuery.each(arr, function() {
      $("#" + this).text("Mine is " + this + ".");
       return (this != "three"); // will stop running after "three"
   });

    jQuery.each(obj, function(i, val) {
      $("#" + i).append(document.createTextNode(" - " + val));
    });</script>
</body>
</html>

Demo:

Example:

Iterates over items in an array, accessing both the current item and its index.
$.each( ['a','b','c'], function(i, l){
   alert( "Index #" + i + ": " + l );
 });

Example:

Iterates over the properties in an object, accessing both the current item and its key.
$.each( { name: "John", lang: "JS" }, function(k, v){
   alert( "Key: " + k + ", Value: " + v );
 });


jQuery.boxModel – jQuery API

Returns: BooleanBoolean jQuery.boxModel

Categories: Utilities, Version 1.0
Description: . States if the current page, in the user's browser, is being rendered using the .
  • version added: 1.0
  • jQuery.boxModel

Examples:

Example:

Returns the box model for the iframe.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>p { color:blue; margin:20px; }
  span { color:red; }</style>
</head>
<body>
  <p>
  </p>
  <script>$("p").html("The box model for this iframe is: <span>" +
                jQuery.boxModel + "</span>");</script>
</body>
</html>

Demo:

Example:

Returns false if the page is in Quirks Mode in Internet Explorer
$.boxModel

© 2010 The jQuery Project


Version – jQuery API

Version

  • jQuery .toggle( [ Boolean ] showOrHide )

    New in 1.3 !

    Display or hide the matched elements.

  • event.stopPropagation( )

    New in 1.0 !

    Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

  • undefined event.preventDefault( )

    New in 1.0 !

    If this method is called, the default action of the event will not be triggered.

  • Element event.target

    New in 1.0 !

    The DOM element that initiated the event.

  • String event.type

    New in 1.0 !

    Describes the nature of the event.

  • jQuery .each( [ Function ] function(index, Element) )

    New in 1.0 !

    Iterate over a jQuery object, executing a function for each matched element.

  • jQuery .pushStack( [ Array ] elements, [ String ] name, [ Array ] arguments )

    New in 1.3 !

    Add a collection of DOM elements onto the jQuery stack.

  • jQuery .keydown( )

    New in 1.0 !

    Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.

  • Number .index( [ Element | jQuery ] element )

    New in 1.0 !

    Search for a given element from among the matched elements.

  • Element, Array .get( [ Number ] index )

    New in 1.0 !

    Retrieve the DOM elements matched by the jQuery object.

  • Number .size( )

    New in 1.0 !

    Return the number of elements in the jQuery object.

  • Object jQuery.noConflict( [ Boolean ] removeAll )

    New in 1.0 !

    Relinquish jQuery's control of the variable.

  • JQuery(":selected")

    New in 1.0 !

    Selects all elements that are selected.

  • JQuery(":checked")

    New in 1.0 !

    Matches all elements that are checked.

  • JQuery(":disabled")

    New in 1.0 !

    Selects all elements that are disabled.

  • JQuery(":enabled")

    New in 1.0 !

    Selects all elements that are enabled.

  • JQuery(":file")

    New in 1.0 !

    Selects all elements of type file.

  • JQuery(":button")

    New in 1.0 !

    Selects all button elements and elements of type button.

  • JQuery(":reset")

    New in 1.0 !

    Selects all elements of type reset.

  • JQuery(":image")

    New in 1.0 !

    Selects all elements of type image.

  • jQuery .submit( )

    New in 1.0 !

    Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

  • JQuery(":checkbox")

    New in 1.0 !

    Selects all elements of type checkbox.

  • JQuery(":radio")

    New in 1.0 !

    Selects all elements of type radio.

  • JQuery(":password")

    New in 1.0 !

    Selects all elements of type password.

  • jQuery .text( [ Function ] function(index, text) )

    New in 1.4 !

    Set the content of each element in the set of matched elements to the specified text.

  • JQuery(":input")

    New in 1.0 !

    Selects all input, textarea, select and button elements.

  • JQuery("[attribute|="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).

  • JQuery("[attribute~="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

  • JQuery("[attributeFilter1][attributeFilter2][attributeFilterN]")

    New in 1.0 !

    Matches elements that match all of the specified attribute filters.

  • JQuery("[attribute*="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value containing the a given substring.

  • JQuery("[attribute$="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.

  • JQuery("[attribute^="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value beginning exactly with a given string.

  • JQuery("[attribute!="value"]")

    New in 1.0 !

    Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.

  • JQuery("[attribute="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value exactly equal to a certain value.

  • JQuery("[attribute]")

    New in 1.0 !

    Selects elements that have the specified attribute, with any value.

  • JQuery(":visible")

    New in 1.0 !

    Selects all elements that are visible.

  • JQuery(":hidden")

    New in 1.0 !

    Selects all elements that are hidden.

  • jQuery .parent( [ Selector ] selector )

    New in 1.0 !

    Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

  • jQuery .empty( )

    New in 1.0 !

    Remove all child nodes of the set of matched elements from the DOM.

  • JQuery(":lt(index)")

    New in 1.0 !

    Select all elements at an index less than within the matched set.

  • JQuery(":gt(index)")

    New in 1.0 !

    Select all elements at an index greater than within the matched set.

  • JQuery(":eq(index)")

    New in 1.0 !

    Select the element at index within the matched set.

  • JQuery(":odd")

    New in 1.0 !

    Selects odd elements, zero-indexed. See also .

  • JQuery(":even")

    New in 1.0 !

    Selects even elements, zero-indexed. See also .

  • jQuery .not( [ Function ] function(index) )

    New in 1.4 !

    Remove elements from the set of matched elements.

  • JQuery(":last")

    New in 1.0 !

    Selects the last matched element.

  • JQuery(":first")

    New in 1.0 !

    Selects the first matched element.

  • JQuery("prev ~ siblings")

    New in 1.0 !

    Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.

  • JQuery("prev + next")

    New in 1.0 !

    Selects all next elements matching "next" that are immediately preceded by a sibling "prev".

  • child")" rel="bookmark">JQuery("parent > child")

    New in 1.0 !

    Selects all direct child elements specified by "child" of elements specified by "parent".

  • JQuery("ancestor descendant")

    New in 1.0 !

    Selects all elements that are descendants of a given ancestor.

  • JQuery("selector1, selector2, selectorN")

    New in 1.0 !

    Selects the combined results of all the specified selectors.

  • JQuery("*")

    New in 1.0 !

    Selects all elements.

  • JQuery(".class")

    New in 1.0 !

    Selects all elements with the given class.

  • JQuery("element")

    New in 1.0 !

    Selects all elements with the given tag name.

  • JQuery("#id")

    New in 1.0 !

    Selects a single element with the given id attribute.

  • jQuery .scroll( )

    New in 1.0 !

    Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.

  • jQuery .resize( )

    New in 1.0 !

    Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.

  • jQuery .keyup( )

    New in 1.0 !

    Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.

  • jQuery .keypress( )

    New in 1.0 !

    Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.

  • jQuery .select( )

    New in 1.0 !

    Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

  • jQuery .change( )

    New in 1.0 !

    Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

  • jQuery .blur( )

    New in 1.0 !

    Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.

  • jQuery .focus( )

    New in 1.0 !

    Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.

  • jQuery .mousemove( )

    New in 1.0 !

    Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.

  • jQuery .hover( [ Function ] handlerInOut(eventObject) )

    New in 1.4 !

    Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.

  • jQuery .mouseleave( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.

  • jQuery .mouseenter( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

  • jQuery .mouseout( )

    New in 1.0 !

    Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.

  • jQuery .mouseover( )

    New in 1.0 !

    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • jQuery .dblclick( )

    New in 1.0 !

    Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.

  • jQuery .click( )

    New in 1.0 !

    Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

  • jQuery .mouseup( )

    New in 1.0 !

    Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.

  • jQuery .mousedown( )

    New in 1.0 !

    Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.

  • jQuery .error( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "error" JavaScript event.

  • jQuery .unload( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "unload" JavaScript event.

  • jQuery .load( [ String ] url, [ Map | String ] data, [ Function ] complete(responseText, textStatus, XMLHttpRequest) )

    New in 1.0 !

    Load data from the server and place the returned HTML into the matched element.

  • jQuery .ready( [ Function ] handler )

    New in 1.0 !

    Specify a function to execute when the DOM is fully loaded.

  • Map jQuery.browser

    New in 1.0 !

    Contains flags for the useragent, read from navigator.userAgent.

  • String jQuery.browser.version

    New in 1.1.3 !

    The version number of the rendering engine for the user's browser.

  • jQuery .trigger( [ Event ] event )

    New in 1.3 !

    Execute all handlers and behaviors attached to the matched elements for the given event type.

  • jQuery .ajaxComplete( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

    Register a handler to be called when Ajax requests complete. This is an .

  • String .serialize( )

    New in 1.0 !

    Encode a set of form elements as a string for submission.

  • jQuery .ajaxSuccess( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

    Attach a function to be executed whenever an Ajax request completes successfully. This is an .

  • jQuery .ajaxStop( [ Function ] handler() )

    New in 1.0 !

    Register a handler to be called when all Ajax requests have completed. This is an .

  • jQuery .ajaxStart( [ Function ] handler() )

    New in 1.0 !

    Register a handler to be called when the first Ajax request begins. This is an .

  • jQuery .ajaxSend( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

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

  • jQuery .ajaxError( [ Function ] handler(event, jqXHR, ajaxSettings, thrownError) )

    New in 1.0 !

    Register a handler to be called when Ajax requests complete with an error. This is an .

  • jQuery .unbind( [ Object ] event )

    New in 1.0 !

    Remove a previously-attached event handler from the elements.

  • jQuery .bind( [ Object ] events )

    New in 1.4 !

    Attach a handler to an event for the elements.

  • jQuery jQuery( [ Function ] callback )

    New in 1.0 !

    Binds a function to be executed when the DOM has finished loading.

  • jQuery .end( )

    New in 1.0 !

    End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.

  • jQuery .siblings( [ Selector ] selector )

    New in 1.0 !

    Get the siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .animate( [ Map ] properties, [ Map ] options )

    New in 1.0 !

    Perform a custom animation of a set of CSS properties.

  • jQuery .prev( [ Selector ] selector )

    New in 1.0 !

    Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .fadeTo( [ String,Number ] duration, [ Number ] opacity, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Adjust the opacity of the matched elements.

  • jQuery .fadeOut( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements by fading them to transparent.

  • jQuery .parents( [ Selector ] selector )

    New in 1.0 !

    Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

  • jQuery .fadeIn( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements by fading them to opaque.

  • jQuery .slideToggle( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display or hide the matched elements with a sliding motion.

  • jqXHR jQuery.post( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP POST request.

  • jQuery .slideUp( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements with a sliding motion.

  • jQuery .next( [ Selector ] selector )

    New in 1.0 !

    Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

  • jQuery .slideDown( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements with a sliding motion.

  • jQuery .find( [ Selector ] selector )

    New in 1.0 !

    Get the descendants of each element in the current set of matched elements, filtered by a selector.

  • XMLHttpRequest jQuery.getScript( [ String ] url, [ Function ] success(data, textStatus) )

    New in 1.0 !

    Load a JavaScript file from the server using a GET HTTP request, then execute it.

  • jqXHR jQuery.getJSON( [ String ] url, [ Map ] data, [ Function ] success(data, textStatus, jqXHR) )

    New in 1.0 !

    Load JSON-encoded data from the server using a GET HTTP request.

  • jqXHR jQuery.get( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP GET request.

  • jqXHR jQuery.ajax( [ Map ] settings )

    New in 1.0 !

    Perform an asynchronous HTTP (Ajax) request.

  • Number length

    New in 1.0 !

    The number of elements in the jQuery object.

  • jQuery .children( [ Selector ] selector )

    New in 1.0 !

    Get the children of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .add( [ Selector ] selector, [ Element ] context )

    New in 1.4 !

    Add elements to the set of matched elements.

  • jQuery .hide( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.

  • jQuery .show( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements.

  • String jQuery.trim( [ String ] str )

    New in 1.0 !

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

  • Array jQuery.merge( [ Array ] first, [ Array ] second )

    New in 1.0 !

    Merge the contents of two arrays together into the first array.

  • Array jQuery.map( [ Array ] array, [ Function ] callback(elementOfArray, indexInArray) )

    New in 1.0 !

    Translate all items in an array or array-like object to another array of items.

  • Array jQuery.grep( [ Array ] array, [ Function ] function(elementOfArray, indexInArray), [ Boolean ] invert )

    New in 1.0 !

    Finds the elements of an array which satisfy a filter function. The original array is not affected.

  • Object jQuery.extend( [ Boolean ] deep, [ Object ] target, [ Object ] object1, [ Object ] objectN )

    New in 1.1.4 !

    Merge the contents of two or more objects together into the first object.

  • Object jQuery.each( [ Object ] collection, [ Function ] callback(indexInArray, valueOfElement) )

    New in 1.0 !

    A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

  • Boolean jQuery.boxModel

    New in 1.0 !

    . States if the current page, in the user's browser, is being rendered using the .

  • jQuery .css( [ Map ] map )

    New in 1.0 !

    Set one or more CSS properties for the set of matched elements.

  • jQuery .clone( [ Boolean ] withDataAndEvents, [ Boolean ] deepWithDataAndEvents )

    New in 1.5 !

    Create a deep copy of the set of matched elements.

  • jQuery .remove( [ String ] selector )

    New in 1.0 !

    Remove the set of matched elements from the DOM.

  • jQuery .wrap( [ Function ] function(index) )

    New in 1.4 !

    Wrap an HTML structure around each element in the set of matched elements.

  • jQuery .insertBefore( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements before the target.

  • jQuery .before( [ Function ] function )

    New in 1.4 !

    Insert content, specified by the parameter, before each element in the set of matched elements.

  • jQuery .insertAfter( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements after the target.

  • jQuery .after( [ Function ] function(index) )

    New in 1.4 !

    Insert content, specified by the parameter, after each element in the set of matched elements.

  • jQuery .prependTo( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements to the beginning of the target.

  • jQuery .prepend( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

  • jQuery .appendTo( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements to the end of the target.

  • jQuery .append( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the end of each element in the set of matched elements.

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.

  • jQuery .html( [ Function ] function(index, oldhtml) )

    New in 1.4 !

    Set the HTML contents of each element in the set of matched elements.

  • Boolean .is( [ Selector ] selector )

    New in 1.0 !

    Check the current matched set of elements against a selector and return true if at least one of these elements matches the selector.

  • jQuery .filter( [ Object ] jQuery object )

    New in 1.4 !

    Reduce the set of matched elements to those that match the selector or pass the function's test.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • jQuery .removeAttr( [ String ] attributeName )

    New in 1.0 !

    Remove an attribute from each element in the set of matched elements.

  • jQuery .attr( [ String ] attributeName, [ Function ] function(index, attr) )

    New in 1.1 !

    Set one or more attributes for the set of matched elements.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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

  • Number event.pageY

    New in 1.0.4 !

    The mouse position relative to the top edge of the document.

  • Number event.pageX

    New in 1.0.4 !

    The mouse position relative to the left edge of the document.

  • jQuery.globalEval( [ String ] code )

    New in 1.0.4 !

    Execute some JavaScript code globally.

  • Anything event.data

    New in 1.1 !

    The optional data passed to jQuery.fn.bind when the current executing handler was bound.

  • jQuery .one( [ String ] eventType, [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.1 !

    Attach a handler to an event for the elements. The handler is executed at most once per element.

  • jQuery.ajaxSetup( [ Options ] options )

    New in 1.1 !

    Set default values for future Ajax requests.

  • jQuery .attr( [ String ] attributeName, [ Function ] function(index, attr) )

    New in 1.1 !

    Set one or more attributes for the set of matched elements.

  • jQuery .eq( [ Integer ] -index )

    New in 1.4 !

    Reduce the set of matched elements to the one at the specified index.

  • Number event.which

    New in 1.1.3 !

    For key or button events, this attribute indicates the specific button or key that was pressed.

  • Map jQuery.browser

    New in 1.0 !

    Contains flags for the useragent, read from navigator.userAgent.

  • String jQuery.browser.version

    New in 1.1.3 !

    The version number of the rendering engine for the user's browser.

  • Array jQuery.unique( [ Array ] array )

    New in 1.1.3 !

    Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.

  • Element event.relatedTarget

    New in 1.1.4 !

    The other DOM element involved in the event, if any.

  • Boolean jQuery.isXMLDoc( [ Element ] node )

    New in 1.1.4 !

    Check to see if a DOM node is within an XML document (or is an XML document).

  • JQuery(":only-child")

    New in 1.1.4 !

    Selects all elements that are the only child of their parent.

  • JQuery(":last-child")

    New in 1.1.4 !

    Selects all elements that are the last child of their parent.

  • JQuery(":first-child")

    New in 1.1.4 !

    Selects all elements that are the first child of their parent.

  • JQuery(":nth-child(index/even/odd/equation)")

    New in 1.1.4 !

    Selects all elements that are the nth-child of their parent.

  • JQuery(":has(selector)")

    New in 1.1.4 !

    Selects elements which contain at least one element that matches the specified selector.

  • JQuery(":contains(text)")

    New in 1.1.4 !

    Select all elements that contain the specified text.

  • jQuery .slice( [ Integer ] start, [ Integer ] end )

    New in 1.1.4 !

    Reduce the set of matched elements to a subset specified by a range of indices.

  • JQuery(":animated")

    New in 1.2 !

    Select all elements that are in the progress of an animation at the time the selector is run.

  • JQuery(":header")

    New in 1.2 !

    Selects all elements that are headers, like h1, h2, h3 and so on.

  • jQuery .dequeue( [ String ] queueName )

    New in 1.2 !

    Execute the next function on the queue for the matched elements.

  • jQuery .queue( [ String ] queueName, [ Function ] callback( next ) )

    New in 1.2 !

    Manipulate the queue of functions to be executed on the matched elements.

  • Object .triggerHandler( [ String ] eventType, [ Array ] extraParameters )

    New in 1.2 !

    Execute all handlers attached to an element for an event.

  • Array .serializeArray( )

    New in 1.2 !

    Encode a set of form elements as an array of names and values.

  • jQuery .stop( [ Boolean ] clearQueue, [ Boolean ] jumpToEnd )

    New in 1.2 !

    Stop the currently-running animation on the matched elements.

  • jQuery .andSelf( )

    New in 1.2 !

    Add the previous set of elements on the stack to the current set.

  • jQuery .prevAll( [ Selector ] selector )

    New in 1.2 !

    Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .nextAll( [ String ] selector )

    New in 1.2 !

    Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .contents( )

    New in 1.2 !

    Get the children of each element in the set of matched elements, including text and comment nodes.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

  • boolean jQuery.isFunction( [ Object ] obj )

    New in 1.2 !

    Determine if the argument passed is a Javascript function object.

  • Number jQuery.inArray( [ Any ] value, [ Array ] array )

    New in 1.2 !

    Search for a specified value within an array and return its index (or -1 if not found).

  • Array jQuery.makeArray( [ Object ] obj )

    New in 1.2 !

    Convert an array-like object into a true JavaScript array.

  • Object .position( )

    New in 1.2 !

    Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.

  • jQuery .replaceAll( [ Selector ] target )

    New in 1.2 !

    Replace each target element with the set of matched elements.

  • jQuery .replaceWith( [ Function ] function )

    New in 1.4 !

    Replace each element in the set of matched elements with the provided new content.

  • jQuery .wrapInner( [ Function ] wrappingFunction )

    New in 1.4 !

    Wrap an HTML structure around the content of each element in the set of matched elements.

  • jQuery .wrapAll( [ String | Selector | Element | jQuery ] wrappingElement )

    New in 1.2 !

    Wrap an HTML structure around all elements in the set of matched elements.

  • jQuery .map( [ Function ] callback(index, domElement) )

    New in 1.2 !

    Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

  • Boolean .hasClass( [ String ] className )

    New in 1.2 !

    Determine whether any of the matched elements are assigned the given class.

  • jQuery jQuery.removeData( [ Element ] element, [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery .removeData( [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • Number event.timeStamp

    New in 1.2.6 !

    The difference in milliseconds between the time an event is triggered and January 1, 1970.

  • Integer .outerWidth( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding and border.

  • Integer .outerHeight( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.

  • Integer .innerWidth( )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding but not border.

  • Integer .innerHeight( )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding but not border.

  • jQuery .scrollLeft( [ Number ] value )

    New in 1.2.6 !

    Set the current horizontal position of the scroll bar for each of the set of matched elements.

  • jQuery .scrollTop( [ Number ] value )

    New in 1.2.6 !

    Set the current vertical position of the scroll bar for each of the set of matched elements.

  • Boolean event.isImmediatePropagationStopped( )

    New in 1.3 !

    Returns whether event.stopImmediatePropagation() was ever called on this event object.

  • event.stopImmediatePropagation( )

    New in 1.3 !

    Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.

  • Boolean event.isPropagationStopped( )

    New in 1.3 !

    Returns whether was ever called on this event object.

  • Boolean event.isDefaultPrevented( )

    New in 1.3 !

    Returns whether was ever called on this event object.

  • Object event.result

    New in 1.3 !

    The last value returned by an event handler that was triggered by this event, unless the value was .

  • Element event.currentTarget

    New in 1.3 !

    The current DOM element within the event bubbling phase.

  • Boolean jQuery.fx.off

    New in 1.3 !

    Globally disable all animations.

  • jQuery .pushStack( [ Array ] elements, [ String ] name, [ Array ] arguments )

    New in 1.3 !

    Add a collection of DOM elements onto the jQuery stack.

  • jQuery jQuery.dequeue( [ Element ] element, [ String ] queueName )

    New in 1.3 !

    Execute the next function on the queue for the matched element.

  • jQuery jQuery.queue( [ Element ] element, [ String ] queueName, [ Function ] callback() )

    New in 1.3 !

    Manipulate the queue of functions to be executed on the matched element.

  • jQuery .die( [ Map ] eventTypes )

    New in 1.4.3 !

    Remove an event handler previously attached using from the elements.

  • jQuery .live( [ Object ] events )

    New in 1.4.3 !

    Attach a handler to the event for all elements which match the current selector, now and in the future.

  • Array .closest( [ Array ] selectors, [ Element ] context )

    New in 1.4 !

    Gets an array of all the elements and selectors matched against the current element up through the DOM tree.

  • String selector

    New in 1.3 !

    A selector representing selector originally passed to jQuery().

  • Element context

    New in 1.3 !

    The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document.

  • jQuery .toggle( [ Boolean ] showOrHide )

    New in 1.3 !

    Display or hide the matched elements.

  • boolean jQuery.isArray( [ Object ] obj )

    New in 1.3 !

    Determine whether the argument is an array.

  • Object jQuery.support

    New in 1.3 !

    A collection of properties that represent the presence of different browser features or bugs.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • Function jQuery.proxy( [ Object ] context, [ String ] name )

    New in 1.4 !

    Takes a function and returns a new one that will always have a particular context.

  • jQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusout" JavaScript event.

  • jQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusin" JavaScript event.

  • jQuery .has( [ Element ] contained )

    New in 1.4 !

    Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

  • Boolean jQuery.contains( [ Element ] container, [ Element ] contained )

    New in 1.4 !

    Check to see if a DOM node is within another DOM node.

  • Function jQuery.noop( )

    New in 1.4 !

    An empty function.

  • jQuery .delay( [ Integer ] duration, [ String ] queueName )

    New in 1.4 !

    Set a timer to delay execution of subsequent items in the queue.

  • jQuery .parentsUntil( [ Selector ] selector )

    New in 1.4 !

    Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.

  • jQuery .prevUntil( [ Selector ] selector )

    New in 1.4 !

    Get all preceding siblings of each element up to but not including the element matched by the selector.

  • jQuery .nextUntil( [ Selector ] selector )

    New in 1.4 !

    Get all following siblings of each element up to but not including the element matched by the selector.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery .clearQueue( [ String ] queueName )

    New in 1.4 !

    Remove from the queue all items that have not yet been run.

  • Array .toArray( )

    New in 1.4 !

    Retrieve all the DOM elements contained in the jQuery set, as an array.

  • Boolean jQuery.isEmptyObject( [ Object ] object )

    New in 1.4 !

    Check to see if an object is empty (contains no properties).

  • Boolean jQuery.isPlainObject( [ Object ] object )

    New in 1.4 !

    Check to see if an object is a plain object (created using "{}" or "new Object").

  • Number .index( [ Element | jQuery ] element )

    New in 1.0 !

    Search for a given element from among the matched elements.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • jQuery .bind( [ Object ] events )

    New in 1.4 !

    Attach a handler to an event for the elements.

  • jQuery .first( )

    New in 1.4 !

    Reduce the set of matched elements to the first in the set.

  • jQuery .last( )

    New in 1.4 !

    Reduce the set of matched elements to the final one in the set.

  • jQuery jQuery( [ Function ] callback )

    New in 1.0 !

    Binds a function to be executed when the DOM has finished loading.

  • Array .closest( [ Array ] selectors, [ Element ] context )

    New in 1.4 !

    Gets an array of all the elements and selectors matched against the current element up through the DOM tree.

  • jQuery .add( [ Selector ] selector, [ Element ] context )

    New in 1.4 !

    Add elements to the set of matched elements.

  • jQuery .not( [ Function ] function(index) )

    New in 1.4 !

    Remove elements from the set of matched elements.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.

  • jQuery .css( [ Map ] map )

    New in 1.0 !

    Set one or more CSS properties for the set of matched elements.

  • jQuery .unwrap( )

    New in 1.4 !

    Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

  • jQuery .detach( [ Selector ] selector )

    New in 1.4 !

    Remove the set of matched elements from the DOM.

  • jQuery .replaceWith( [ Function ] function )

    New in 1.4 !

    Replace each element in the set of matched elements with the provided new content.

  • jQuery .wrapInner( [ Function ] wrappingFunction )

    New in 1.4 !

    Wrap an HTML structure around the content of each element in the set of matched elements.

  • jQuery .wrapAll( [ String | Selector | Element | jQuery ] wrappingElement )

    New in 1.2 !

    Wrap an HTML structure around all elements in the set of matched elements.

  • jQuery .wrap( [ Function ] function(index) )

    New in 1.4 !

    Wrap an HTML structure around each element in the set of matched elements.

  • jQuery .before( [ Function ] function )

    New in 1.4 !

    Insert content, specified by the parameter, before each element in the set of matched elements.

  • jQuery .after( [ Function ] function(index) )

    New in 1.4 !

    Insert content, specified by the parameter, after each element in the set of matched elements.

  • jQuery .prepend( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

  • jQuery .append( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the end of each element in the set of matched elements.

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.

  • jQuery .text( [ Function ] function(index, text) )

    New in 1.4 !

    Set the content of each element in the set of matched elements to the specified text.

  • jQuery .html( [ Function ] function(index, oldhtml) )

    New in 1.4 !

    Set the HTML contents of each element in the set of matched elements.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • jQuery .removeAttr( [ String ] attributeName )

    New in 1.0 !

    Remove an attribute from each element in the set of matched elements.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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

  • jQuery.error( [ String ] message )

    New in 1.4.1 !

    Takes a string and throws an exception containing it.

  • Object jQuery.parseJSON( [ String ] json )

    New in 1.4.1 !

    Takes a well-formed JSON string and returns the resulting JavaScript object.

  • jQuery .die( [ Map ] eventTypes )

    New in 1.4.3 !

    Remove an event handler previously attached using from the elements.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.

  • jQuery .undelegate( [ String ] namespace )

    New in 1.6 !

    Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.

  • jQuery .delegate( [ String ] selector, [ Map ] events )

    New in 1.4.3 !

    Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

  • Number jQuery.now( )

    New in 1.4.3 !

    Return a number representing the current time.

  • Object jQuery.cssHooks

    New in 1.4.3 !

    Provides a way to hook directly into jQuery to override how particular CSS properties are retrieved or set. Amongst other uses, cssHooks can be used to create custom, browser-normalized properties for CSS3 features such as box-shadows and gradients.

  • String jQuery.type( [ Object ] obj )

    New in 1.4.3 !

    Determine the internal JavaScript [[Class]] of an object.

  • boolean jQuery.isWindow( [ Object ] obj )

    New in 1.4.3 !

    Determine whether the argument is a window.

  • Number jQuery.fx.interval

    New in 1.4.3 !

    The rate (in milliseconds) at which animations fire.

  • String event.namespace

    New in 1.4.3 !

    The namespace specified when the event was triggered.

  • jQuery .undelegate( [ String ] namespace )

    New in 1.6 !

    Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.

  • jQuery .delegate( [ String ] selector, [ Map ] events )

    New in 1.4.3 !

    Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

  • jQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusout" JavaScript event.

  • jQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusin" JavaScript event.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery .keydown( )

    New in 1.0 !

    Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • jQuery .scroll( )

    New in 1.0 !

    Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.

  • jQuery .resize( )

    New in 1.0 !

    Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.

  • jQuery .keyup( )

    New in 1.0 !

    Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.

  • jQuery .keypress( )

    New in 1.0 !

    Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.

  • jQuery .submit( )

    New in 1.0 !

    Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

  • jQuery .select( )

    New in 1.0 !

    Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

  • jQuery .change( )

    New in 1.0 !

    Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

  • jQuery .blur( )

    New in 1.0 !

    Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.

  • jQuery .focus( )

    New in 1.0 !

    Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.

  • jQuery .mousemove( )

    New in 1.0 !

    Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.

  • jQuery .mouseleave( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.

  • jQuery .mouseenter( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

  • jQuery .mouseout( )

    New in 1.0 !

    Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.

  • jQuery .mouseover( )

    New in 1.0 !

    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • jQuery .dblclick( )

    New in 1.0 !

    Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.

  • jQuery .click( )

    New in 1.0 !

    Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

  • jQuery .mouseup( )

    New in 1.0 !

    Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.

  • jQuery .mousedown( )

    New in 1.0 !

    Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.

  • jQuery .error( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "error" JavaScript event.

  • jQuery .unload( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "unload" JavaScript event.

  • jQuery .load( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "load" JavaScript event.

  • jQuery .die( [ Map ] eventTypes )

    New in 1.4.3 !

    Remove an event handler previously attached using from the elements.

  • jQuery .unbind( [ Object ] event )

    New in 1.0 !

    Remove a previously-attached event handler from the elements.

  • jQuery .bind( [ Object ] events )

    New in 1.4 !

    Attach a handler to an event for the elements.

  • jQuery .fadeTo( [ String,Number ] duration, [ Number ] opacity, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Adjust the opacity of the matched elements.

  • jQuery .fadeOut( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements by fading them to transparent.

  • jQuery .fadeIn( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements by fading them to opaque.

  • jQuery .slideToggle( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display or hide the matched elements with a sliding motion.

  • jQuery .slideUp( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements with a sliding motion.

  • jQuery .slideDown( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements with a sliding motion.

  • jQuery .toggle( [ Boolean ] showOrHide )

    New in 1.3 !

    Display or hide the matched elements.

  • jQuery .hide( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements.

  • jQuery .show( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements.

  • jQuery .fadeToggle( [ String,Number ] duration, [ String ] easing, [ Function ] callback )

    New in 1.4.4 !

    Display or hide the matched elements by animating their opacity.

  • undefined jQuery.ajaxPrefilter( [ String ] dataTypes, [ Function ] handler(options, originalOptions, jqXHR) )

    New in 1.5 !

    Handle custom Ajax options or modify existing options before each request is sent and before they are processed by .

  • Boolean jQuery.hasData( [ Element ] element )

    New in 1.5 !

    Determine whether an element has any jQuery data associated with it.

  • Promise .deferred.promise( )

    New in 1.5 !

    Return a Deferred's Promise object.

  • XMLDocument jQuery.parseXML( [ String ] data )

    New in 1.5 !

    Parses a string into an XML document.

  • Promise jQuery.when( [ Deferred ] deferreds )

    New in 1.5 !

    Provides a way to execute callback functions based on one or more objects, usually objects that represent asynchronous events.

  • Deferred .deferred.resolveWith( [ Object ] context, [ Array ] args )

    New in 1.5 !

    Resolve a Deferred object and call any doneCallbacks with the given and .

  • Deferred .deferred.rejectWith( [ Object ] context, [ Array ] args )

    New in 1.5 !

    Reject a Deferred object and call any failCallbacks with the given and .

  • Deferred .deferred.fail( [ Function ] failCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is rejected.

  • Deferred .deferred.done( [ Function ] doneCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is resolved.

  • Deferred .deferred.then( [ Function ] doneCallbacks, [ Function ] failCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is resolved or rejected.

  • Deferred .deferred.reject( [ Object ] args )

    New in 1.5 !

    Reject a Deferred object and call any failCallbacks with the given .

  • Boolean .deferred.isRejected( )

    New in 1.5 !

    Determine whether a Deferred object has been rejected.

  • Boolean .deferred.isResolved( )

    New in 1.5 !

    Determine whether a Deferred object has been resolved.

  • Deferred .deferred.resolve( [ Object ] args )

    New in 1.5 !

    Resolve a Deferred object and call any doneCallbacks with the given .

  • jQuery jQuery.sub( )

    New in 1.5 !

    Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.

  • jqXHR jQuery.post( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP POST request.

  • XMLHttpRequest jQuery.getScript( [ String ] url, [ Function ] success(data, textStatus) )

    New in 1.0 !

    Load a JavaScript file from the server using a GET HTTP request, then execute it.

  • jqXHR jQuery.getJSON( [ String ] url, [ Map ] data, [ Function ] success(data, textStatus, jqXHR) )

    New in 1.0 !

    Load JSON-encoded data from the server using a GET HTTP request.

  • jqXHR jQuery.get( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP GET request.

  • jqXHR jQuery.ajax( [ Map ] settings )

    New in 1.0 !

    Perform an asynchronous HTTP (Ajax) request.

  • jQuery .clone( [ Boolean ] withDataAndEvents, [ Boolean ] deepWithDataAndEvents )

    New in 1.5 !

    Create a deep copy of the set of matched elements.

  • jqXHR jQuery.ajax( [ Map ] settings )

    New in 1.0 !

    Perform an asynchronous HTTP (Ajax) request.

  • Object jQuery.support

    New in 1.3 !

    A collection of properties that represent the presence of different browser features or bugs.


Version 1.0 – jQuery API

Version 1.0

  • jQuery .toggle( [ Boolean ] showOrHide )

    New in 1.3 !

    Display or hide the matched elements.

  • event.stopPropagation( )

    New in 1.0 !

    Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

  • undefined event.preventDefault( )

    New in 1.0 !

    If this method is called, the default action of the event will not be triggered.

  • Element event.target

    New in 1.0 !

    The DOM element that initiated the event.

  • String event.type

    New in 1.0 !

    Describes the nature of the event.

  • jQuery .each( [ Function ] function(index, Element) )

    New in 1.0 !

    Iterate over a jQuery object, executing a function for each matched element.

  • jQuery .pushStack( [ Array ] elements, [ String ] name, [ Array ] arguments )

    New in 1.3 !

    Add a collection of DOM elements onto the jQuery stack.

  • jQuery .keydown( )

    New in 1.0 !

    Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.

  • Number .index( [ Element | jQuery ] element )

    New in 1.0 !

    Search for a given element from among the matched elements.

  • Element, Array .get( [ Number ] index )

    New in 1.0 !

    Retrieve the DOM elements matched by the jQuery object.

  • Number .size( )

    New in 1.0 !

    Return the number of elements in the jQuery object.

  • Object jQuery.noConflict( [ Boolean ] removeAll )

    New in 1.0 !

    Relinquish jQuery's control of the variable.

  • JQuery(":selected")

    New in 1.0 !

    Selects all elements that are selected.

  • JQuery(":checked")

    New in 1.0 !

    Matches all elements that are checked.

  • JQuery(":disabled")

    New in 1.0 !

    Selects all elements that are disabled.

  • JQuery(":enabled")

    New in 1.0 !

    Selects all elements that are enabled.

  • JQuery(":file")

    New in 1.0 !

    Selects all elements of type file.

  • JQuery(":button")

    New in 1.0 !

    Selects all button elements and elements of type button.

  • JQuery(":reset")

    New in 1.0 !

    Selects all elements of type reset.

  • JQuery(":image")

    New in 1.0 !

    Selects all elements of type image.

  • jQuery .submit( )

    New in 1.0 !

    Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

  • JQuery(":checkbox")

    New in 1.0 !

    Selects all elements of type checkbox.

  • JQuery(":radio")

    New in 1.0 !

    Selects all elements of type radio.

  • JQuery(":password")

    New in 1.0 !

    Selects all elements of type password.

  • jQuery .text( [ Function ] function(index, text) )

    New in 1.4 !

    Set the content of each element in the set of matched elements to the specified text.

  • JQuery(":input")

    New in 1.0 !

    Selects all input, textarea, select and button elements.

  • JQuery("[attribute|="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).

  • JQuery("[attribute~="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

  • JQuery("[attributeFilter1][attributeFilter2][attributeFilterN]")

    New in 1.0 !

    Matches elements that match all of the specified attribute filters.

  • JQuery("[attribute*="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value containing the a given substring.

  • JQuery("[attribute$="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.

  • JQuery("[attribute^="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value beginning exactly with a given string.

  • JQuery("[attribute!="value"]")

    New in 1.0 !

    Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.

  • JQuery("[attribute="value"]")

    New in 1.0 !

    Selects elements that have the specified attribute with a value exactly equal to a certain value.

  • JQuery("[attribute]")

    New in 1.0 !

    Selects elements that have the specified attribute, with any value.

  • JQuery(":visible")

    New in 1.0 !

    Selects all elements that are visible.

  • JQuery(":hidden")

    New in 1.0 !

    Selects all elements that are hidden.

  • jQuery .parent( [ Selector ] selector )

    New in 1.0 !

    Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

  • jQuery .empty( )

    New in 1.0 !

    Remove all child nodes of the set of matched elements from the DOM.

  • JQuery(":lt(index)")

    New in 1.0 !

    Select all elements at an index less than within the matched set.

  • JQuery(":gt(index)")

    New in 1.0 !

    Select all elements at an index greater than within the matched set.

  • JQuery(":eq(index)")

    New in 1.0 !

    Select the element at index within the matched set.

  • JQuery(":odd")

    New in 1.0 !

    Selects odd elements, zero-indexed. See also .

  • JQuery(":even")

    New in 1.0 !

    Selects even elements, zero-indexed. See also .

  • jQuery .not( [ Function ] function(index) )

    New in 1.4 !

    Remove elements from the set of matched elements.

  • JQuery(":last")

    New in 1.0 !

    Selects the last matched element.

  • JQuery(":first")

    New in 1.0 !

    Selects the first matched element.

  • JQuery("prev ~ siblings")

    New in 1.0 !

    Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.

  • JQuery("prev + next")

    New in 1.0 !

    Selects all next elements matching "next" that are immediately preceded by a sibling "prev".

  • child")" rel="bookmark">JQuery("parent > child")

    New in 1.0 !

    Selects all direct child elements specified by "child" of elements specified by "parent".

  • JQuery("ancestor descendant")

    New in 1.0 !

    Selects all elements that are descendants of a given ancestor.

  • JQuery("selector1, selector2, selectorN")

    New in 1.0 !

    Selects the combined results of all the specified selectors.

  • JQuery("*")

    New in 1.0 !

    Selects all elements.

  • JQuery(".class")

    New in 1.0 !

    Selects all elements with the given class.

  • JQuery("element")

    New in 1.0 !

    Selects all elements with the given tag name.

  • JQuery("#id")

    New in 1.0 !

    Selects a single element with the given id attribute.

  • jQuery .scroll( )

    New in 1.0 !

    Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.

  • jQuery .resize( )

    New in 1.0 !

    Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.

  • jQuery .keyup( )

    New in 1.0 !

    Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.

  • jQuery .keypress( )

    New in 1.0 !

    Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.

  • jQuery .select( )

    New in 1.0 !

    Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

  • jQuery .change( )

    New in 1.0 !

    Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

  • jQuery .blur( )

    New in 1.0 !

    Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.

  • jQuery .focus( )

    New in 1.0 !

    Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.

  • jQuery .mousemove( )

    New in 1.0 !

    Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.

  • jQuery .hover( [ Function ] handlerInOut(eventObject) )

    New in 1.4 !

    Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.

  • jQuery .mouseleave( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.

  • jQuery .mouseenter( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

  • jQuery .mouseout( )

    New in 1.0 !

    Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.

  • jQuery .mouseover( )

    New in 1.0 !

    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • jQuery .dblclick( )

    New in 1.0 !

    Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.

  • jQuery .click( )

    New in 1.0 !

    Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

  • jQuery .mouseup( )

    New in 1.0 !

    Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.

  • jQuery .mousedown( )

    New in 1.0 !

    Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.

  • jQuery .error( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "error" JavaScript event.

  • jQuery .unload( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "unload" JavaScript event.

  • jQuery .load( [ String ] url, [ Map | String ] data, [ Function ] complete(responseText, textStatus, XMLHttpRequest) )

    New in 1.0 !

    Load data from the server and place the returned HTML into the matched element.

  • jQuery .ready( [ Function ] handler )

    New in 1.0 !

    Specify a function to execute when the DOM is fully loaded.

  • Map jQuery.browser

    New in 1.0 !

    Contains flags for the useragent, read from navigator.userAgent.

  • String jQuery.browser.version

    New in 1.1.3 !

    The version number of the rendering engine for the user's browser.

  • jQuery .trigger( [ Event ] event )

    New in 1.3 !

    Execute all handlers and behaviors attached to the matched elements for the given event type.

  • jQuery .ajaxComplete( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

    Register a handler to be called when Ajax requests complete. This is an .

  • String .serialize( )

    New in 1.0 !

    Encode a set of form elements as a string for submission.

  • jQuery .ajaxSuccess( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

    Attach a function to be executed whenever an Ajax request completes successfully. This is an .

  • jQuery .ajaxStop( [ Function ] handler() )

    New in 1.0 !

    Register a handler to be called when all Ajax requests have completed. This is an .

  • jQuery .ajaxStart( [ Function ] handler() )

    New in 1.0 !

    Register a handler to be called when the first Ajax request begins. This is an .

  • jQuery .ajaxSend( [ Function ] handler(event, XMLHttpRequest, ajaxOptions) )

    New in 1.0 !

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

  • jQuery .ajaxError( [ Function ] handler(event, jqXHR, ajaxSettings, thrownError) )

    New in 1.0 !

    Register a handler to be called when Ajax requests complete with an error. This is an .

  • jQuery .unbind( [ Object ] event )

    New in 1.0 !

    Remove a previously-attached event handler from the elements.

  • jQuery .bind( [ Object ] events )

    New in 1.4 !

    Attach a handler to an event for the elements.

  • jQuery jQuery( [ Function ] callback )

    New in 1.0 !

    Binds a function to be executed when the DOM has finished loading.

  • jQuery .end( )

    New in 1.0 !

    End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.

  • jQuery .siblings( [ Selector ] selector )

    New in 1.0 !

    Get the siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .animate( [ Map ] properties, [ Map ] options )

    New in 1.0 !

    Perform a custom animation of a set of CSS properties.

  • jQuery .prev( [ Selector ] selector )

    New in 1.0 !

    Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .fadeTo( [ String,Number ] duration, [ Number ] opacity, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Adjust the opacity of the matched elements.

  • jQuery .fadeOut( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements by fading them to transparent.

  • jQuery .parents( [ Selector ] selector )

    New in 1.0 !

    Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

  • jQuery .fadeIn( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements by fading them to opaque.

  • jQuery .slideToggle( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display or hide the matched elements with a sliding motion.

  • jqXHR jQuery.post( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP POST request.

  • jQuery .slideUp( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements with a sliding motion.

  • jQuery .next( [ Selector ] selector )

    New in 1.0 !

    Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

  • jQuery .slideDown( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements with a sliding motion.

  • jQuery .find( [ Selector ] selector )

    New in 1.0 !

    Get the descendants of each element in the current set of matched elements, filtered by a selector.

  • XMLHttpRequest jQuery.getScript( [ String ] url, [ Function ] success(data, textStatus) )

    New in 1.0 !

    Load a JavaScript file from the server using a GET HTTP request, then execute it.

  • jqXHR jQuery.getJSON( [ String ] url, [ Map ] data, [ Function ] success(data, textStatus, jqXHR) )

    New in 1.0 !

    Load JSON-encoded data from the server using a GET HTTP request.

  • jqXHR jQuery.get( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP GET request.

  • jqXHR jQuery.ajax( [ Map ] settings )

    New in 1.0 !

    Perform an asynchronous HTTP (Ajax) request.

  • Number length

    New in 1.0 !

    The number of elements in the jQuery object.

  • jQuery .children( [ Selector ] selector )

    New in 1.0 !

    Get the children of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .add( [ Selector ] selector, [ Element ] context )

    New in 1.4 !

    Add elements to the set of matched elements.

  • jQuery .hide( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.

  • jQuery .show( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements.

  • String jQuery.trim( [ String ] str )

    New in 1.0 !

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

  • Array jQuery.merge( [ Array ] first, [ Array ] second )

    New in 1.0 !

    Merge the contents of two arrays together into the first array.

  • Array jQuery.map( [ Array ] array, [ Function ] callback(elementOfArray, indexInArray) )

    New in 1.0 !

    Translate all items in an array or array-like object to another array of items.

  • Array jQuery.grep( [ Array ] array, [ Function ] function(elementOfArray, indexInArray), [ Boolean ] invert )

    New in 1.0 !

    Finds the elements of an array which satisfy a filter function. The original array is not affected.

  • Object jQuery.extend( [ Boolean ] deep, [ Object ] target, [ Object ] object1, [ Object ] objectN )

    New in 1.1.4 !

    Merge the contents of two or more objects together into the first object.

  • Object jQuery.each( [ Object ] collection, [ Function ] callback(indexInArray, valueOfElement) )

    New in 1.0 !

    A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

  • Boolean jQuery.boxModel

    New in 1.0 !

    . States if the current page, in the user's browser, is being rendered using the .

  • jQuery .css( [ Map ] map )

    New in 1.0 !

    Set one or more CSS properties for the set of matched elements.

  • jQuery .clone( [ Boolean ] withDataAndEvents, [ Boolean ] deepWithDataAndEvents )

    New in 1.5 !

    Create a deep copy of the set of matched elements.

  • jQuery .remove( [ String ] selector )

    New in 1.0 !

    Remove the set of matched elements from the DOM.

  • jQuery .wrap( [ Function ] function(index) )

    New in 1.4 !

    Wrap an HTML structure around each element in the set of matched elements.

  • jQuery .insertBefore( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements before the target.

  • jQuery .before( [ Function ] function )

    New in 1.4 !

    Insert content, specified by the parameter, before each element in the set of matched elements.

  • jQuery .insertAfter( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements after the target.

  • jQuery .after( [ Function ] function(index) )

    New in 1.4 !

    Insert content, specified by the parameter, after each element in the set of matched elements.

  • jQuery .prependTo( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements to the beginning of the target.

  • jQuery .prepend( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

  • jQuery .appendTo( [ Selector | Element | jQuery ] target )

    New in 1.0 !

    Insert every element in the set of matched elements to the end of the target.

  • jQuery .append( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the end of each element in the set of matched elements.

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.

  • jQuery .html( [ Function ] function(index, oldhtml) )

    New in 1.4 !

    Set the HTML contents of each element in the set of matched elements.

  • Boolean .is( [ Selector ] selector )

    New in 1.0 !

    Check the current matched set of elements against a selector and return true if at least one of these elements matches the selector.

  • jQuery .filter( [ Object ] jQuery object )

    New in 1.4 !

    Reduce the set of matched elements to those that match the selector or pass the function's test.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • jQuery .removeAttr( [ String ] attributeName )

    New in 1.0 !

    Remove an attribute from each element in the set of matched elements.

  • jQuery .attr( [ String ] attributeName, [ Function ] function(index, attr) )

    New in 1.1 !

    Set one or more attributes for the set of matched elements.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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


Version 1.0.4 – jQuery API

Version 1.0.4

  • Number event.pageY

    New in 1.0.4 !

    The mouse position relative to the top edge of the document.

  • Number event.pageX

    New in 1.0.4 !

    The mouse position relative to the left edge of the document.

  • jQuery.globalEval( [ String ] code )

    New in 1.0.4 !

    Execute some JavaScript code globally.


Version 1.1 – jQuery API

Version 1.1

  • Anything event.data

    New in 1.1 !

    The optional data passed to jQuery.fn.bind when the current executing handler was bound.

  • jQuery .one( [ String ] eventType, [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.1 !

    Attach a handler to an event for the elements. The handler is executed at most once per element.

  • jQuery.ajaxSetup( [ Options ] options )

    New in 1.1 !

    Set default values for future Ajax requests.

  • jQuery .attr( [ String ] attributeName, [ Function ] function(index, attr) )

    New in 1.1 !

    Set one or more attributes for the set of matched elements.


Version 1.1.2 – jQuery API

Version 1.1.2

  • jQuery .eq( [ Integer ] -index )

    New in 1.4 !

    Reduce the set of matched elements to the one at the specified index.


Version 1.1.3 – jQuery API

Version 1.1.3

  • Number event.which

    New in 1.1.3 !

    For key or button events, this attribute indicates the specific button or key that was pressed.

  • Map jQuery.browser

    New in 1.0 !

    Contains flags for the useragent, read from navigator.userAgent.

  • String jQuery.browser.version

    New in 1.1.3 !

    The version number of the rendering engine for the user's browser.

  • Array jQuery.unique( [ Array ] array )

    New in 1.1.3 !

    Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.


Version 1.1.4 – jQuery API

Version 1.1.4

  • Element event.relatedTarget

    New in 1.1.4 !

    The other DOM element involved in the event, if any.

  • Boolean jQuery.isXMLDoc( [ Element ] node )

    New in 1.1.4 !

    Check to see if a DOM node is within an XML document (or is an XML document).

  • JQuery(":only-child")

    New in 1.1.4 !

    Selects all elements that are the only child of their parent.

  • JQuery(":last-child")

    New in 1.1.4 !

    Selects all elements that are the last child of their parent.

  • JQuery(":first-child")

    New in 1.1.4 !

    Selects all elements that are the first child of their parent.

  • JQuery(":nth-child(index/even/odd/equation)")

    New in 1.1.4 !

    Selects all elements that are the nth-child of their parent.

  • JQuery(":has(selector)")

    New in 1.1.4 !

    Selects elements which contain at least one element that matches the specified selector.

  • JQuery(":contains(text)")

    New in 1.1.4 !

    Select all elements that contain the specified text.

  • jQuery .slice( [ Integer ] start, [ Integer ] end )

    New in 1.1.4 !

    Reduce the set of matched elements to a subset specified by a range of indices.


Version 1.2 – jQuery API

Version 1.2

  • JQuery(":animated")

    New in 1.2 !

    Select all elements that are in the progress of an animation at the time the selector is run.

  • JQuery(":header")

    New in 1.2 !

    Selects all elements that are headers, like h1, h2, h3 and so on.

  • jQuery .dequeue( [ String ] queueName )

    New in 1.2 !

    Execute the next function on the queue for the matched elements.

  • jQuery .queue( [ String ] queueName, [ Function ] callback( next ) )

    New in 1.2 !

    Manipulate the queue of functions to be executed on the matched elements.

  • Object .triggerHandler( [ String ] eventType, [ Array ] extraParameters )

    New in 1.2 !

    Execute all handlers attached to an element for an event.

  • Array .serializeArray( )

    New in 1.2 !

    Encode a set of form elements as an array of names and values.

  • jQuery .stop( [ Boolean ] clearQueue, [ Boolean ] jumpToEnd )

    New in 1.2 !

    Stop the currently-running animation on the matched elements.

  • jQuery .andSelf( )

    New in 1.2 !

    Add the previous set of elements on the stack to the current set.

  • jQuery .prevAll( [ Selector ] selector )

    New in 1.2 !

    Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .nextAll( [ String ] selector )

    New in 1.2 !

    Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.

  • jQuery .contents( )

    New in 1.2 !

    Get the children of each element in the set of matched elements, including text and comment nodes.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

  • boolean jQuery.isFunction( [ Object ] obj )

    New in 1.2 !

    Determine if the argument passed is a Javascript function object.

  • Number jQuery.inArray( [ Any ] value, [ Array ] array )

    New in 1.2 !

    Search for a specified value within an array and return its index (or -1 if not found).

  • Array jQuery.makeArray( [ Object ] obj )

    New in 1.2 !

    Convert an array-like object into a true JavaScript array.

  • Object .position( )

    New in 1.2 !

    Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.

  • jQuery .replaceAll( [ Selector ] target )

    New in 1.2 !

    Replace each target element with the set of matched elements.

  • jQuery .replaceWith( [ Function ] function )

    New in 1.4 !

    Replace each element in the set of matched elements with the provided new content.

  • jQuery .wrapInner( [ Function ] wrappingFunction )

    New in 1.4 !

    Wrap an HTML structure around the content of each element in the set of matched elements.

  • jQuery .wrapAll( [ String | Selector | Element | jQuery ] wrappingElement )

    New in 1.2 !

    Wrap an HTML structure around all elements in the set of matched elements.

  • jQuery .map( [ Function ] callback(index, domElement) )

    New in 1.2 !

    Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

  • Boolean .hasClass( [ String ] className )

    New in 1.2 !

    Determine whether any of the matched elements are assigned the given class.


Version 1.2.3 – jQuery API

Version 1.2.3

  • jQuery jQuery.removeData( [ Element ] element, [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery .removeData( [ String ] name )

    New in 1.2.3 !

    Remove a previously-stored piece of data.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).


Version 1.2.6 – jQuery API

Version 1.2.6

  • Number event.timeStamp

    New in 1.2.6 !

    The difference in milliseconds between the time an event is triggered and January 1, 1970.

  • Integer .outerWidth( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding and border.

  • Integer .outerHeight( [ Boolean ] includeMargin )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.

  • Integer .innerWidth( )

    New in 1.2.6 !

    Get the current computed width for the first element in the set of matched elements, including padding but not border.

  • Integer .innerHeight( )

    New in 1.2.6 !

    Get the current computed height for the first element in the set of matched elements, including padding but not border.

  • jQuery .scrollLeft( [ Number ] value )

    New in 1.2.6 !

    Set the current horizontal position of the scroll bar for each of the set of matched elements.

  • jQuery .scrollTop( [ Number ] value )

    New in 1.2.6 !

    Set the current vertical position of the scroll bar for each of the set of matched elements.


Version 1.3 – jQuery API

Version 1.3

  • Boolean event.isImmediatePropagationStopped( )

    New in 1.3 !

    Returns whether event.stopImmediatePropagation() was ever called on this event object.

  • event.stopImmediatePropagation( )

    New in 1.3 !

    Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.

  • Boolean event.isPropagationStopped( )

    New in 1.3 !

    Returns whether was ever called on this event object.

  • Boolean event.isDefaultPrevented( )

    New in 1.3 !

    Returns whether was ever called on this event object.

  • Object event.result

    New in 1.3 !

    The last value returned by an event handler that was triggered by this event, unless the value was .

  • Element event.currentTarget

    New in 1.3 !

    The current DOM element within the event bubbling phase.

  • Boolean jQuery.fx.off

    New in 1.3 !

    Globally disable all animations.

  • jQuery .pushStack( [ Array ] elements, [ String ] name, [ Array ] arguments )

    New in 1.3 !

    Add a collection of DOM elements onto the jQuery stack.

  • jQuery jQuery.dequeue( [ Element ] element, [ String ] queueName )

    New in 1.3 !

    Execute the next function on the queue for the matched element.

  • jQuery jQuery.queue( [ Element ] element, [ String ] queueName, [ Function ] callback() )

    New in 1.3 !

    Manipulate the queue of functions to be executed on the matched element.

  • jQuery .die( [ Map ] eventTypes )

    New in 1.4.3 !

    Remove an event handler previously attached using from the elements.

  • jQuery .live( [ Object ] events )

    New in 1.4.3 !

    Attach a handler to the event for all elements which match the current selector, now and in the future.

  • Array .closest( [ Array ] selectors, [ Element ] context )

    New in 1.4 !

    Gets an array of all the elements and selectors matched against the current element up through the DOM tree.

  • String selector

    New in 1.3 !

    A selector representing selector originally passed to jQuery().

  • Element context

    New in 1.3 !

    The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document.

  • jQuery .toggle( [ Boolean ] showOrHide )

    New in 1.3 !

    Display or hide the matched elements.

  • boolean jQuery.isArray( [ Object ] obj )

    New in 1.3 !

    Determine whether the argument is an array.

  • Object jQuery.support

    New in 1.3 !

    A collection of properties that represent the presence of different browser features or bugs.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.


Version 1.4 – jQuery API

Version 1.4

  • Function jQuery.proxy( [ Object ] context, [ String ] name )

    New in 1.4 !

    Takes a function and returns a new one that will always have a particular context.

  • jQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusout" JavaScript event.

  • jQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusin" JavaScript event.

  • jQuery .has( [ Element ] contained )

    New in 1.4 !

    Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

  • Boolean jQuery.contains( [ Element ] container, [ Element ] contained )

    New in 1.4 !

    Check to see if a DOM node is within another DOM node.

  • Function jQuery.noop( )

    New in 1.4 !

    An empty function.

  • jQuery .delay( [ Integer ] duration, [ String ] queueName )

    New in 1.4 !

    Set a timer to delay execution of subsequent items in the queue.

  • jQuery .parentsUntil( [ Selector ] selector )

    New in 1.4 !

    Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.

  • jQuery .prevUntil( [ Selector ] selector )

    New in 1.4 !

    Get all preceding siblings of each element up to but not including the element matched by the selector.

  • jQuery .nextUntil( [ Selector ] selector )

    New in 1.4 !

    Get all following siblings of each element up to but not including the element matched by the selector.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery .clearQueue( [ String ] queueName )

    New in 1.4 !

    Remove from the queue all items that have not yet been run.

  • Array .toArray( )

    New in 1.4 !

    Retrieve all the DOM elements contained in the jQuery set, as an array.

  • Boolean jQuery.isEmptyObject( [ Object ] object )

    New in 1.4 !

    Check to see if an object is empty (contains no properties).

  • Boolean jQuery.isPlainObject( [ Object ] object )

    New in 1.4 !

    Check to see if an object is a plain object (created using "{}" or "new Object").

  • Number .index( [ Element | jQuery ] element )

    New in 1.0 !

    Search for a given element from among the matched elements.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • jQuery .bind( [ Object ] events )

    New in 1.4 !

    Attach a handler to an event for the elements.

  • jQuery .first( )

    New in 1.4 !

    Reduce the set of matched elements to the first in the set.

  • jQuery .last( )

    New in 1.4 !

    Reduce the set of matched elements to the final one in the set.

  • jQuery jQuery( [ Function ] callback )

    New in 1.0 !

    Binds a function to be executed when the DOM has finished loading.

  • Array .closest( [ Array ] selectors, [ Element ] context )

    New in 1.4 !

    Gets an array of all the elements and selectors matched against the current element up through the DOM tree.

  • jQuery .add( [ Selector ] selector, [ Element ] context )

    New in 1.4 !

    Add elements to the set of matched elements.

  • jQuery .not( [ Function ] function(index) )

    New in 1.4 !

    Remove elements from the set of matched elements.

  • String jQuery.param( [ Array | Object ] obj, [ Boolean ] traditional )

    New in 1.4 !

    Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

  • jQuery .offset( [ Function ] function(index, coords) )

    New in 1.4 !

    Set the current coordinates of every element in the set of matched elements, relative to the document.

  • jQuery .css( [ Map ] map )

    New in 1.0 !

    Set one or more CSS properties for the set of matched elements.

  • jQuery .unwrap( )

    New in 1.4 !

    Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

  • jQuery .detach( [ Selector ] selector )

    New in 1.4 !

    Remove the set of matched elements from the DOM.

  • jQuery .replaceWith( [ Function ] function )

    New in 1.4 !

    Replace each element in the set of matched elements with the provided new content.

  • jQuery .wrapInner( [ Function ] wrappingFunction )

    New in 1.4 !

    Wrap an HTML structure around the content of each element in the set of matched elements.

  • jQuery .wrapAll( [ String | Selector | Element | jQuery ] wrappingElement )

    New in 1.2 !

    Wrap an HTML structure around all elements in the set of matched elements.

  • jQuery .wrap( [ Function ] function(index) )

    New in 1.4 !

    Wrap an HTML structure around each element in the set of matched elements.

  • jQuery .before( [ Function ] function )

    New in 1.4 !

    Insert content, specified by the parameter, before each element in the set of matched elements.

  • jQuery .after( [ Function ] function(index) )

    New in 1.4 !

    Insert content, specified by the parameter, after each element in the set of matched elements.

  • jQuery .prepend( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

  • jQuery .append( [ Function ] function(index, html) )

    New in 1.4 !

    Insert content, specified by the parameter, to the end of each element in the set of matched elements.

  • jQuery .val( [ Function ] function(index, value) )

    New in 1.4 !

    Set the value of each element in the set of matched elements.

  • jQuery .text( [ Function ] function(index, text) )

    New in 1.4 !

    Set the content of each element in the set of matched elements to the specified text.

  • jQuery .html( [ Function ] function(index, oldhtml) )

    New in 1.4 !

    Set the HTML contents of each element in the set of matched elements.

  • jQuery .toggleClass( [ Function ] function(index, class), [ Boolean ] switch )

    New in 1.4 !

    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

  • jQuery .removeClass( [ Function ] function(index, class) )

    New in 1.4 !

    Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

  • jQuery .removeAttr( [ String ] attributeName )

    New in 1.0 !

    Remove an attribute from each element in the set of matched elements.

  • jQuery .addClass( [ Function ] function(index, currentClass) )

    New in 1.4 !

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


Version 1.4.1 – jQuery API

Version 1.4.1

  • jQuery.error( [ String ] message )

    New in 1.4.1 !

    Takes a string and throws an exception containing it.

  • Object jQuery.parseJSON( [ String ] json )

    New in 1.4.1 !

    Takes a well-formed JSON string and returns the resulting JavaScript object.

  • jQuery .die( [ Map ] eventTypes )

    New in 1.4.3 !

    Remove an event handler previously attached using from the elements.

  • jQuery .width( [ Function ] function(index, width) )

    New in 1.4.1 !

    Set the CSS width of each element in the set of matched elements.

  • jQuery .height( [ Function ] function(index, height) )

    New in 1.4.1 !

    Set the CSS height of every matched element.


Version 1.4.2 – jQuery API

Version 1.4.2

  • jQuery .undelegate( [ String ] namespace )

    New in 1.6 !

    Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.

  • jQuery .delegate( [ String ] selector, [ Map ] events )

    New in 1.4.3 !

    Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.


Version 1.4.3 – jQuery API

Version 1.4.3

  • Number jQuery.now( )

    New in 1.4.3 !

    Return a number representing the current time.

  • Object jQuery.cssHooks

    New in 1.4.3 !

    Provides a way to hook directly into jQuery to override how particular CSS properties are retrieved or set. Amongst other uses, cssHooks can be used to create custom, browser-normalized properties for CSS3 features such as box-shadows and gradients.

  • String jQuery.type( [ Object ] obj )

    New in 1.4.3 !

    Determine the internal JavaScript [[Class]] of an object.

  • boolean jQuery.isWindow( [ Object ] obj )

    New in 1.4.3 !

    Determine whether the argument is a window.

  • Number jQuery.fx.interval

    New in 1.4.3 !

    The rate (in milliseconds) at which animations fire.

  • String event.namespace

    New in 1.4.3 !

    The namespace specified when the event was triggered.

  • jQuery .undelegate( [ String ] namespace )

    New in 1.6 !

    Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.

  • jQuery .delegate( [ String ] selector, [ Map ] events )

    New in 1.4.3 !

    Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

  • jQuery .focusout( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusout" JavaScript event.

  • jQuery .focusin( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "focusin" JavaScript event.

  • Object jQuery.data( [ Element ] element )

    New in 1.4 !

    Returns value at named data store for the element, as set by , or the full data store for the element.

  • jQuery .keydown( )

    New in 1.0 !

    Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.

  • Object .data( )

    New in 1.4 !

    Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • jQuery .scroll( )

    New in 1.0 !

    Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.

  • jQuery .resize( )

    New in 1.0 !

    Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.

  • jQuery .keyup( )

    New in 1.0 !

    Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.

  • jQuery .keypress( )

    New in 1.0 !

    Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.

  • jQuery .submit( )

    New in 1.0 !

    Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

  • jQuery .select( )

    New in 1.0 !

    Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

  • jQuery .change( )

    New in 1.0 !

    Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

  • jQuery .blur( )

    New in 1.0 !

    Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.

  • jQuery .focus( )

    New in 1.0 !

    Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.

  • jQuery .mousemove( )

    New in 1.0 !

    Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.

  • jQuery .mouseleave( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.

  • jQuery .mouseenter( )

    New in 1.0 !

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

  • jQuery .mouseout( )

    New in 1.0 !

    Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.

  • jQuery .mouseover( )

    New in 1.0 !

    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • jQuery .dblclick( )

    New in 1.0 !

    Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.

  • jQuery .click( )

    New in 1.0 !

    Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

  • jQuery .mouseup( )

    New in 1.0 !

    Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.

  • jQuery .mousedown( )

    New in 1.0 !

    Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.

  • jQuery .error( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "error" JavaScript event.

  • jQuery .unload( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "unload" JavaScript event.

  • jQuery .load( [ Object ] eventData, [ Function ] handler(eventObject) )

    New in 1.4.3 !

    Bind an event handler to the "load" JavaScript event.

  • jQuery .die( [ Map ] eventTypes )

    New in 1.4.3 !

    Remove an event handler previously attached using from the elements.

  • jQuery .unbind( [ Object ] event )

    New in 1.0 !

    Remove a previously-attached event handler from the elements.

  • jQuery .bind( [ Object ] events )

    New in 1.4 !

    Attach a handler to an event for the elements.

  • jQuery .fadeTo( [ String,Number ] duration, [ Number ] opacity, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Adjust the opacity of the matched elements.

  • jQuery .fadeOut( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements by fading them to transparent.

  • jQuery .fadeIn( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements by fading them to opaque.

  • jQuery .slideToggle( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display or hide the matched elements with a sliding motion.

  • jQuery .slideUp( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements with a sliding motion.

  • jQuery .slideDown( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements with a sliding motion.

  • jQuery .toggle( [ Boolean ] showOrHide )

    New in 1.3 !

    Display or hide the matched elements.

  • jQuery .hide( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Hide the matched elements.

  • jQuery .show( [ String,Number ] duration, [ String ] easing, [ Callback ] callback )

    New in 1.4.3 !

    Display the matched elements.


Version 1.4.4 – jQuery API

Version 1.4.4

  • jQuery .fadeToggle( [ String,Number ] duration, [ String ] easing, [ Function ] callback )

    New in 1.4.4 !

    Display or hide the matched elements by animating their opacity.


Version 1.5 – jQuery API

Version 1.5

  • undefined jQuery.ajaxPrefilter( [ String ] dataTypes, [ Function ] handler(options, originalOptions, jqXHR) )

    New in 1.5 !

    Handle custom Ajax options or modify existing options before each request is sent and before they are processed by .

  • Boolean jQuery.hasData( [ Element ] element )

    New in 1.5 !

    Determine whether an element has any jQuery data associated with it.

  • Promise .deferred.promise( )

    New in 1.5 !

    Return a Deferred's Promise object.

  • XMLDocument jQuery.parseXML( [ String ] data )

    New in 1.5 !

    Parses a string into an XML document.

  • Promise jQuery.when( [ Deferred ] deferreds )

    New in 1.5 !

    Provides a way to execute callback functions based on one or more objects, usually objects that represent asynchronous events.

  • Deferred .deferred.resolveWith( [ Object ] context, [ Array ] args )

    New in 1.5 !

    Resolve a Deferred object and call any doneCallbacks with the given and .

  • Deferred .deferred.rejectWith( [ Object ] context, [ Array ] args )

    New in 1.5 !

    Reject a Deferred object and call any failCallbacks with the given and .

  • Deferred .deferred.fail( [ Function ] failCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is rejected.

  • Deferred .deferred.done( [ Function ] doneCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is resolved.

  • Deferred .deferred.then( [ Function ] doneCallbacks, [ Function ] failCallbacks )

    New in 1.5 !

    Add handlers to be called when the Deferred object is resolved or rejected.

  • Deferred .deferred.reject( [ Object ] args )

    New in 1.5 !

    Reject a Deferred object and call any failCallbacks with the given .

  • Boolean .deferred.isRejected( )

    New in 1.5 !

    Determine whether a Deferred object has been rejected.

  • Boolean .deferred.isResolved( )

    New in 1.5 !

    Determine whether a Deferred object has been resolved.

  • Deferred .deferred.resolve( [ Object ] args )

    New in 1.5 !

    Resolve a Deferred object and call any doneCallbacks with the given .

  • jQuery jQuery.sub( )

    New in 1.5 !

    Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.

  • jqXHR jQuery.post( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP POST request.

  • XMLHttpRequest jQuery.getScript( [ String ] url, [ Function ] success(data, textStatus) )

    New in 1.0 !

    Load a JavaScript file from the server using a GET HTTP request, then execute it.

  • jqXHR jQuery.getJSON( [ String ] url, [ Map ] data, [ Function ] success(data, textStatus, jqXHR) )

    New in 1.0 !

    Load JSON-encoded data from the server using a GET HTTP request.

  • jqXHR jQuery.get( [ String ] url, [ Map | String ] data, [ Function ] success(data, textStatus, jqXHR), [ String ] dataType )

    New in 1.0 !

    Load data from the server using a HTTP GET request.

  • jqXHR jQuery.ajax( [ Map ] settings )

    New in 1.0 !

    Perform an asynchronous HTTP (Ajax) request.

  • jQuery .clone( [ Boolean ] withDataAndEvents, [ Boolean ] deepWithDataAndEvents )

    New in 1.5 !

    Create a deep copy of the set of matched elements.


Version 1.5.1 – jQuery API

Version 1.5.1

  • jqXHR jQuery.ajax( [ Map ] settings )

    New in 1.0 !

    Perform an asynchronous HTTP (Ajax) request.

  • Object jQuery.support

    New in 1.3 !

    A collection of properties that represent the presence of different browser features or bugs.


Draggable – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Draggable

Overview

The jQuery UI Draggable plugin makes selected elements draggable by mouse.

Draggable elements gets a class of ui-draggable. During drag the element also gets a class of ui-draggable-dragging. If you want not just drag, but drag-and-drop, see the jQuery UI Droppable plugin, which provides a drop target for draggables.

All callbacks (start, stop, drag) receive two arguments: The original browser event and a prepared ui object, view below for a documentation of this object (if you name your second argument 'ui'):

  • ui.helper - the jQuery object representing the helper that's being dragged
  • ui.position - current position of the helper as { top, left } object, relative to the offset element
  • ui.offset - current absolute position of the helper as { top, left } object, relative to page

To manipulate the position of a draggable during drag, you can either use a wrapper as the draggable helper and position the wrapped element with absolute positioning, or you can correct internal values like so: $(this).data('draggable').offset.click.top -= x.

Dependencies

  • UI Core
  • UI Widget
  • UI Mouse

Example

  • Demo
  • View Source

Initialize a draggable with default options.

$("#draggable").draggable();

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
    #draggable { width: 100px; height: 70px; background: silver; }
  </style>
  <script>
  $(document).ready(function() {
    $("#draggable").draggable();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="draggable">Drag me</div>

</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the draggable. Can be set when initialising (first creating) the draggable.

    Code examples

    Initialize a draggable with the disabled option specified.
    $( ".selector" ).draggable({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).draggable( "option", "disabled" );
//setter
$( ".selector" ).draggable( "option", "disabled", true );

  • addClasses

    Type:
    Boolean
    Default:
    true

    If set to false, will prevent the ui-draggable class from being added. This may be desired as a performance optimization when calling .draggable() init on many hundreds of elements.

    Code examples

    Initialize a draggable with the addClasses option specified.
    $( ".selector" ).draggable({ addClasses: false });
    Get or set the addClasses option, after init.
    //getter
var addClasses = $( ".selector" ).draggable( "option", "addClasses" );
//setter
$( ".selector" ).draggable( "option", "addClasses", false );

  • appendTo

    Type:
    Element, Selector
    Default:
    'parent'

    The element passed to or selected by the appendTo option will be used as the draggable helper's container during dragging. By default, the helper is appended to the same container as the draggable.

    Code examples

    Initialize a draggable with the appendTo option specified.
    $( ".selector" ).draggable({ appendTo: 'body' });
    Get or set the appendTo option, after init.
    //getter
var appendTo = $( ".selector" ).draggable( "option", "appendTo" );
//setter
$( ".selector" ).draggable( "option", "appendTo", 'body' );

  • axis

    Type:
    String
    Default:
    false

    Constrains dragging to either the horizontal (x) or vertical (y) axis. Possible values: 'x', 'y'.

    Code examples

    Initialize a draggable with the axis option specified.
    $( ".selector" ).draggable({ axis: 'x' });
    Get or set the axis option, after init.
    //getter
var axis = $( ".selector" ).draggable( "option", "axis" );
//setter
$( ".selector" ).draggable( "option", "axis", 'x' );

  • cancel

    Type:
    Selector
    Default:
    ':input,option'

    Prevents dragging from starting on specified elements.

    Code examples

    Initialize a draggable with the cancel option specified.
    $( ".selector" ).draggable({ cancel: 'button' });
    Get or set the cancel option, after init.
    //getter
var cancel = $( ".selector" ).draggable( "option", "cancel" );
//setter
$( ".selector" ).draggable( "option", "cancel", 'button' );

  • connectToSortable

    Type:
    Selector
    Default:
    false

    Allows the draggable to be dropped onto the specified sortables. If this option is used (helper must be set to 'clone' in order to work flawlessly), a draggable can be dropped onto a sortable list and then becomes part of it.

    Note: Specifying this option as an array of selectors has been removed.

    Code examples

    Initialize a draggable with the connectToSortable option specified.
    $( ".selector" ).draggable({ connectToSortable: 'ul#myList' });
    Get or set the connectToSortable option, after init.
    //getter
var connectToSortable = $( ".selector" ).draggable( "option", "connectToSortable" );
//setter
$( ".selector" ).draggable( "option", "connectToSortable", 'ul#myList' );

  • containment

    Type:
    Selector, Element, String, Array
    Default:
    false

    Constrains dragging to within the bounds of the specified element or region. Possible string values: 'parent', 'document', 'window', [x1, y1, x2, y2].

    Code examples

    Initialize a draggable with the containment option specified.
    $( ".selector" ).draggable({ containment: 'parent' });
    Get or set the containment option, after init.
    //getter
var containment = $( ".selector" ).draggable( "option", "containment" );
//setter
$( ".selector" ).draggable( "option", "containment", 'parent' );

  • cursor

    Type:
    String
    Default:
    'auto'

    The css cursor during the drag operation.

    Code examples

    Initialize a draggable with the cursor option specified.
    $( ".selector" ).draggable({ cursor: 'crosshair' });
    Get or set the cursor option, after init.
    //getter
var cursor = $( ".selector" ).draggable( "option", "cursor" );
//setter
$( ".selector" ).draggable( "option", "cursor", 'crosshair' );

  • cursorAt

    Type:
    Object
    Default:
    false

    Sets the offset of the dragging helper relative to the mouse cursor. Coordinates can be given as a hash using a combination of one or two keys: { top, left, right, bottom }.

    Code examples

    Initialize a draggable with the cursorAt option specified.
    $( ".selector" ).draggable({ cursorAt: { left: 5 } });
    Get or set the cursorAt option, after init.
    //getter
var cursorAt = $( ".selector" ).draggable( "option", "cursorAt" );
//setter
$( ".selector" ).draggable( "option", "cursorAt", { left: 5 } );

  • delay

    Type:
    Integer
    Default:
    0

    Time in milliseconds after mousedown until dragging should start. This option can be used to prevent unwanted drags when clicking on an element.

    Code examples

    Initialize a draggable with the delay option specified.
    $( ".selector" ).draggable({ delay: 500 });
    Get or set the delay option, after init.
    //getter
var delay = $( ".selector" ).draggable( "option", "delay" );
//setter
$( ".selector" ).draggable( "option", "delay", 500 );

  • distance

    Type:
    Integer
    Default:
    1

    Distance in pixels after mousedown the mouse must move before dragging should start. This option can be used to prevent unwanted drags when clicking on an element.

    Code examples

    Initialize a draggable with the distance option specified.
    $( ".selector" ).draggable({ distance: 30 });
    Get or set the distance option, after init.
    //getter
var distance = $( ".selector" ).draggable( "option", "distance" );
//setter
$( ".selector" ).draggable( "option", "distance", 30 );

  • grid

    Type:
    Array
    Default:
    false

    Snaps the dragging helper to a grid, every x and y pixels. Array values: [x, y]

    Code examples

    Initialize a draggable with the grid option specified.
    $( ".selector" ).draggable({ grid: [50, 20] });
    Get or set the grid option, after init.
    //getter
var grid = $( ".selector" ).draggable( "option", "grid" );
//setter
$( ".selector" ).draggable( "option", "grid", [50, 20] );

  • handle

    Type:
    Element, Selector
    Default:
    false

    If specified, restricts drag start click to the specified element(s).

    Code examples

    Initialize a draggable with the handle option specified.
    $( ".selector" ).draggable({ handle: 'h2' });
    Get or set the handle option, after init.
    //getter
var handle = $( ".selector" ).draggable( "option", "handle" );
//setter
$( ".selector" ).draggable( "option", "handle", 'h2' );

  • helper

    Type:
    String, Function
    Default:
    'original'

    Allows for a helper element to be used for dragging display. Possible values: 'original', 'clone', Function. If a function is specified, it must return a DOMElement.

    Code examples

    Initialize a draggable with the helper option specified.
    $( ".selector" ).draggable({ helper: 'clone' });
    Get or set the helper option, after init.
    //getter
var helper = $( ".selector" ).draggable( "option", "helper" );
//setter
$( ".selector" ).draggable( "option", "helper", 'clone' );

  • iframeFix

    Type:
    Boolean, Selector
    Default:
    false

    Prevent iframes from capturing the mousemove events during a drag. Useful in combination with cursorAt, or in any case, if the mouse cursor is not over the helper. If set to true, transparent overlays will be placed over all iframes on the page. If a selector is supplied, the matched iframes will have an overlay placed over them.

    Code examples

    Initialize a draggable with the iframeFix option specified.
    $( ".selector" ).draggable({ iframeFix: true });
    Get or set the iframeFix option, after init.
    //getter
var iframeFix = $( ".selector" ).draggable( "option", "iframeFix" );
//setter
$( ".selector" ).draggable( "option", "iframeFix", true );

  • opacity

    Type:
    Float
    Default:
    false

    Opacity for the helper while being dragged.

    Code examples

    Initialize a draggable with the opacity option specified.
    $( ".selector" ).draggable({ opacity: 0.35 });
    Get or set the opacity option, after init.
    //getter
var opacity = $( ".selector" ).draggable( "option", "opacity" );
//setter
$( ".selector" ).draggable( "option", "opacity", 0.35 );

  • refreshPositions

    Type:
    Boolean
    Default:
    false

    If set to true, all droppable positions are calculated on every mousemove. Caution: This solves issues on highly dynamic pages, but dramatically decreases performance.

    Code examples

    Initialize a draggable with the refreshPositions option specified.
    $( ".selector" ).draggable({ refreshPositions: true });
    Get or set the refreshPositions option, after init.
    //getter
var refreshPositions = $( ".selector" ).draggable( "option", "refreshPositions" );
//setter
$( ".selector" ).draggable( "option", "refreshPositions", true );

  • revert

    Type:
    Boolean, String
    Default:
    false

    If set to true, the element will return to its start position when dragging stops. Possible string values: 'valid', 'invalid'. If set to invalid, revert will only occur if the draggable has not been dropped on a droppable. For valid, it's the other way around.

    Code examples

    Initialize a draggable with the revert option specified.
    $( ".selector" ).draggable({ revert: true });
    Get or set the revert option, after init.
    //getter
var revert = $( ".selector" ).draggable( "option", "revert" );
//setter
$( ".selector" ).draggable( "option", "revert", true );

  • revertDuration

    Type:
    Integer
    Default:
    500

    The duration of the revert animation, in milliseconds. Ignored if revert is false.

    Code examples

    Initialize a draggable with the revertDuration option specified.
    $( ".selector" ).draggable({ revertDuration: 1000 });
    Get or set the revertDuration option, after init.
    //getter
var revertDuration = $( ".selector" ).draggable( "option", "revertDuration" );
//setter
$( ".selector" ).draggable( "option", "revertDuration", 1000 );

  • scope

    Type:
    String
    Default:
    'default'

    Used to group sets of draggable and droppable items, in addition to droppable's accept option. A draggable with the same scope value as a droppable will be accepted by the droppable.

    Code examples

    Initialize a draggable with the scope option specified.
    $( ".selector" ).draggable({ scope: 'tasks' });
    Get or set the scope option, after init.
    //getter
var scope = $( ".selector" ).draggable( "option", "scope" );
//setter
$( ".selector" ).draggable( "option", "scope", 'tasks' );

  • scroll

    Type:
    Boolean
    Default:
    true

    If set to true, container auto-scrolls while dragging.

    Code examples

    Initialize a draggable with the scroll option specified.
    $( ".selector" ).draggable({ scroll: false });
    Get or set the scroll option, after init.
    //getter
var scroll = $( ".selector" ).draggable( "option", "scroll" );
//setter
$( ".selector" ).draggable( "option", "scroll", false );

  • scrollSensitivity

    Type:
    Integer
    Default:
    20

    Distance in pixels from the edge of the viewport after which the viewport should scroll. Distance is relative to pointer, not the draggable.

    Code examples

    Initialize a draggable with the scrollSensitivity option specified.
    $( ".selector" ).draggable({ scrollSensitivity: 40 });
    Get or set the scrollSensitivity option, after init.
    //getter
var scrollSensitivity = $( ".selector" ).draggable( "option", "scrollSensitivity" );
//setter
$( ".selector" ).draggable( "option", "scrollSensitivity", 40 );

  • scrollSpeed

    Type:
    Integer
    Default:
    20

    The speed at which the window should scroll once the mouse pointer gets within the scrollSensitivity distance.

    Code examples

    Initialize a draggable with the scrollSpeed option specified.
    $( ".selector" ).draggable({ scrollSpeed: 40 });
    Get or set the scrollSpeed option, after init.
    //getter
var scrollSpeed = $( ".selector" ).draggable( "option", "scrollSpeed" );
//setter
$( ".selector" ).draggable( "option", "scrollSpeed", 40 );

  • snap

    Type:
    Boolean, Selector
    Default:
    false

    If set to a selector or to true (equivalent to '.ui-draggable'), the draggable will snap to the edges of the selected elements when near an edge of the element.

    Code examples

    Initialize a draggable with the snap option specified.
    $( ".selector" ).draggable({ snap: true });
    Get or set the snap option, after init.
    //getter
var snap = $( ".selector" ).draggable( "option", "snap" );
//setter
$( ".selector" ).draggable( "option", "snap", true );

  • snapMode

    Type:
    String
    Default:
    'both'

    Determines which edges of snap elements the draggable will snap to. Ignored if snap is false. Possible values: 'inner', 'outer', 'both'

    Code examples

    Initialize a draggable with the snapMode option specified.
    $( ".selector" ).draggable({ snapMode: 'outer' });
    Get or set the snapMode option, after init.
    //getter
var snapMode = $( ".selector" ).draggable( "option", "snapMode" );
//setter
$( ".selector" ).draggable( "option", "snapMode", 'outer' );

  • snapTolerance

    Type:
    Integer
    Default:
    20

    The distance in pixels from the snap element edges at which snapping should occur. Ignored if snap is false.

    Code examples

    Initialize a draggable with the snapTolerance option specified.
    $( ".selector" ).draggable({ snapTolerance: 40 });
    Get or set the snapTolerance option, after init.
    //getter
var snapTolerance = $( ".selector" ).draggable( "option", "snapTolerance" );
//setter
$( ".selector" ).draggable( "option", "snapTolerance", 40 );

  • stack

    Type:
    Selector
    Default:
    false

    Controls the z-Index of the set of elements that match the selector, always brings to front the dragged item. Very useful in things like window managers.

    Code examples

    Initialize a draggable with the stack option specified.
    $( ".selector" ).draggable({ stack: ".products" });
    Get or set the stack option, after init.
    //getter
var stack = $( ".selector" ).draggable( "option", "stack" );
//setter
$( ".selector" ).draggable( "option", "stack", ".products" );

  • zIndex

    Type:
    Integer
    Default:
    false

    z-index for the helper while being dragged.

    Code examples

    Initialize a draggable with the zIndex option specified.
    $( ".selector" ).draggable({ zIndex: 2700 });
    Get or set the zIndex option, after init.
    //getter
var zIndex = $( ".selector" ).draggable( "option", "zIndex" );
//setter
$( ".selector" ).draggable( "option", "zIndex", 2700 );

Events

  • create

    Type:
    dragcreate

    This event is triggered when draggable is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).draggable({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: dragcreate.
    $( ".selector" ).bind( "dragcreate", function(event, ui) {
  ...
});

  • start

    Type:
    dragstart

    This event is triggered when dragging starts.

    Code examples

    Supply a callback function to handle the start event as an init option.
    $( ".selector" ).draggable({
   start: function(event, ui) { ... }
});
    Bind to the start event by type: dragstart.
    $( ".selector" ).bind( "dragstart", function(event, ui) {
  ...
});

  • drag

    Type:
    drag

    This event is triggered when the mouse is moved during the dragging.

    Code examples

    Supply a callback function to handle the drag event as an init option.
    $( ".selector" ).draggable({
   drag: function(event, ui) { ... }
});
    Bind to the drag event by type: drag.
    $( ".selector" ).bind( "drag", function(event, ui) {
  ...
});

  • stop

    Type:
    dragstop

    This event is triggered when dragging stops.

    Code examples

    Supply a callback function to handle the stop event as an init option.
    $( ".selector" ).draggable({
   stop: function(event, ui) { ... }
});
    Bind to the stop event by type: dragstop.
    $( ".selector" ).bind( "dragstop", function(event, ui) {
  ...
});

Methods

  • destroy

    Signature:
    .draggable( "destroy" )

    Remove the draggable functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .draggable( "disable" )

    Disable the draggable.

  • enable

    Signature:
    .draggable( "enable" )

    Enable the draggable.

  • option

    Signature:
    .draggable( "option" , optionName , [value] )

    Get or set any draggable option. If no value is specified, will act as a getter.

  • option

    Signature:
    .draggable( "option" , options )

    Set multiple draggable options at once by providing an options object.

  • widget

    Signature:
    .draggable( "widget" )

    Returns the .ui-draggable element.

Theming

The jQuery UI Draggable plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.draggable.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<div class="ui-draggable"></div>

Note: This is a sample of markup generated by the draggable plugin, not markup you should use to create a draggable. The only markup needed for that is <div></div>.


Droppable – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Droppable

Overview

The jQuery UI Droppable plugin makes selected elements droppable (meaning they accept being dropped on by draggables). You can specify which (individually) or which kind of draggables each will accept.

All callbacks receive two arguments: The original browser event and a prepared ui object, view below for a documentation of this object (if you name your second argument 'ui'):

  • ui.draggable - current draggable element, a jQuery object.
  • ui.helper - current draggable helper, a jQuery object
  • ui.position - current position of the draggable helper { top: , left: }
  • ui.offset - current absolute position of the draggable helper { top: , left: }

Dependencies

  • UI Core
  • UI Widget
  • UI Mouse
  • UI Draggable

Example

  • Demo
  • View Source

Makes the div droppable (a drop target for a draggable).

$("#draggable").draggable();
    $("#droppable").droppable({
      drop: function() { alert('dropped'); }
    });

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
    #draggable { width: 75px; height: 25px; background: silver; padding: 10px; }
    #droppable { position: absolute; left: 250px; top: 0; width: 125px; height: 75px; background: gray; color: white; padding: 10px; }
  </style>
  <script>
  $(document).ready(function() {
    $("#draggable").draggable();
    $("#droppable").droppable({
      drop: function() { alert('dropped'); }
    });
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="droppable">Drop here</div>
<div id="draggable">Drag me</div>

</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the droppable. Can be set when initialising (first creating) the droppable.

    Code examples

    Initialize a droppable with the disabled option specified.
    $( ".selector" ).droppable({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).droppable( "option", "disabled" );
//setter
$( ".selector" ).droppable( "option", "disabled", true );

  • accept

    Type:
    Selector, Function
    Default:
    '*'

    All draggables that match the selector will be accepted. If a function is specified, the function will be called for each draggable on the page (passed as the first argument to the function), to provide a custom filter. The function should return true if the draggable should be accepted.

    Code examples

    Initialize a droppable with the accept option specified.
    $( ".selector" ).droppable({ accept: '.special' });
    Get or set the accept option, after init.
    //getter
var accept = $( ".selector" ).droppable( "option", "accept" );
//setter
$( ".selector" ).droppable( "option", "accept", '.special' );

  • activeClass

    Type:
    String
    Default:
    false

    If specified, the class will be added to the droppable while an acceptable draggable is being dragged.

    Code examples

    Initialize a droppable with the activeClass option specified.
    $( ".selector" ).droppable({ activeClass: 'ui-state-highlight' });
    Get or set the activeClass option, after init.
    //getter
var activeClass = $( ".selector" ).droppable( "option", "activeClass" );
//setter
$( ".selector" ).droppable( "option", "activeClass", 'ui-state-highlight' );

  • addClasses

    Type:
    Boolean
    Default:
    true

    If set to false, will prevent the ui-droppable class from being added. This may be desired as a performance optimization when calling .droppable() init on many hundreds of elements.

    Code examples

    Initialize a droppable with the addClasses option specified.
    $( ".selector" ).droppable({ addClasses: false });
    Get or set the addClasses option, after init.
    //getter
var addClasses = $( ".selector" ).droppable( "option", "addClasses" );
//setter
$( ".selector" ).droppable( "option", "addClasses", false );

  • greedy

    Type:
    Boolean
    Default:
    false

    If true, will prevent event propagation on nested droppables.

    Code examples

    Initialize a droppable with the greedy option specified.
    $( ".selector" ).droppable({ greedy: true });
    Get or set the greedy option, after init.
    //getter
var greedy = $( ".selector" ).droppable( "option", "greedy" );
//setter
$( ".selector" ).droppable( "option", "greedy", true );

  • hoverClass

    Type:
    String
    Default:
    false

    If specified, the class will be added to the droppable while an acceptable draggable is being hovered.

    Code examples

    Initialize a droppable with the hoverClass option specified.
    $( ".selector" ).droppable({ hoverClass: 'drophover' });
    Get or set the hoverClass option, after init.
    //getter
var hoverClass = $( ".selector" ).droppable( "option", "hoverClass" );
//setter
$( ".selector" ).droppable( "option", "hoverClass", 'drophover' );

  • scope

    Type:
    String
    Default:
    'default'

    Used to group sets of draggable and droppable items, in addition to droppable's accept option. A draggable with the same scope value as a droppable will be accepted.

    Code examples

    Initialize a droppable with the scope option specified.
    $( ".selector" ).droppable({ scope: 'tasks' });
    Get or set the scope option, after init.
    //getter
var scope = $( ".selector" ).droppable( "option", "scope" );
//setter
$( ".selector" ).droppable( "option", "scope", 'tasks' );

  • tolerance

    Type:
    String
    Default:
    'intersect'

    Specifies which mode to use for testing whether a draggable is 'over' a droppable. Possible values: 'fit', 'intersect', 'pointer', 'touch'.

    • fit: draggable overlaps the droppable entirely
    • intersect: draggable overlaps the droppable at least 50%
    • pointer: mouse pointer overlaps the droppable
    • touch: draggable overlaps the droppable any amount

    Code examples

    Initialize a droppable with the tolerance option specified.
    $( ".selector" ).droppable({ tolerance: 'fit' });
    Get or set the tolerance option, after init.
    //getter
var tolerance = $( ".selector" ).droppable( "option", "tolerance" );
//setter
$( ".selector" ).droppable( "option", "tolerance", 'fit' );

Events

  • create

    Type:
    dropcreate

    This event is triggered when droppable is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).droppable({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: dropcreate.
    $( ".selector" ).bind( "dropcreate", function(event, ui) {
  ...
});

  • activate

    Type:
    dropactivate

    This event is triggered any time an accepted draggable starts dragging. This can be useful if you want to make the droppable 'light up' when it can be dropped on.

    Code examples

    Supply a callback function to handle the activate event as an init option.
    $( ".selector" ).droppable({
   activate: function(event, ui) { ... }
});
    Bind to the activate event by type: dropactivate.
    $( ".selector" ).bind( "dropactivate", function(event, ui) {
  ...
});

  • deactivate

    Type:
    dropdeactivate

    This event is triggered any time an accepted draggable stops dragging.

    Code examples

    Supply a callback function to handle the deactivate event as an init option.
    $( ".selector" ).droppable({
   deactivate: function(event, ui) { ... }
});
    Bind to the deactivate event by type: dropdeactivate.
    $( ".selector" ).bind( "dropdeactivate", function(event, ui) {
  ...
});

  • over

    Type:
    dropover

    This event is triggered as an accepted draggable is dragged 'over' (within the tolerance of) this droppable.

    Code examples

    Supply a callback function to handle the over event as an init option.
    $( ".selector" ).droppable({
   over: function(event, ui) { ... }
});
    Bind to the over event by type: dropover.
    $( ".selector" ).bind( "dropover", function(event, ui) {
  ...
});

  • out

    Type:
    dropout

    This event is triggered when an accepted draggable is dragged out (within the tolerance of) this droppable.

    Code examples

    Supply a callback function to handle the out event as an init option.
    $( ".selector" ).droppable({
   out: function(event, ui) { ... }
});
    Bind to the out event by type: dropout.
    $( ".selector" ).bind( "dropout", function(event, ui) {
  ...
});

  • drop

    Type:
    drop

    This event is triggered when an accepted draggable is dropped 'over' (within the tolerance of) this droppable. In the callback, $(this) represents the droppable the draggable is dropped on. ui.draggable represents the draggable.

    Code examples

    Supply a callback function to handle the drop event as an init option.
    $( ".selector" ).droppable({
   drop: function(event, ui) { ... }
});
    Bind to the drop event by type: drop.
    $( ".selector" ).bind( "drop", function(event, ui) {
  ...
});

Methods

  • destroy

    Signature:
    .droppable( "destroy" )

    Remove the droppable functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .droppable( "disable" )

    Disable the droppable.

  • enable

    Signature:
    .droppable( "enable" )

    Enable the droppable.

  • option

    Signature:
    .droppable( "option" , optionName , [value] )

    Get or set any droppable option. If no value is specified, will act as a getter.

  • option

    Signature:
    .droppable( "option" , options )

    Set multiple droppable options at once by providing an options object.

  • widget

    Signature:
    .droppable( "widget" )

    Returns the .ui-droppable element.

Theming

The jQuery UI Droppable plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.droppable.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<div class="ui-droppable"></div>

Note: This is a sample of markup generated by the droppable plugin, not markup you should use to create a droppable. The only markup needed for that is <div></div>.


Resizable – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Resizable

Overview

The jQuery UI Resizable plugin makes selected elements resizable (meaning they have draggable resize handles). You can specify one or more handles as well as min and max width and height.

All callbacks (start,stop,resize) receive two arguments: The original browser event and a prepared ui object. The ui object has the following fields:

  • ui.helper - a jQuery object containing the helper element
  • ui.originalPosition - {top, left} before resizing started
  • ui.originalSize - {width, height} before resizing started
  • ui.position - {top, left} current position
  • ui.size - {width, height} current size

Dependencies

  • UI Core
  • UI Widget
  • UI Mouse

Example

  • Demo
  • View Source

A simple jQuery UI Resizable.

$("#resizable").resizable();

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
    #resizable { width: 100px; height: 100px; background: silver; }
  </style>
  <script>
  $(document).ready(function() {
    $("#resizable").resizable();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="resizable"></div>

</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the resizable. Can be set when initialising (first creating) the resizable.

    Code examples

    Initialize a resizable with the disabled option specified.
    $( ".selector" ).resizable({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).resizable( "option", "disabled" );
//setter
$( ".selector" ).resizable( "option", "disabled", true );

  • alsoResize

    Type:
    Selector, jQuery, Element
    Default:
    false

    Resize these elements synchronous when resizing.

    Code examples

    Initialize a resizable with the alsoResize option specified.
    $( ".selector" ).resizable({ alsoResize: '.other' });
    Get or set the alsoResize option, after init.
    //getter
var alsoResize = $( ".selector" ).resizable( "option", "alsoResize" );
//setter
$( ".selector" ).resizable( "option", "alsoResize", '.other' );

  • animate

    Type:
    Boolean
    Default:
    false

    Animates to the final size after resizing.

    Code examples

    Initialize a resizable with the animate option specified.
    $( ".selector" ).resizable({ animate: true });
    Get or set the animate option, after init.
    //getter
var animate = $( ".selector" ).resizable( "option", "animate" );
//setter
$( ".selector" ).resizable( "option", "animate", true );

  • animateDuration

    Type:
    Integer, String
    Default:
    'slow'

    Duration time for animating, in milliseconds. Other possible values: 'slow', 'normal', 'fast'.

    Code examples

    Initialize a resizable with the animateDuration option specified.
    $( ".selector" ).resizable({ animateDuration: 500 });
    Get or set the animateDuration option, after init.
    //getter
var animateDuration = $( ".selector" ).resizable( "option", "animateDuration" );
//setter
$( ".selector" ).resizable( "option", "animateDuration", 500 );

  • animateEasing

    Type:
    String
    Default:
    'swing'

    Easing effect for animating.

    Code examples

    Initialize a resizable with the animateEasing option specified.
    $( ".selector" ).resizable({ animateEasing: 'swing' });
    Get or set the animateEasing option, after init.
    //getter
var animateEasing = $( ".selector" ).resizable( "option", "animateEasing" );
//setter
$( ".selector" ).resizable( "option", "animateEasing", 'swing' );

  • aspectRatio

    Type:
    Boolean, Float
    Default:
    false

    If set to true, resizing is constrained by the original aspect ratio. Otherwise a custom aspect ratio can be specified, such as 9 / 16, or 0.5.

    Code examples

    Initialize a resizable with the aspectRatio option specified.
    $( ".selector" ).resizable({ aspectRatio: .75 });
    Get or set the aspectRatio option, after init.
    //getter
var aspectRatio = $( ".selector" ).resizable( "option", "aspectRatio" );
//setter
$( ".selector" ).resizable( "option", "aspectRatio", .75 );

  • autoHide

    Type:
    Boolean
    Default:
    false

    If set to true, automatically hides the handles except when the mouse hovers over the element.

    Code examples

    Initialize a resizable with the autoHide option specified.
    $( ".selector" ).resizable({ autoHide: true });
    Get or set the autoHide option, after init.
    //getter
var autoHide = $( ".selector" ).resizable( "option", "autoHide" );
//setter
$( ".selector" ).resizable( "option", "autoHide", true );

  • cancel

    Type:
    Selector
    Default:
    ':input,option'

    Prevents resizing if you start on elements matching the selector.

    Code examples

    Initialize a resizable with the cancel option specified.
    $( ".selector" ).resizable({ cancel: ':input,option' });
    Get or set the cancel option, after init.
    //getter
var cancel = $( ".selector" ).resizable( "option", "cancel" );
//setter
$( ".selector" ).resizable( "option", "cancel", ':input,option' );

  • containment

    Type:
    String, Element, Selector
    Default:
    false

    Constrains resizing to within the bounds of the specified element. Possible values: 'parent', 'document', a DOMElement, or a Selector.

    Code examples

    Initialize a resizable with the containment option specified.
    $( ".selector" ).resizable({ containment: 'parent' });
    Get or set the containment option, after init.
    //getter
var containment = $( ".selector" ).resizable( "option", "containment" );
//setter
$( ".selector" ).resizable( "option", "containment", 'parent' );

  • delay

    Type:
    Integer
    Default:
    0

    Tolerance, in milliseconds, for when resizing should start. If specified, resizing will not start until after mouse is moved beyond duration. This can help prevent unintended resizing when clicking on an element.

    Code examples

    Initialize a resizable with the delay option specified.
    $( ".selector" ).resizable({ delay: 20 });
    Get or set the delay option, after init.
    //getter
var delay = $( ".selector" ).resizable( "option", "delay" );
//setter
$( ".selector" ).resizable( "option", "delay", 20 );

  • distance

    Type:
    Integer
    Default:
    1

    Tolerance, in pixels, for when resizing should start. If specified, resizing will not start until after mouse is moved beyond distance. This can help prevent unintended resizing when clicking on an element.

    Code examples

    Initialize a resizable with the distance option specified.
    $( ".selector" ).resizable({ distance: 20 });
    Get or set the distance option, after init.
    //getter
var distance = $( ".selector" ).resizable( "option", "distance" );
//setter
$( ".selector" ).resizable( "option", "distance", 20 );

  • ghost

    Type:
    Boolean
    Default:
    false

    If set to true, a semi-transparent helper element is shown for resizing.

    Code examples

    Initialize a resizable with the ghost option specified.
    $( ".selector" ).resizable({ ghost: true });
    Get or set the ghost option, after init.
    //getter
var ghost = $( ".selector" ).resizable( "option", "ghost" );
//setter
$( ".selector" ).resizable( "option", "ghost", true );

  • grid

    Type:
    Array
    Default:
    false

    Snaps the resizing element to a grid, every x and y pixels. Array values: [x, y]

    Code examples

    Initialize a resizable with the grid option specified.
    $( ".selector" ).resizable({ grid: [50, 50] });
    Get or set the grid option, after init.
    //getter
var grid = $( ".selector" ).resizable( "option", "grid" );
//setter
$( ".selector" ).resizable( "option", "grid", [50, 50] );

  • handles

    Type:
    String, Object
    Default:
    'e, s, se'

    If specified as a string, should be a comma-split list of any of the following: 'n, e, s, w, ne, se, sw, nw, all'. The necessary handles will be auto-generated by the plugin.

    If specified as an object, the following keys are supported: { n, e, s, w, ne, se, sw, nw }. The value of any specified should be a jQuery selector matching the child element of the resizable to use as that handle. If the handle is not a child of the resizable, you can pass in the DOMElement or a valid jQuery object directly.

    Code examples

    Initialize a resizable with the handles option specified.
    $( ".selector" ).resizable({ handles: 'n, e, s, w' });
    Get or set the handles option, after init.
    //getter
var handles = $( ".selector" ).resizable( "option", "handles" );
//setter
$( ".selector" ).resizable( "option", "handles", 'n, e, s, w' );

  • helper

    Type:
    String
    Default:
    false

    This is the css class that will be added to a proxy element to outline the resize during the drag of the resize handle. Once the resize is complete, the original element is sized.

    Code examples

    Initialize a resizable with the helper option specified.
    $( ".selector" ).resizable({ helper: 'ui-state-highlight' });
    Get or set the helper option, after init.
    //getter
var helper = $( ".selector" ).resizable( "option", "helper" );
//setter
$( ".selector" ).resizable( "option", "helper", 'ui-state-highlight' );

  • maxHeight

    Type:
    Integer
    Default:
    null

    This is the maximum height the resizable should be allowed to resize to.

    Code examples

    Initialize a resizable with the maxHeight option specified.
    $( ".selector" ).resizable({ maxHeight: 300 });
    Get or set the maxHeight option, after init.
    //getter
var maxHeight = $( ".selector" ).resizable( "option", "maxHeight" );
//setter
$( ".selector" ).resizable( "option", "maxHeight", 300 );

  • maxWidth

    Type:
    Integer
    Default:
    null

    This is the maximum width the resizable should be allowed to resize to.

    Code examples

    Initialize a resizable with the maxWidth option specified.
    $( ".selector" ).resizable({ maxWidth: 250 });
    Get or set the maxWidth option, after init.
    //getter
var maxWidth = $( ".selector" ).resizable( "option", "maxWidth" );
//setter
$( ".selector" ).resizable( "option", "maxWidth", 250 );

  • minHeight

    Type:
    Integer
    Default:
    10

    This is the minimum height the resizable should be allowed to resize to.

    Code examples

    Initialize a resizable with the minHeight option specified.
    $( ".selector" ).resizable({ minHeight: 150 });
    Get or set the minHeight option, after init.
    //getter
var minHeight = $( ".selector" ).resizable( "option", "minHeight" );
//setter
$( ".selector" ).resizable( "option", "minHeight", 150 );

  • minWidth

    Type:
    Integer
    Default:
    10

    This is the minimum width the resizable should be allowed to resize to.

    Code examples

    Initialize a resizable with the minWidth option specified.
    $( ".selector" ).resizable({ minWidth: 75 });
    Get or set the minWidth option, after init.
    //getter
var minWidth = $( ".selector" ).resizable( "option", "minWidth" );
//setter
$( ".selector" ).resizable( "option", "minWidth", 75 );

Events

  • create

    Type:
    resizecreate

    This event is triggered when resizable is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).resizable({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: resizecreate.
    $( ".selector" ).bind( "resizecreate", function(event, ui) {
  ...
});

  • start

    Type:
    resizestart

    This event is triggered at the start of a resize operation.

    Code examples

    Supply a callback function to handle the start event as an init option.
    $( ".selector" ).resizable({
   start: function(event, ui) { ... }
});
    Bind to the start event by type: resizestart.
    $( ".selector" ).bind( "resizestart", function(event, ui) {
  ...
});

  • resize

    Type:
    resize

    This event is triggered during the resize, on the drag of the resize handler.

    Code examples

    Supply a callback function to handle the resize event as an init option.
    $( ".selector" ).resizable({
   resize: function(event, ui) { ... }
});
    Bind to the resize event by type: resize.
    $( ".selector" ).bind( "resize", function(event, ui) {
  ...
});

  • stop

    Type:
    resizestop

    This event is triggered at the end of a resize operation.

    Code examples

    Supply a callback function to handle the stop event as an init option.
    $( ".selector" ).resizable({
   stop: function(event, ui) { ... }
});
    Bind to the stop event by type: resizestop.
    $( ".selector" ).bind( "resizestop", function(event, ui) {
  ...
});

Methods

  • destroy

    Signature:
    .resizable( "destroy" )

    Remove the resizable functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .resizable( "disable" )

    Disable the resizable.

  • enable

    Signature:
    .resizable( "enable" )

    Enable the resizable.

  • option

    Signature:
    .resizable( "option" , optionName , [value] )

    Get or set any resizable option. If no value is specified, will act as a getter.

  • option

    Signature:
    .resizable( "option" , options )

    Set multiple resizable options at once by providing an options object.

  • widget

    Signature:
    .resizable( "widget" )

    Returns the .ui-resizable element.

Theming

The jQuery UI Resizable plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.resizable.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<div class="ui-resizable">
<div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-e"></div>
<div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-s"></div>
<div unselectable="on" style="z-index: 1001; -moz-user-select: none;" class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se"></div>
</div>

Note: This is a sample of markup generated by the resizable plugin, not markup you should use to create a resizable. The only markup needed for that is <div></div>.


Selectable – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Selectable

Overview

The jQuery UI Selectable plugin allows for elements to be selected by dragging a box (sometimes called a lasso) with the mouse over the elements. Also, elements can be selected by click or drag while holding the Ctrl/Meta key, allowing for multiple (non-contiguous) selections.

Dependencies

  • UI Core
  • UI Widget
  • UI Mouse

Example

  • Demo
  • View Source

A simple jQuery UI Selectable.

$("#selectable").selectable();

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
#selectable .ui-selecting {
    background: silver;
}
#selectable .ui-selected {
    background: gray;
}
</style>

  <script>
  $(document).ready(function() {
    $("#selectable").selectable();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<ul id="selectable">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>

</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the selectable. Can be set when initialising (first creating) the selectable.

    Code examples

    Initialize a selectable with the disabled option specified.
    $( ".selector" ).selectable({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).selectable( "option", "disabled" );
//setter
$( ".selector" ).selectable( "option", "disabled", true );

  • autoRefresh

    Type:
    Boolean
    Default:
    true

    This determines whether to refresh (recalculate) the position and size of each selectee at the beginning of each select operation. If you have many many items, you may want to set this to false and call the refresh method manually.

    Code examples

    Initialize a selectable with the autoRefresh option specified.
    $( ".selector" ).selectable({ autoRefresh: false });
    Get or set the autoRefresh option, after init.
    //getter
var autoRefresh = $( ".selector" ).selectable( "option", "autoRefresh" );
//setter
$( ".selector" ).selectable( "option", "autoRefresh", false );

  • cancel

    Type:
    Selector
    Default:
    ':input,option'

    Prevents selecting if you start on elements matching the selector.

    Code examples

    Initialize a selectable with the cancel option specified.
    $( ".selector" ).selectable({ cancel: ':input,option' });
    Get or set the cancel option, after init.
    //getter
var cancel = $( ".selector" ).selectable( "option", "cancel" );
//setter
$( ".selector" ).selectable( "option", "cancel", ':input,option' );

  • delay

    Type:
    Integer
    Default:
    0

    Time in milliseconds to define when the selecting should start. It helps preventing unwanted selections when clicking on an element.

    Code examples

    Initialize a selectable with the delay option specified.
    $( ".selector" ).selectable({ delay: 20 });
    Get or set the delay option, after init.
    //getter
var delay = $( ".selector" ).selectable( "option", "delay" );
//setter
$( ".selector" ).selectable( "option", "delay", 20 );

  • distance

    Type:
    Integer
    Default:
    0

    Tolerance, in pixels, for when selecting should start. If specified, selecting will not start until after mouse is dragged beyond distance.

    Code examples

    Initialize a selectable with the distance option specified.
    $( ".selector" ).selectable({ distance: 20 });
    Get or set the distance option, after init.
    //getter
var distance = $( ".selector" ).selectable( "option", "distance" );
//setter
$( ".selector" ).selectable( "option", "distance", 20 );

  • filter

    Type:
    Selector
    Default:
    '*'

    The matching child elements will be made selectees (able to be selected).

    Code examples

    Initialize a selectable with the filter option specified.
    $( ".selector" ).selectable({ filter: 'li' });
    Get or set the filter option, after init.
    //getter
var filter = $( ".selector" ).selectable( "option", "filter" );
//setter
$( ".selector" ).selectable( "option", "filter", 'li' );

  • tolerance

    Type:
    String
    Default:
    'touch'

    Possible values: 'touch', 'fit'.

    • fit: draggable overlaps the droppable entirely
    • touch: draggable overlaps the droppable any amount

    Code examples

    Initialize a selectable with the tolerance option specified.
    $( ".selector" ).selectable({ tolerance: 'fit' });
    Get or set the tolerance option, after init.
    //getter
var tolerance = $( ".selector" ).selectable( "option", "tolerance" );
//setter
$( ".selector" ).selectable( "option", "tolerance", 'fit' );

Events

  • create

    Type:
    selectablecreate

    This event is triggered when selectable is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).selectable({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: selectablecreate.
    $( ".selector" ).bind( "selectablecreate", function(event, ui) {
  ...
});

  • selected

    Type:
    selectableselected

    This event is triggered at the end of the select operation, on each element added to the selection.

    Code examples

    Supply a callback function to handle the selected event as an init option.
    $( ".selector" ).selectable({
   selected: function(event, ui) { ... }
});
    Bind to the selected event by type: selectableselected.
    $( ".selector" ).bind( "selectableselected", function(event, ui) {
  ...
});

  • selecting

    Type:
    selectableselecting

    This event is triggered during the select operation, on each element added to the selection.

    Code examples

    Supply a callback function to handle the selecting event as an init option.
    $( ".selector" ).selectable({
   selecting: function(event, ui) { ... }
});
    Bind to the selecting event by type: selectableselecting.
    $( ".selector" ).bind( "selectableselecting", function(event, ui) {
  ...
});

  • start

    Type:
    selectablestart

    This event is triggered at the beginning of the select operation.

    Code examples

    Supply a callback function to handle the start event as an init option.
    $( ".selector" ).selectable({
   start: function(event, ui) { ... }
});
    Bind to the start event by type: selectablestart.
    $( ".selector" ).bind( "selectablestart", function(event, ui) {
  ...
});

  • stop

    Type:
    selectablestop

    This event is triggered at the end of the select operation.

    Code examples

    Supply a callback function to handle the stop event as an init option.
    $( ".selector" ).selectable({
   stop: function(event, ui) { ... }
});
    Bind to the stop event by type: selectablestop.
    $( ".selector" ).bind( "selectablestop", function(event, ui) {
  ...
});

  • unselected

    Type:
    selectableunselected

    This event is triggered at the end of the select operation, on each element removed from the selection.

    Code examples

    Supply a callback function to handle the unselected event as an init option.
    $( ".selector" ).selectable({
   unselected: function(event, ui) { ... }
});
    Bind to the unselected event by type: selectableunselected.
    $( ".selector" ).bind( "selectableunselected", function(event, ui) {
  ...
});

  • unselecting

    Type:
    selectableunselecting

    This event is triggered during the select operation, on each element removed from the selection.

    Code examples

    Supply a callback function to handle the unselecting event as an init option.
    $( ".selector" ).selectable({
   unselecting: function(event, ui) { ... }
});
    Bind to the unselecting event by type: selectableunselecting.
    $( ".selector" ).bind( "selectableunselecting", function(event, ui) {
  ...
});

Methods

  • destroy

    Signature:
    .selectable( "destroy" )

    Remove the selectable functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .selectable( "disable" )

    Disable the selectable.

  • enable

    Signature:
    .selectable( "enable" )

    Enable the selectable.

  • option

    Signature:
    .selectable( "option" , optionName , [value] )

    Get or set any selectable option. If no value is specified, will act as a getter.

  • option

    Signature:
    .selectable( "option" , options )

    Set multiple selectable options at once by providing an options object.

  • widget

    Signature:
    .selectable( "widget" )

    Returns the .ui-selectable element.

  • refresh

    Signature:
    .selectable( "refresh" )

    Refresh the position and size of each selectee element. This method can be used to manually recalculate the position and size of each selectee element. Very useful if autoRefresh is set to false.

Theming

The jQuery UI Selectable plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.selectable.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<ul class="ui-selectable">
<li class="ui-selectee"></li>
<li class="ui-selectee"></li>
<li class="ui-selectee"></li>
</ul>

Note: This is a sample of markup generated by the selectable plugin, not markup you should use to create a selectable. The only markup needed for that is
<ul>
<li></li>
<li></li>
<li></li>
</ul>.


Sortable – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Sortable

Overview

The jQuery UI Sortable plugin makes selected elements sortable by dragging with the mouse.

All callbacks receive two arguments: The original browser event and a prepared ui object, view below for a documentation of this object (if you name your second argument 'ui'):

  • ui.helper - the current helper element (most often a clone of the item)
  • ui.position - current position of the helper
  • ui.offset - current absolute position of the helper
  • ui.item - the current dragged element
  • ui.placeholder - the placeholder (if you defined one)
  • ui.sender - the sortable where the item comes from (only exists if you move from one connected list to another)

Dependencies

  • UI Core
  • UI Widget
  • UI Mouse

Example

  • Demo
  • View Source

A simple jQuery UI Sortable.

$("#sortable").sortable();

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("#sortable").sortable();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<ul id="sortable">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>

</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the sortable. Can be set when initialising (first creating) the sortable.

    Code examples

    Initialize a sortable with the disabled option specified.
    $( ".selector" ).sortable({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).sortable( "option", "disabled" );
//setter
$( ".selector" ).sortable( "option", "disabled", true );

  • appendTo

    Type:
    String
    Default:
    'parent'

    Defines where the helper that moves with the mouse is being appended to during the drag (for example, to resolve overlap/zIndex issues).

    Code examples

    Initialize a sortable with the appendTo option specified.
    $( ".selector" ).sortable({ appendTo: 'body' });
    Get or set the appendTo option, after init.
    //getter
var appendTo = $( ".selector" ).sortable( "option", "appendTo" );
//setter
$( ".selector" ).sortable( "option", "appendTo", 'body' );

  • axis

    Type:
    String
    Default:
    false

    If defined, the items can be dragged only horizontally or vertically. Possible values:'x', 'y'.

    Code examples

    Initialize a sortable with the axis option specified.
    $( ".selector" ).sortable({ axis: 'x' });
    Get or set the axis option, after init.
    //getter
var axis = $( ".selector" ).sortable( "option", "axis" );
//setter
$( ".selector" ).sortable( "option", "axis", 'x' );

  • cancel

    Type:
    Selector
    Default:
    ':input,button'

    Prevents sorting if you start on elements matching the selector.

    Code examples

    Initialize a sortable with the cancel option specified.
    $( ".selector" ).sortable({ cancel: 'button' });
    Get or set the cancel option, after init.
    //getter
var cancel = $( ".selector" ).sortable( "option", "cancel" );
//setter
$( ".selector" ).sortable( "option", "cancel", 'button' );

  • connectWith

    Type:
    Selector
    Default:
    false

    Takes a jQuery selector with items that also have sortables applied. If used, the sortable is now connected to the other one-way, so you can drag from this sortable to the other.

    Code examples

    Initialize a sortable with the connectWith option specified.
    $( ".selector" ).sortable({ connectWith: '.otherlist' });
    Get or set the connectWith option, after init.
    //getter
var connectWith = $( ".selector" ).sortable( "option", "connectWith" );
//setter
$( ".selector" ).sortable( "option", "connectWith", '.otherlist' );

  • containment

    Type:
    Element, String, Selector
    Default:
    false

    Constrains dragging to within the bounds of the specified element - can be a DOM element, 'parent', 'document', 'window', or a jQuery selector.

    Note: the element specified for containment must have a calculated width and height (though it need not be explicit), so for example, if you have float:left sortable children and specify containment:'parent' be sure to have float:left on the sortable/parent container as well or it will have height: 0, causing undefined behavior.

    Code examples

    Initialize a sortable with the containment option specified.
    $( ".selector" ).sortable({ containment: 'parent' });
    Get or set the containment option, after init.
    //getter
var containment = $( ".selector" ).sortable( "option", "containment" );
//setter
$( ".selector" ).sortable( "option", "containment", 'parent' );

  • cursor

    Type:
    String
    Default:
    'auto'

    Defines the cursor that is being shown while sorting.

    Code examples

    Initialize a sortable with the cursor option specified.
    $( ".selector" ).sortable({ cursor: 'crosshair' });
    Get or set the cursor option, after init.
    //getter
var cursor = $( ".selector" ).sortable( "option", "cursor" );
//setter
$( ".selector" ).sortable( "option", "cursor", 'crosshair' );

  • cursorAt

    Type:
    Object
    Default:
    false

    Moves the sorting element or helper so the cursor always appears to drag from the same position. Coordinates can be given as a hash using a combination of one or two keys: { top, left, right, bottom }.

    Code examples

    Initialize a sortable with the cursorAt option specified.
    $( ".selector" ).sortable({ cursorAt: 'top' });
    Get or set the cursorAt option, after init.
    //getter
var cursorAt = $( ".selector" ).sortable( "option", "cursorAt" );
//setter
$( ".selector" ).sortable( "option", "cursorAt", 'top' );

  • delay

    Type:
    Integer
    Default:
    0

    Time in milliseconds to define when the sorting should start. It helps preventing unwanted drags when clicking on an element.

    Code examples

    Initialize a sortable with the delay option specified.
    $( ".selector" ).sortable({ delay: 500 });
    Get or set the delay option, after init.
    //getter
var delay = $( ".selector" ).sortable( "option", "delay" );
//setter
$( ".selector" ).sortable( "option", "delay", 500 );

  • distance

    Type:
    Integer
    Default:
    1

    Tolerance, in pixels, for when sorting should start. If specified, sorting will not start until after mouse is dragged beyond distance. Can be used to allow for clicks on elements within a handle.

    Code examples

    Initialize a sortable with the distance option specified.
    $( ".selector" ).sortable({ distance: 30 });
    Get or set the distance option, after init.
    //getter
var distance = $( ".selector" ).sortable( "option", "distance" );
//setter
$( ".selector" ).sortable( "option", "distance", 30 );

  • dropOnEmpty

    Type:
    Boolean
    Default:
    true

    If false items from this sortable can't be dropped to an empty linked sortable.

    Code examples

    Initialize a sortable with the dropOnEmpty option specified.
    $( ".selector" ).sortable({ dropOnEmpty: false });
    Get or set the dropOnEmpty option, after init.
    //getter
var dropOnEmpty = $( ".selector" ).sortable( "option", "dropOnEmpty" );
//setter
$( ".selector" ).sortable( "option", "dropOnEmpty", false );

  • forceHelperSize

    Type:
    Boolean
    Default:
    false

    If true, forces the helper to have a size.

    Code examples

    Initialize a sortable with the forceHelperSize option specified.
    $( ".selector" ).sortable({ forceHelperSize: true });
    Get or set the forceHelperSize option, after init.
    //getter
var forceHelperSize = $( ".selector" ).sortable( "option", "forceHelperSize" );
//setter
$( ".selector" ).sortable( "option", "forceHelperSize", true );

  • forcePlaceholderSize

    Type:
    Boolean
    Default:
    false

    If true, forces the placeholder to have a size.

    Code examples

    Initialize a sortable with the forcePlaceholderSize option specified.
    $( ".selector" ).sortable({ forcePlaceholderSize: true });
    Get or set the forcePlaceholderSize option, after init.
    //getter
var forcePlaceholderSize = $( ".selector" ).sortable( "option", "forcePlaceholderSize" );
//setter
$( ".selector" ).sortable( "option", "forcePlaceholderSize", true );

  • grid

    Type:
    Array
    Default:
    false

    Snaps the sorting element or helper to a grid, every x and y pixels. Array values: [x, y]

    Code examples

    Initialize a sortable with the grid option specified.
    $( ".selector" ).sortable({ grid: [50, 20] });
    Get or set the grid option, after init.
    //getter
var grid = $( ".selector" ).sortable( "option", "grid" );
//setter
$( ".selector" ).sortable( "option", "grid", [50, 20] );

  • handle

    Type:
    Selector, Element
    Default:
    false

    Restricts sort start click to the specified element.

    Code examples

    Initialize a sortable with the handle option specified.
    $( ".selector" ).sortable({ handle: 'h2' });
    Get or set the handle option, after init.
    //getter
var handle = $( ".selector" ).sortable( "option", "handle" );
//setter
$( ".selector" ).sortable( "option", "handle", 'h2' );

  • helper

    Type:
    String, Function
    Default:
    'original'

    Allows for a helper element to be used for dragging display. The supplied function receives the event and the element being sorted, and should return a DOMElement to be used as a custom proxy helper. Possible values: 'original', 'clone'

    Code examples

    Initialize a sortable with the helper option specified.
    $( ".selector" ).sortable({ helper: 'clone' });
    Get or set the helper option, after init.
    //getter
var helper = $( ".selector" ).sortable( "option", "helper" );
//setter
$( ".selector" ).sortable( "option", "helper", 'clone' );

  • items

    Type:
    Selector
    Default:
    '> *'

    Specifies which items inside the element should be sortable.

    Code examples

    Initialize a sortable with the items option specified.
    $( ".selector" ).sortable({ items: 'li' });
    Get or set the items option, after init.
    //getter
var items = $( ".selector" ).sortable( "option", "items" );
//setter
$( ".selector" ).sortable( "option", "items", 'li' );

  • opacity

    Type:
    Float
    Default:
    false

    Defines the opacity of the helper while sorting. From 0.01 to 1

    Code examples

    Initialize a sortable with the opacity option specified.
    $( ".selector" ).sortable({ opacity: 0.6 });
    Get or set the opacity option, after init.
    //getter
var opacity = $( ".selector" ).sortable( "option", "opacity" );
//setter
$( ".selector" ).sortable( "option", "opacity", 0.6 );

  • placeholder

    Type:
    String
    Default:
    false

    Class that gets applied to the otherwise white space.

    Code examples

    Initialize a sortable with the placeholder option specified.
    $( ".selector" ).sortable({ placeholder: 'ui-state-highlight' });
    Get or set the placeholder option, after init.
    //getter
var placeholder = $( ".selector" ).sortable( "option", "placeholder" );
//setter
$( ".selector" ).sortable( "option", "placeholder", 'ui-state-highlight' );

  • revert

    Type:
    Boolean/Integer
    Default:
    false

    If set to true, the item will be reverted to its new DOM position with a smooth animation. Optionally, it can also be set to a number that controls the duration of the animation in ms.

    Code examples

    Initialize a sortable with the revert option specified.
    $( ".selector" ).sortable({ revert: true });
    Get or set the revert option, after init.
    //getter
var revert = $( ".selector" ).sortable( "option", "revert" );
//setter
$( ".selector" ).sortable( "option", "revert", true );

  • scroll

    Type:
    Boolean
    Default:
    true

    If set to true, the page scrolls when coming to an edge.

    Code examples

    Initialize a sortable with the scroll option specified.
    $( ".selector" ).sortable({ scroll: false });
    Get or set the scroll option, after init.
    //getter
var scroll = $( ".selector" ).sortable( "option", "scroll" );
//setter
$( ".selector" ).sortable( "option", "scroll", false );

  • scrollSensitivity

    Type:
    Integer
    Default:
    20

    Defines how near the mouse must be to an edge to start scrolling.

    Code examples

    Initialize a sortable with the scrollSensitivity option specified.
    $( ".selector" ).sortable({ scrollSensitivity: 40 });
    Get or set the scrollSensitivity option, after init.
    //getter
var scrollSensitivity = $( ".selector" ).sortable( "option", "scrollSensitivity" );
//setter
$( ".selector" ).sortable( "option", "scrollSensitivity", 40 );

  • scrollSpeed

    Type:
    Integer
    Default:
    20

    The speed at which the window should scroll once the mouse pointer gets within the scrollSensitivity distance.

    Code examples

    Initialize a sortable with the scrollSpeed option specified.
    $( ".selector" ).sortable({ scrollSpeed: 40 });
    Get or set the scrollSpeed option, after init.
    //getter
var scrollSpeed = $( ".selector" ).sortable( "option", "scrollSpeed" );
//setter
$( ".selector" ).sortable( "option", "scrollSpeed", 40 );

  • tolerance

    Type:
    String
    Default:
    'intersect'

    This is the way the reordering behaves during drag. Possible values: 'intersect', 'pointer'. In some setups, 'pointer' is more natural.

    • intersect: draggable overlaps the droppable at least 50%
    • pointer: mouse pointer overlaps the droppable

    Code examples

    Initialize a sortable with the tolerance option specified.
    $( ".selector" ).sortable({ tolerance: 'pointer' });
    Get or set the tolerance option, after init.
    //getter
var tolerance = $( ".selector" ).sortable( "option", "tolerance" );
//setter
$( ".selector" ).sortable( "option", "tolerance", 'pointer' );

  • zIndex

    Type:
    Integer
    Default:
    1000

    Z-index for element/helper while being sorted.

    Code examples

    Initialize a sortable with the zIndex option specified.
    $( ".selector" ).sortable({ zIndex: 5 });
    Get or set the zIndex option, after init.
    //getter
var zIndex = $( ".selector" ).sortable( "option", "zIndex" );
//setter
$( ".selector" ).sortable( "option", "zIndex", 5 );

Events

  • create

    Type:
    sortcreate

    This event is triggered when sortable is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).sortable({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: sortcreate.
    $( ".selector" ).bind( "sortcreate", function(event, ui) {
  ...
});

  • start

    Type:
    sortstart

    This event is triggered when sorting starts.

    Code examples

    Supply a callback function to handle the start event as an init option.
    $( ".selector" ).sortable({
   start: function(event, ui) { ... }
});
    Bind to the start event by type: sortstart.
    $( ".selector" ).bind( "sortstart", function(event, ui) {
  ...
});

  • sort

    Type:
    sort

    This event is triggered during sorting.

    Code examples

    Supply a callback function to handle the sort event as an init option.
    $( ".selector" ).sortable({
   sort: function(event, ui) { ... }
});
    Bind to the sort event by type: sort.
    $( ".selector" ).bind( "sort", function(event, ui) {
  ...
});

  • change

    Type:
    sortchange

    This event is triggered during sorting, but only when the DOM position has changed.

    Code examples

    Supply a callback function to handle the change event as an init option.
    $( ".selector" ).sortable({
   change: function(event, ui) { ... }
});
    Bind to the change event by type: sortchange.
    $( ".selector" ).bind( "sortchange", function(event, ui) {
  ...
});

  • beforeStop

    Type:
    sortbeforestop

    This event is triggered when sorting stops, but when the placeholder/helper is still available.

    Code examples

    Supply a callback function to handle the beforeStop event as an init option.
    $( ".selector" ).sortable({
   beforeStop: function(event, ui) { ... }
});
    Bind to the beforeStop event by type: sortbeforestop.
    $( ".selector" ).bind( "sortbeforestop", function(event, ui) {
  ...
});

  • stop

    Type:
    sortstop

    This event is triggered when sorting has stopped.

    Code examples

    Supply a callback function to handle the stop event as an init option.
    $( ".selector" ).sortable({
   stop: function(event, ui) { ... }
});
    Bind to the stop event by type: sortstop.
    $( ".selector" ).bind( "sortstop", function(event, ui) {
  ...
});

  • update

    Type:
    sortupdate

    This event is triggered when the user stopped sorting and the DOM position has changed.

    Code examples

    Supply a callback function to handle the update event as an init option.
    $( ".selector" ).sortable({
   update: function(event, ui) { ... }
});
    Bind to the update event by type: sortupdate.
    $( ".selector" ).bind( "sortupdate", function(event, ui) {
  ...
});

  • receive

    Type:
    sortreceive

    This event is triggered when a connected sortable list has received an item from another list.

    Code examples

    Supply a callback function to handle the receive event as an init option.
    $( ".selector" ).sortable({
   receive: function(event, ui) { ... }
});
    Bind to the receive event by type: sortreceive.
    $( ".selector" ).bind( "sortreceive", function(event, ui) {
  ...
});

  • remove

    Type:
    sortremove

    This event is triggered when a sortable item has been dragged out from the list and into another.

    Code examples

    Supply a callback function to handle the remove event as an init option.
    $( ".selector" ).sortable({
   remove: function(event, ui) { ... }
});
    Bind to the remove event by type: sortremove.
    $( ".selector" ).bind( "sortremove", function(event, ui) {
  ...
});

  • over

    Type:
    sortover

    This event is triggered when a sortable item is moved into a connected list.

    Code examples

    Supply a callback function to handle the over event as an init option.
    $( ".selector" ).sortable({
   over: function(event, ui) { ... }
});
    Bind to the over event by type: sortover.
    $( ".selector" ).bind( "sortover", function(event, ui) {
  ...
});

  • out

    Type:
    sortout

    This event is triggered when a sortable item is moved away from a connected list.

    Code examples

    Supply a callback function to handle the out event as an init option.
    $( ".selector" ).sortable({
   out: function(event, ui) { ... }
});
    Bind to the out event by type: sortout.
    $( ".selector" ).bind( "sortout", function(event, ui) {
  ...
});

  • activate

    Type:
    sortactivate

    This event is triggered when using connected lists, every connected list on drag start receives it.

    Code examples

    Supply a callback function to handle the activate event as an init option.
    $( ".selector" ).sortable({
   activate: function(event, ui) { ... }
});
    Bind to the activate event by type: sortactivate.
    $( ".selector" ).bind( "sortactivate", function(event, ui) {
  ...
});

  • deactivate

    Type:
    sortdeactivate

    This event is triggered when sorting was stopped, is propagated to all possible connected lists.

    Code examples

    Supply a callback function to handle the deactivate event as an init option.
    $( ".selector" ).sortable({
   deactivate: function(event, ui) { ... }
});
    Bind to the deactivate event by type: sortdeactivate.
    $( ".selector" ).bind( "sortdeactivate", function(event, ui) {
  ...
});

Methods

  • destroy

    Signature:
    .sortable( "destroy" )

    Remove the sortable functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .sortable( "disable" )

    Disable the sortable.

  • enable

    Signature:
    .sortable( "enable" )

    Enable the sortable.

  • option

    Signature:
    .sortable( "option" , optionName , [value] )

    Get or set any sortable option. If no value is specified, will act as a getter.

  • option

    Signature:
    .sortable( "option" , options )

    Set multiple sortable options at once by providing an options object.

  • widget

    Signature:
    .sortable( "widget" )

    Returns the .ui-sortable element.

  • serialize

    Signature:
    .sortable( "serialize" , [options] )

    Serializes the sortable's item id's into a form/ajax submittable string. Calling this method produces a hash that can be appended to any url to easily submit a new item order back to the server.

    It works by default by looking at the id of each item in the format 'setname_number', and it spits out a hash like "setname[]=number&setname[]=number".

    You can also give in a option hash as second argument to custom define how the function works. The possible options are: 'key' (replaces part1[] with whatever you want), 'attribute' (test another attribute than 'id') and 'expression' (use your own regexp).

    If serialize returns an empty string, make sure the id attributes include an underscore. They must be in the form: "set_number" For example, a 3 element list with id attributes foo_1, foo_5, foo_2 will serialize to foo[]=1&foo[]=5&foo[]=2. You can use an underscore, equal sign or hyphen to separate the set and number. For example foo=1 or foo-1 or foo_1 all serialize to foo[]=1.

  • toArray

    Signature:
    .sortable( "toArray" )

    Serializes the sortable's item id's into an array of string. If you have

    <ul id="a_sortable"><br>
<li id="hello">Hello</li><br>
<li id="goodbye">Good bye</li><br>
</ul>

    and do

    var result = $('#a_sortable').sortable('toArray');

    then

    result[0] will contain "hello" and result[1] will contain "goodbye".

  • refresh

    Signature:
    .sortable( "refresh" )

    Refresh the sortable items. Custom trigger the reloading of all sortable items, causing new items to be recognized.

  • refreshPositions

    Signature:
    .sortable( "refreshPositions" )

    Refresh the cached positions of the sortables' items. Calling this method refreshes the cached item positions of all sortables. This is usually done automatically by the script and slows down performance. Use wisely.

  • cancel

    Signature:
    .sortable( "cancel" )

    Cancels a change in the current sortable and reverts it back to how it was before the current sort started. Useful in the stop and receive callback functions.

    If the sortable item is not being moved from one connected sortable to another:

    $(this).sortable('cancel');

    will cancel the change.

    If the sortable item is being moved from one connected sortable to another:

    $(ui.sender).sortable('cancel');

    will cancel the change. Useful in the 'receive' callback.

Theming

The jQuery UI Sortable plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.sortable.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<ul class="ui-sortable">
<li></li>
<li class="ui-sortable-helper"></li>
<li class="ui-sortable-placeholder"></li>
<li></li>
</ul>

Note: This is a sample of markup generated by the sortable plugin, not markup you should use to create a sortable. The only markup needed for that is
<ul>
<li></li>
<li></li>
<li></li>
</ul>.


Accordion – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Accordion

Overview

Make the selected elements Accordion widgets. Semantic requirements:

The markup of your accordion container needs pairs of headers and content panels:

<div id="accordion">
    <h3><a href="#">First header</a></h3>
    <div>First content</div>
    <h3><a href="#">Second header</a></h3>
    <div>Second content</div>
</div>

If you use a different element for the header, specify the header-option with an appropriate selector, eg. header: 'a.header'. The content element must be always next to its header.

If you have links inside the accordion content and use a-elements as headers, add a class to them and use that as the header, eg. header: 'a.header'.

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

[edit]

NOTE: If you want multiple sections open at once, don't use an accordion

An accordion doesn't allow more than one content panel to be open at the same time, and it takes a lot of effort to do that. If you are looking for a widget that allows more than one content panel to be open, don't use this. Usually it can be written with a few lines of jQuery instead, something like this:

jQuery(document).ready(function(){
    $('.accordion .head').click(function() {
        $(this).next().toggle();
        return false;
    }).next().hide();
});

Or animated:

jQuery(document).ready(function(){
    $('.accordion .head').click(function() {
        $(this).next().toggle('slow');
        return false;
    }).next().hide();
});

Dependencies

  • UI Core
  • UI Widget
  • UI Effects Core (Optional - only for non-default animations)

Example

  • Demo
  • View Source

A simple jQuery UI Accordion.

$("#accordion").accordion();

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("#accordion").accordion();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="accordion">
    <h3><a href="#">Section 1</a></h3>
    <div>
        <p>
        Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
        ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
        amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
        odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
        </p>
    </div>
    <h3><a href="#">Section 2</a></h3>
    <div>
        <p>
        Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
        purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
        velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
        suscipit faucibus urna.
        </p>
    </div>
    <h3><a href="#">Section 3</a></h3>
    <div>
        <p>
        Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
        Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
        ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
        lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.
        </p>
        <ul>
            <li>List item one</li>
            <li>List item two</li>
            <li>List item three</li>
        </ul>
    </div>
    <h3><a href="#">Section 4</a></h3>
    <div>
        <p>
        Cras dictum. Pellentesque habitant morbi tristique senectus et netus
        et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
        faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
        mauris vel est.
        </p>
        <p>
        Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
        Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
        inceptos himenaeos.
        </p>
    </div>
</div>

</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the accordion. Can be set when initialising (first creating) the accordion.

    Code examples

    Initialize a accordion with the disabled option specified.
    $( ".selector" ).accordion({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).accordion( "option", "disabled" );
//setter
$( ".selector" ).accordion( "option", "disabled", true );

  • active

    Type:
    Selector, Element, jQuery, Boolean, Number
    Default:
    first child

    Selector for the active element. Set to false to display none at start. Needs collapsible: true.

    Code examples

    Initialize a accordion with the active option specified.
    $( ".selector" ).accordion({ active: 2 });
    Get or set the active option, after init.
    //getter
var active = $( ".selector" ).accordion( "option", "active" );
//setter
$( ".selector" ).accordion( "option", "active", 2 );

  • animated

    Type:
    Boolean, String
    Default:
    'slide'

    Choose your favorite animation, or disable them (set to false). In addition to the default, 'bounceslide' and all defined easing methods are supported ('bounceslide' requires UI Effects Core).

    Code examples

    Initialize a accordion with the animated option specified.
    $( ".selector" ).accordion({ animated: 'bounceslide' });
    Get or set the animated option, after init.
    //getter
var animated = $( ".selector" ).accordion( "option", "animated" );
//setter
$( ".selector" ).accordion( "option", "animated", 'bounceslide' );

  • autoHeight

    Type:
    Boolean
    Default:
    true

    If set, the highest content part is used as height reference for all other parts. Provides more consistent animations.

    Code examples

    Initialize a accordion with the autoHeight option specified.
    $( ".selector" ).accordion({ autoHeight: false });
    Get or set the autoHeight option, after init.
    //getter
var autoHeight = $( ".selector" ).accordion( "option", "autoHeight" );
//setter
$( ".selector" ).accordion( "option", "autoHeight", false );

  • clearStyle

    Type:
    Boolean
    Default:
    false

    If set, clears height and overflow styles after finishing animations. This enables accordions to work with dynamic content. Won't work together with autoHeight.

    Code examples

    Initialize a accordion with the clearStyle option specified.
    $( ".selector" ).accordion({ clearStyle: true });
    Get or set the clearStyle option, after init.
    //getter
var clearStyle = $( ".selector" ).accordion( "option", "clearStyle" );
//setter
$( ".selector" ).accordion( "option", "clearStyle", true );

  • collapsible

    Type:
    Boolean
    Default:
    false

    Whether all the sections can be closed at once. Allows collapsing the active section by the triggering event (click is the default).

    Code examples

    Initialize a accordion with the collapsible option specified.
    $( ".selector" ).accordion({ collapsible: true });
    Get or set the collapsible option, after init.
    //getter
var collapsible = $( ".selector" ).accordion( "option", "collapsible" );
//setter
$( ".selector" ).accordion( "option", "collapsible", true );

  • event

    Type:
    String
    Default:
    'click'

    The event on which to trigger the accordion.

    Code examples

    Initialize a accordion with the event option specified.
    $( ".selector" ).accordion({ event: 'mouseover' });
    Get or set the event option, after init.
    //getter
var event = $( ".selector" ).accordion( "option", "event" );
//setter
$( ".selector" ).accordion( "option", "event", 'mouseover' );

  • fillSpace

    Type:
    Boolean
    Default:
    false

    If set, the accordion completely fills the height of the parent element. Overrides autoheight.

    Code examples

    Initialize a accordion with the fillSpace option specified.
    $( ".selector" ).accordion({ fillSpace: true });
    Get or set the fillSpace option, after init.
    //getter
var fillSpace = $( ".selector" ).accordion( "option", "fillSpace" );
//setter
$( ".selector" ).accordion( "option", "fillSpace", true );

  • header

    Type:
    Selector, jQuery
    Default:
    '> li > :first-child,> :not(li):even'

    Selector for the header element.

    Code examples

    Initialize a accordion with the header option specified.
    $( ".selector" ).accordion({ header: 'h3' });
    Get or set the header option, after init.
    //getter
var header = $( ".selector" ).accordion( "option", "header" );
//setter
$( ".selector" ).accordion( "option", "header", 'h3' );

  • icons

    Type:
    Object
    Default:
    { 'header': 'ui-icon-triangle-1-e', 'headerSelected': 'ui-icon-triangle-1-s' }

    Icons to use for headers. Icons may be specified for 'header' and 'headerSelected', and we recommend using the icons native to the jQuery UI CSS Framework manipulated by jQuery UI ThemeRoller

    Code examples

    Initialize a accordion with the icons option specified.
    $( ".selector" ).accordion({ icons: { 'header': 'ui-icon-plus', 'headerSelected': 'ui-icon-minus' } });
    Get or set the icons option, after init.
    //getter
var icons = $( ".selector" ).accordion( "option", "icons" );
//setter
$( ".selector" ).accordion( "option", "icons", { 'header': 'ui-icon-plus', 'headerSelected': 'ui-icon-minus' } );

  • navigation

    Type:
    Boolean
    Default:
    false

    If set, looks for the anchor that matches location.href and activates it. Great for href-based state-saving. Use navigationFilter to implement your own matcher.

    Code examples

    Initialize a accordion with the navigation option specified.
    $( ".selector" ).accordion({ navigation: true });
    Get or set the navigation option, after init.
    //getter
var navigation = $( ".selector" ).accordion( "option", "navigation" );
//setter
$( ".selector" ).accordion( "option", "navigation", true );

  • navigationFilter

    Type:
    Function
    Default:

    Overwrite the default location.href-matching with your own matcher.

    Code examples

    Initialize a accordion with the navigationFilter option specified.
    $( ".selector" ).accordion({ navigationFilter: function(){ ... } });
    Get or set the navigationFilter option, after init.
    //getter
var navigationFilter = $( ".selector" ).accordion( "option", "navigationFilter" );
//setter
$( ".selector" ).accordion( "option", "navigationFilter", function(){ ... } );

Events

  • create

    Type:
    accordioncreate

    This event is triggered when accordion is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).accordion({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: accordioncreate.
    $( ".selector" ).bind( "accordioncreate", function(event, ui) {
  ...
});

  • change

    Type:
    accordionchange

    This event is triggered every time the accordion changes. If the accordion is animated, the event will be triggered upon completion of the animation; otherwise, it is triggered immediately.

    $('.ui-accordion').bind('accordionchange', function(event, ui) {
  ui.newHeader // jQuery object, activated header
  ui.oldHeader // jQuery object, previous header
  ui.newContent // jQuery object, activated content
  ui.oldContent // jQuery object, previous content
});

    Code examples

    Supply a callback function to handle the change event as an init option.
    $( ".selector" ).accordion({
   change: function(event, ui) { ... }
});
    Bind to the change event by type: accordionchange.
    $( ".selector" ).bind( "accordionchange", function(event, ui) {
  ...
});

  • changestart

    Type:
    accordionchangestart

    This event is triggered every time the accordion starts to change.

    $('.ui-accordion').bind('accordionchangestart', function(event, ui) {
  ui.newHeader // jQuery object, activated header
  ui.oldHeader // jQuery object, previous header
  ui.newContent // jQuery object, activated content
  ui.oldContent // jQuery object, previous content
});

    Code examples

    Supply a callback function to handle the changestart event as an init option.
    $( ".selector" ).accordion({
   changestart: function(event, ui) { ... }
});
    Bind to the changestart event by type: accordionchangestart.
    $( ".selector" ).bind( "accordionchangestart", function(event, ui) {
  ...
});

Methods

  • destroy

    Signature:
    .accordion( "destroy" )

    Remove the accordion functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .accordion( "disable" )

    Disable the accordion.

  • enable

    Signature:
    .accordion( "enable" )

    Enable the accordion.

  • option

    Signature:
    .accordion( "option" , optionName , [value] )

    Get or set any accordion option. If no value is specified, will act as a getter.

  • option

    Signature:
    .accordion( "option" , options )

    Set multiple accordion options at once by providing an options object.

  • widget

    Signature:
    .accordion( "widget" )

    Returns the .ui-accordion element.

  • activate

    Signature:
    .accordion( "activate" , index )

    Activate a content part of the Accordion programmatically. The index can be a zero-indexed number to match the position of the header to close or a Selector matching an element. Pass false to close all (only possible with collapsible:true).

  • resize

    Signature:
    .accordion( "resize" )

    Recompute heights of the accordion contents when using the fillSpace option and the container height changed. For example, when the container is a resizable, this method should be called by its resize-event.

Theming

The jQuery UI Accordion plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.accordion.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<div class="ui-accordion ui-widget ui-helper-reset">
<h3 class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top">
<span class="ui-icon ui-icon-triangle-1-s"/>
<a href="#">Section 1</a>
</h3>
<div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active">
Section 1 content
</div>
<h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all">
<span class="ui-icon ui-icon-triangle-1-e"/>
<a href="#">Section 2</a>
</h3>
<div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom">
Section 2 content
</div>
<h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all">
<span class="ui-icon ui-icon-triangle-1-e"/>
<a href="#">Section 3</a>
</h3>
<div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom">
Section 3 content
</div>
</div>

Note: This is a sample of markup generated by the accordion plugin, not markup you should use to create a accordion. The only markup needed for that is
<div>
<h3><a href="#">Section 1</a></h3>
<div>
Section 1 content
</div>
<h3><a href="#">Section 2</a></h3>
<div>
Section 2 content
</div>
<h3><a href="#">Section 3</a></h3>
<div>
Section 3 content
</div>
</div>.


Autocomplete – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Autocomplete

Overview

Autocomplete, when added to an input field, enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

By giving an Autocomplete field focus or entering something into it, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

This can be used to enter previous selected values, for example you could use Autocomplete for entering tags, to complete an address, you could enter a city name and get the zip code, or maybe enter email addresses from an address book.

You can pull data in from a local and/or a remote source: Local is good for small data sets (like an address book with 50 entries), remote is necessary for big data sets, like a database with hundreds or millions of entries to select from.

Autocomplete can be customized to work with various data sources, by just specifying the source option. A data source can be:

  • an Array with local data
  • a String, specifying a URL
  • a Callback

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The request parameter "term" gets added to that URL. The data itself can be in the same format as the local data described above.

The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:

  • A request object, with a single property called "term", which refers to the value currently in the text input. For example, when the user entered "new yo" in a city field, the Autocomplete term will equal "new yo".
  • A response callback, which expects a single argument to contain the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties). It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.

The label is always treated as text, if you want the label to be treated as html you can use Scott González' html extension. The demos all focus on different variations of the source-option - look for the one that matches your use case, and take a look at the code.

Dependencies

  • UI Core
  • UI Widget
  • UI Position

Example

  • Demo
  • View Source

A simple jQuery UI Autocomplete.

$("input#autocomplete").autocomplete({
    source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("input#autocomplete").autocomplete({
    source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
});
  });
  </script>
</head>
<body style="font-size:62.5%;">

<input id="autocomplete" />

</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the autocomplete. Can be set when initialising (first creating) the autocomplete.

    Code examples

    Initialize a autocomplete with the disabled option specified.
    $( ".selector" ).autocomplete({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).autocomplete( "option", "disabled" );
//setter
$( ".selector" ).autocomplete( "option", "disabled", true );

  • appendTo

    Type:
    Selector
    Default:
    "body"

    Which element the menu should be appended to.

    Code examples

    Initialize a autocomplete with the appendTo option specified.
    $( ".selector" ).autocomplete({ appendTo: "#someElem" });
    Get or set the appendTo option, after init.
    //getter
var appendTo = $( ".selector" ).autocomplete( "option", "appendTo" );
//setter
$( ".selector" ).autocomplete( "option", "appendTo", "#someElem" );

  • autoFocus

    Type:
    Boolean
    Default:
    false

    If set to true the first item will be automatically focused.

    Code examples

    Initialize a autocomplete with the autoFocus option specified.
    $( ".selector" ).autocomplete({ autoFocus: true });
    Get or set the autoFocus option, after init.
    //getter
var autoFocus = $( ".selector" ).autocomplete( "option", "autoFocus" );
//setter
$( ".selector" ).autocomplete( "option", "autoFocus", true );

  • delay

    Type:
    Integer
    Default:
    300

    The delay in milliseconds the Autocomplete waits after a keystroke to activate itself. A zero-delay makes sense for local data (more responsive), but can produce a lot of load for remote data, while being less responsive.

    Code examples

    Initialize a autocomplete with the delay option specified.
    $( ".selector" ).autocomplete({ delay: 0 });
    Get or set the delay option, after init.
    //getter
var delay = $( ".selector" ).autocomplete( "option", "delay" );
//setter
$( ".selector" ).autocomplete( "option", "delay", 0 );

  • minLength

    Type:
    Integer
    Default:
    1

    The minimum number of characters a user has to type before the Autocomplete activates. Zero is useful for local data with just a few items. Should be increased when there are a lot of items, where a single character would match a few thousand items.

    Code examples

    Initialize a autocomplete with the minLength option specified.
    $( ".selector" ).autocomplete({ minLength: 0 });
    Get or set the minLength option, after init.
    //getter
var minLength = $( ".selector" ).autocomplete( "option", "minLength" );
//setter
$( ".selector" ).autocomplete( "option", "minLength", 0 );

  • position

    Type:
    Object
    Default:
    { my: "left top", at: "left bottom", collision: "none" }

    Identifies the position of the Autocomplete widget in relation to the associated input element. The "of" option defaults to the input element, but you can specify another element to position against. You can refer to the jQuery UI Position utility for more details about the various options.

    Code examples

    Initialize a autocomplete with the position option specified.
    $( ".selector" ).autocomplete({ position: { my : "right top", at: "right bottom" } });
    Get or set the position option, after init.
    //getter
var position = $( ".selector" ).autocomplete( "option", "position" );
//setter
$( ".selector" ).autocomplete( "option", "position", { my : "right top", at: "right bottom" } );

  • source

    Type:
    String, Array, Callback
    Default:
    none, must be specified

    Defines the data to use, must be specified. See Overview section for more details, and look at the various demos.

    Code examples

    Initialize a autocomplete with the source option specified.
    $( ".selector" ).autocomplete({ source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"] });
    Get or set the source option, after init.
    //getter
var source = $( ".selector" ).autocomplete( "option", "source" );
//setter
$( ".selector" ).autocomplete( "option", "source", ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"] );

Events

  • create

    Type:
    autocompletecreate

    This event is triggered when autocomplete is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).autocomplete({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: autocompletecreate.
    $( ".selector" ).bind( "autocompletecreate", function(event, ui) {
  ...
});

  • search

    Type:
    autocompletesearch

    Before a request (source-option) is started, after minLength and delay are met. Can be canceled (return false), then no request will be started and no items suggested.

    Code examples

    Supply a callback function to handle the search event as an init option.
    $( ".selector" ).autocomplete({
   search: function(event, ui) { ... }
});
    Bind to the search event by type: autocompletesearch.
    $( ".selector" ).bind( "autocompletesearch", function(event, ui) {
  ...
});

  • open

    Type:
    autocompleteopen

    Triggered when the suggestion menu is opened.

    Code examples

    Supply a callback function to handle the open event as an init option.
    $( ".selector" ).autocomplete({
   open: function(event, ui) { ... }
});
    Bind to the open event by type: autocompleteopen.
    $( ".selector" ).bind( "autocompleteopen", function(event, ui) {
  ...
});

  • focus

    Type:
    autocompletefocus

    Before focus is moved to an item (not selecting), ui.item refers to the focused item. The default action of focus is to replace the text field's value with the value of the focused item, though only if the focus event was triggered by a keyboard interaction. Canceling this event prevents the value from being updated, but does not prevent the menu item from being focused.

    Code examples

    Supply a callback function to handle the focus event as an init option.
    $( ".selector" ).autocomplete({
   focus: function(event, ui) { ... }
});
    Bind to the focus event by type: autocompletefocus.
    $( ".selector" ).bind( "autocompletefocus", function(event, ui) {
  ...
});

  • select

    Type:
    autocompleteselect

    Triggered when an item is selected from the menu; ui.item refers to the selected item. The default action of select is to replace the text field's value with the value of the selected item. Canceling this event prevents the value from being updated, but does not prevent the menu from closing.

    Code examples

    Supply a callback function to handle the select event as an init option.
    $( ".selector" ).autocomplete({
   select: function(event, ui) { ... }
});
    Bind to the select event by type: autocompleteselect.
    $( ".selector" ).bind( "autocompleteselect", function(event, ui) {
  ...
});

  • close

    Type:
    autocompleteclose

    When the list is hidden - doesn't have to occur together with a change.

    Code examples

    Supply a callback function to handle the close event as an init option.
    $( ".selector" ).autocomplete({
   close: function(event, ui) { ... }
});
    Bind to the close event by type: autocompleteclose.
    $( ".selector" ).bind( "autocompleteclose", function(event, ui) {
  ...
});

  • change

    Type:
    autocompletechange

    After an item was selected; ui.item refers to the selected item. Always triggered after the close event.

    Code examples

    Supply a callback function to handle the change event as an init option.
    $( ".selector" ).autocomplete({
   change: function(event, ui) { ... }
});
    Bind to the change event by type: autocompletechange.
    $( ".selector" ).bind( "autocompletechange", function(event, ui) {
  ...
});

Methods

  • destroy

    Signature:
    .autocomplete( "destroy" )

    Remove the autocomplete functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .autocomplete( "disable" )

    Disable the autocomplete.

  • enable

    Signature:
    .autocomplete( "enable" )

    Enable the autocomplete.

  • option

    Signature:
    .autocomplete( "option" , optionName , [value] )

    Get or set any autocomplete option. If no value is specified, will act as a getter.

  • option

    Signature:
    .autocomplete( "option" , options )

    Set multiple autocomplete options at once by providing an options object.

  • widget

    Signature:
    .autocomplete( "widget" )

    Returns the .ui-autocomplete element.

  • search

    Signature:
    .autocomplete( "search" , [value] )

    Triggers a search event, which, when data is available, then will display the suggestions; can be used by a selectbox-like button to open the suggestions when clicked. If no value argument is specified, the current input's value is used. Can be called with an empty string and minLength: 0 to display all items.

  • close

    Signature:
    .autocomplete( "close" )

    Close the Autocomplete menu. Useful in combination with the search method, to close the open menu.

Theming

The jQuery UI Autocomplete plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.autocomplete.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<input class="ui-autocomplete-input"/>
<ul class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all">
<li class="ui-menu-item">
<a class="ui-corner-all">item 1</a>
</li>
<li class="ui-menu-item">
<a class="ui-corner-all">item 2</a>
</li>
<li class="ui-menu-item">
<a class="ui-corner-all">item 3</a>
</li>
</ul>

Note: This is a sample of markup generated by the autocomplete plugin, not markup you should use to create a autocomplete. The only markup needed for that is <input/>.


Button – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Button

Overview

Button enhances standard form elements like button, input of type submit or reset or anchors to themable buttons with appropiate mouseover and active styles.

In addition to basic push buttons, radio buttons and checkboxes (inputs of type radio and checkbox) can be converted to buttons: Their associated label is styled to appear as the button, while the underlying input is updated on click.

In order to group radio buttons, Button also provides an additional widget-method, called Buttonset. Its used by selecting a container element (which contains the radio buttons) and calling buttonset(). Buttonset will also provide visual grouping, and therefore should be used whenever you have a group of buttons. It works by selecting all descendents and applying button() to them. You can enable and disable a buttonset, which will enable and disable all contained buttons. Destroying a buttonset also calls the button's destroy method.

When using an input of type button, submit or reset, support is limited to plain text labels with no icons.

Dependencies

  • UI Core
  • UI Widget

Example

  • Demo
  • View Source

A simple jQuery UI Button.

$("button").button();

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("button").button();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<button>Button label</button>

</body>
</html>

  • Demo
  • View Source
A simple jQuery UI Button.

$("#radio").buttonset();

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("#radio").buttonset();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="radio">
    <input type="radio" id="radio1" name="radio" /><label for="radio1">Choice 1</label>
    <input type="radio" id="radio2" name="radio" checked="checked" /><label for="radio2">Choice 2</label>
    <input type="radio" id="radio3" name="radio" /><label for="radio3">Choice 3</label>
</div>

</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the button. Can be set when initialising (first creating) the button.

    Code examples

    Initialize a button with the disabled option specified.
    $( ".selector" ).button({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).button( "option", "disabled" );
//setter
$( ".selector" ).button( "option", "disabled", true );

  • text

    Type:
    Boolean
    Default:
    true

    Whether to show any text - when set to false (display no text), icons (see icons option) must be enabled, otherwise it'll be ignored.

    Code examples

    Initialize a button with the text option specified.
    $( ".selector" ).button({ text: false });
    Get or set the text option, after init.
    //getter
var text = $( ".selector" ).button( "option", "text" );
//setter
$( ".selector" ).button( "option", "text", false );

  • icons

    Type:
    Options
    Default:
    { primary: null, secondary: null }

    Icons to display, with or without text (see text option). The primary icon is displayed by default on the left of the label text, the secondary by default is on the right. Value for the primary and secondary properties must be a classname (String), eg. "ui-icon-gear". For using only one icon: icons: {primary:'ui-icon-locked'}. For using two icons: icons: {primary:'ui-icon-gear',secondary:'ui-icon-triangle-1-s'}

    Code examples

    Initialize a button with the icons option specified.
    $( ".selector" ).button({ icons: {primary:'ui-icon-gear',secondary:'ui-icon-triangle-1-s'} });
    Get or set the icons option, after init.
    //getter
var icons = $( ".selector" ).button( "option", "icons" );
//setter
$( ".selector" ).button( "option", "icons", {primary:'ui-icon-gear',secondary:'ui-icon-triangle-1-s'} );

  • label

    Type:
    String
    Default:
    HTML content of the button, or value attribute

    Text to show on the button. When not specified (null), the element's html content is used, or its value attribute when it's an input element of type submit or reset; or the html content of the associated label element if its an input of type radio or checkbox

    Code examples

    Initialize a button with the label option specified.
    $( ".selector" ).button({ label: "custom label" });
    Get or set the label option, after init.
    //getter
var label = $( ".selector" ).button( "option", "label" );
//setter
$( ".selector" ).button( "option", "label", "custom label" );

Events

  • create

    Type:
    buttoncreate

    This event is triggered when button is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).button({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: buttoncreate.
    $( ".selector" ).bind( "buttoncreate", function(event, ui) {
  ...
});

    • There are no events for this plugin.

Methods

  • destroy

    Signature:
    .button( "destroy" )

    Remove the button functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .button( "disable" )

    Disable the button.

  • enable

    Signature:
    .button( "enable" )

    Enable the button.

  • option

    Signature:
    .button( "option" , optionName , [value] )

    Get or set any button option. If no value is specified, will act as a getter.

  • option

    Signature:
    .button( "option" , options )

    Set multiple button options at once by providing an options object.

  • widget

    Signature:
    .button( "widget" )

    Returns the .ui-button element.

  • refresh

    Signature:
    .button( "refresh" )

    Refreshes the visual state of the button. Useful for updating button state after the native element's checked or disabled state is changed programatically.

Theming

The jQuery UI Button plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.button.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<button class="ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all">
<span class="ui-button-text">Button Label</span>
</button>

Note: This is a sample of markup generated by the button plugin, not markup you should use to create a button. The only markup needed for that is <button>Button Label</button>.


Datepicker – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Datepicker

Overview

The jQuery UI Datepicker is a highly configurable plugin that adds datepicker functionality to your pages. You can customize the date format and language, restrict the selectable date ranges and add in buttons and other navigation options easily.

By default, the datepicker calendar opens in a small overlay onFocus and closes automatically onBlur or when a date is selected. For an inline calendar, simply attach the datepicker to a div or span.

You can use keyboard shortcuts to drive the datepicker:

  • page up/down - previous/next month
  • ctrl+page up/down - previous/next year
  • ctrl+home - current month or open when closed
  • ctrl+left/right - previous/next day
  • ctrl+up/down - previous/next week
  • enter - accept the selected date
  • ctrl+end - close and erase the date
  • escape - close the datepicker without selection
[edit]

Utility functions

  • $.datepicker.setDefaults( settings ) - Set settings for all datepicker instances.
  • $.datepicker.formatDate( format, date, settings ) - Format a date into a string value with a specified format.
  • $.datepicker.parseDate( format, value, settings ) - Extract a date from a string value with a specified format.
  • $.datepicker.iso8601Week( date ) - Determine the week of the year for a given date: 1 to 53.
  • $.datepicker.noWeekends - Set as beforeShowDay function to prevent selection of weekends.
[edit]

Localization

Datepicker provides support for localizing its content to cater for different languages and date formats. Each localization is contained within its own file with the language code appended to the name, e.g. jquery.ui.datepicker-fr.js for French. The desired localization file should be include after the main datepicker code. They add their settings to the set of available localizations and automatically apply them as defaults for all instances.

The $.datepicker.regional attribute holds an array of localizations, indexed by language code, with '' referring to the default (English). Each entry is an object with the following attributes: closeText, prevText, nextText, currentText, monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, weekHeader, dateFormat, firstDay, isRTL, showMonthAfterYear, and yearSuffix.

You can restore the default localizations with:

$.datepicker.setDefaults($.datepicker.regional['']);

And can then override an individual datepicker for a specific locale:

$(selector).datepicker($.datepicker.regional['fr']);

The localization files are also available in the UI svn: http://jquery-ui.googlecode.com/svn/trunk/ui/i18n/

Dependencies

  • UI Core

Example

  • Demo
  • View Source

A simple jQuery UI Datepicker.

$("#datepicker").datepicker();

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("#datepicker").datepicker();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div type="text" id="datepicker"></div>

</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the datepicker. Can be set when initialising (first creating) the datepicker.

    Code examples

    Initialize a datepicker with the disabled option specified.
    $( ".selector" ).datepicker({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).datepicker( "option", "disabled" );
//setter
$( ".selector" ).datepicker( "option", "disabled", true );

  • altField

    Type:
    Selector, jQuery, Element
    Default:
    ''

    The jQuery selector for another field that is to be updated with the selected date from the datepicker. Use the altFormat setting to change the format of the date within this field. Leave as blank for no alternate field.

    Code examples

    Initialize a datepicker with the altField option specified.
    $( ".selector" ).datepicker({ altField: '#actualDate' });
    Get or set the altField option, after init.
    //getter
var altField = $( ".selector" ).datepicker( "option", "altField" );
//setter
$( ".selector" ).datepicker( "option", "altField", '#actualDate' );

  • altFormat

    Type:
    String
    Default:
    ''

    The dateFormat to be used for the altField option. This allows one date format to be shown to the user for selection purposes, while a different format is actually sent behind the scenes. For a full list of the possible formats see the formatDate function

    Code examples

    Initialize a datepicker with the altFormat option specified.
    $( ".selector" ).datepicker({ altFormat: 'yy-mm-dd' });
    Get or set the altFormat option, after init.
    //getter
var altFormat = $( ".selector" ).datepicker( "option", "altFormat" );
//setter
$( ".selector" ).datepicker( "option", "altFormat", 'yy-mm-dd' );

  • appendText

    Type:
    String
    Default:
    ''

    The text to display after each date field, e.g. to show the required format.

    Code examples

    Initialize a datepicker with the appendText option specified.
    $( ".selector" ).datepicker({ appendText: '(yyyy-mm-dd)' });
    Get or set the appendText option, after init.
    //getter
var appendText = $( ".selector" ).datepicker( "option", "appendText" );
//setter
$( ".selector" ).datepicker( "option", "appendText", '(yyyy-mm-dd)' );

  • autoSize

    Type:
    Boolean
    Default:
    false

    Set to true to automatically resize the input field to accomodate dates in the current dateFormat.

    Code examples

    Initialize a datepicker with the autoSize option specified.
    $( ".selector" ).datepicker({ autoSize: true });
    Get or set the autoSize option, after init.
    //getter
var autoSize = $( ".selector" ).datepicker( "option", "autoSize" );
//setter
$( ".selector" ).datepicker( "option", "autoSize", true );

  • buttonImage

    Type:
    String
    Default:
    ''

    The URL for the popup button image. If set, buttonText becomes the alt value and is not directly displayed.

    Code examples

    Initialize a datepicker with the buttonImage option specified.
    $( ".selector" ).datepicker({ buttonImage: '/images/datepicker.gif' });
    Get or set the buttonImage option, after init.
    //getter
var buttonImage = $( ".selector" ).datepicker( "option", "buttonImage" );
//setter
$( ".selector" ).datepicker( "option", "buttonImage", '/images/datepicker.gif' );

  • buttonImageOnly

    Type:
    Boolean
    Default:
    false

    Set to true to place an image after the field to use as the trigger without it appearing on a button.

    Code examples

    Initialize a datepicker with the buttonImageOnly option specified.
    $( ".selector" ).datepicker({ buttonImageOnly: true });
    Get or set the buttonImageOnly option, after init.
    //getter
var buttonImageOnly = $( ".selector" ).datepicker( "option", "buttonImageOnly" );
//setter
$( ".selector" ).datepicker( "option", "buttonImageOnly", true );

  • buttonText

    Type:
    String
    Default:
    '...'

    The text to display on the trigger button. Use in conjunction with showOn equal to 'button' or 'both'.

    Code examples

    Initialize a datepicker with the buttonText option specified.
    $( ".selector" ).datepicker({ buttonText: 'Choose' });
    Get or set the buttonText option, after init.
    //getter
var buttonText = $( ".selector" ).datepicker( "option", "buttonText" );
//setter
$( ".selector" ).datepicker( "option", "buttonText", 'Choose' );

  • calculateWeek

    Type:
    Function
    Default:
    $.datepicker.iso8601Week

    A function to calculate the week of the year for a given date. The default implementation uses the ISO 8601 definition: weeks start on a Monday; the first week of the year contains the first Thursday of the year.

    Code examples

    Initialize a datepicker with the calculateWeek option specified.
    $( ".selector" ).datepicker({ calculateWeek: myWeekCalc });
    Get or set the calculateWeek option, after init.
    //getter
var calculateWeek = $( ".selector" ).datepicker( "option", "calculateWeek" );
//setter
$( ".selector" ).datepicker( "option", "calculateWeek", myWeekCalc );

  • changeMonth

    Type:
    Boolean
    Default:
    false

    Allows you to change the month by selecting from a drop-down list. You can enable this feature by setting the attribute to true.

    Code examples

    Initialize a datepicker with the changeMonth option specified.
    $( ".selector" ).datepicker({ changeMonth: true });
    Get or set the changeMonth option, after init.
    //getter
var changeMonth = $( ".selector" ).datepicker( "option", "changeMonth" );
//setter
$( ".selector" ).datepicker( "option", "changeMonth", true );

  • changeYear

    Type:
    Boolean
    Default:
    false

    Allows you to change the year by selecting from a drop-down list. You can enable this feature by setting the attribute to true. Use the yearRange option to control which years are made available for selection.

    Code examples

    Initialize a datepicker with the changeYear option specified.
    $( ".selector" ).datepicker({ changeYear: true });
    Get or set the changeYear option, after init.
    //getter
var changeYear = $( ".selector" ).datepicker( "option", "changeYear" );
//setter
$( ".selector" ).datepicker( "option", "changeYear", true );

  • closeText

    Type:
    String
    Default:
    'Done'

    The text to display for the close link. This attribute is one of the regionalisation attributes. Use the showButtonPanel to display this button.

    Code examples

    Initialize a datepicker with the closeText option specified.
    $( ".selector" ).datepicker({ closeText: 'X' });
    Get or set the closeText option, after init.
    //getter
var closeText = $( ".selector" ).datepicker( "option", "closeText" );
//setter
$( ".selector" ).datepicker( "option", "closeText", 'X' );

  • constrainInput

    Type:
    Boolean
    Default:
    true

    When true entry in the input field is constrained to those characters allowed by the current dateFormat.

    Code examples

    Initialize a datepicker with the constrainInput option specified.
    $( ".selector" ).datepicker({ constrainInput: false });
    Get or set the constrainInput option, after init.
    //getter
var constrainInput = $( ".selector" ).datepicker( "option", "constrainInput" );
//setter
$( ".selector" ).datepicker( "option", "constrainInput", false );

  • currentText

    Type:
    String
    Default:
    'Today'

    The text to display for the current day link. This attribute is one of the regionalisation attributes. Use the showButtonPanel to display this button.

    Code examples

    Initialize a datepicker with the currentText option specified.
    $( ".selector" ).datepicker({ currentText: 'Now' });
    Get or set the currentText option, after init.
    //getter
var currentText = $( ".selector" ).datepicker( "option", "currentText" );
//setter
$( ".selector" ).datepicker( "option", "currentText", 'Now' );

  • dateFormat

    Type:
    String
    Default:
    'mm/dd/yy'

    The format for parsed and displayed dates. This attribute is one of the regionalisation attributes. For a full list of the possible formats see the formatDate function.

    Code examples

    Initialize a datepicker with the dateFormat option specified.
    $( ".selector" ).datepicker({ dateFormat: 'yy-mm-dd' });
    Get or set the dateFormat option, after init.
    //getter
var dateFormat = $( ".selector" ).datepicker( "option", "dateFormat" );
//setter
$( ".selector" ).datepicker( "option", "dateFormat", 'yy-mm-dd' );

  • dayNames

    Type:
    Array
    Default:
    ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

    The list of long day names, starting from Sunday, for use as requested via the dateFormat setting. They also appear as popup hints when hovering over the corresponding column headings. This attribute is one of the regionalisation attributes.

    Code examples

    Initialize a datepicker with the dayNames option specified.
    $( ".selector" ).datepicker({ dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'] });
    Get or set the dayNames option, after init.
    //getter
var dayNames = $( ".selector" ).datepicker( "option", "dayNames" );
//setter
$( ".selector" ).datepicker( "option", "dayNames", ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'] );

  • dayNamesMin

    Type:
    Array
    Default:
    ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']

    The list of minimised day names, starting from Sunday, for use as column headers within the datepicker. This attribute is one of the regionalisation attributes.

    Code examples

    Initialize a datepicker with the dayNamesMin option specified.
    $( ".selector" ).datepicker({ dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'] });
    Get or set the dayNamesMin option, after init.
    //getter
var dayNamesMin = $( ".selector" ).datepicker( "option", "dayNamesMin" );
//setter
$( ".selector" ).datepicker( "option", "dayNamesMin", ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'] );

  • dayNamesShort

    Type:
    Array
    Default:
    ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

    The list of abbreviated day names, starting from Sunday, for use as requested via the dateFormat setting. This attribute is one of the regionalisation attributes.

    Code examples

    Initialize a datepicker with the dayNamesShort option specified.
    $( ".selector" ).datepicker({ dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'] });
    Get or set the dayNamesShort option, after init.
    //getter
var dayNamesShort = $( ".selector" ).datepicker( "option", "dayNamesShort" );
//setter
$( ".selector" ).datepicker( "option", "dayNamesShort", ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'] );

  • defaultDate

    Type:
    Date, Number, String
    Default:
    null

    Set the date to highlight on first opening if the field is blank. Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

    Code examples

    Initialize a datepicker with the defaultDate option specified.
    $( ".selector" ).datepicker({ defaultDate: +7 });
    Get or set the defaultDate option, after init.
    //getter
var defaultDate = $( ".selector" ).datepicker( "option", "defaultDate" );
//setter
$( ".selector" ).datepicker( "option", "defaultDate", +7 );

  • duration

    Type:
    String, Number
    Default:
    'normal'

    Control the speed at which the datepicker appears, it may be a time in milliseconds or a string representing one of the three predefined speeds ("slow", "normal", "fast").

    Code examples

    Initialize a datepicker with the duration option specified.
    $( ".selector" ).datepicker({ duration: 'slow' });
    Get or set the duration option, after init.
    //getter
var duration = $( ".selector" ).datepicker( "option", "duration" );
//setter
$( ".selector" ).datepicker( "option", "duration", 'slow' );

  • firstDay

    Type:
    Number
    Default:
    0

    Set the first day of the week: Sunday is 0, Monday is 1, ... This attribute is one of the regionalisation attributes.

    Code examples

    Initialize a datepicker with the firstDay option specified.
    $( ".selector" ).datepicker({ firstDay: 1 });
    Get or set the firstDay option, after init.
    //getter
var firstDay = $( ".selector" ).datepicker( "option", "firstDay" );
//setter
$( ".selector" ).datepicker( "option", "firstDay", 1 );

  • gotoCurrent

    Type:
    Boolean
    Default:
    false

    When true the current day link moves to the currently selected date instead of today.

    Code examples

    Initialize a datepicker with the gotoCurrent option specified.
    $( ".selector" ).datepicker({ gotoCurrent: true });
    Get or set the gotoCurrent option, after init.
    //getter
var gotoCurrent = $( ".selector" ).datepicker( "option", "gotoCurrent" );
//setter
$( ".selector" ).datepicker( "option", "gotoCurrent", true );

  • hideIfNoPrevNext

    Type:
    Boolean
    Default:
    false

    Normally the previous and next links are disabled when not applicable (see minDate/maxDate). You can hide them altogether by setting this attribute to true.

    Code examples

    Initialize a datepicker with the hideIfNoPrevNext option specified.
    $( ".selector" ).datepicker({ hideIfNoPrevNext: true });
    Get or set the hideIfNoPrevNext option, after init.
    //getter
var hideIfNoPrevNext = $( ".selector" ).datepicker( "option", "hideIfNoPrevNext" );
//setter
$( ".selector" ).datepicker( "option", "hideIfNoPrevNext", true );

  • isRTL

    Type:
    Boolean
    Default:
    false

    True if the current language is drawn from right to left. This attribute is one of the regionalisation attributes.

    Code examples

    Initialize a datepicker with the isRTL option specified.
    $( ".selector" ).datepicker({ isRTL: true });
    Get or set the isRTL option, after init.
    //getter
var isRTL = $( ".selector" ).datepicker( "option", "isRTL" );
//setter
$( ".selector" ).datepicker( "option", "isRTL", true );

  • maxDate

    Type:
    Date, Number, String
    Default:
    null

    Set a maximum selectable date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +1w'), or null for no limit.

    Code examples

    Initialize a datepicker with the maxDate option specified.
    $( ".selector" ).datepicker({ maxDate: '+1m +1w' });
    Get or set the maxDate option, after init.
    //getter
var maxDate = $( ".selector" ).datepicker( "option", "maxDate" );
//setter
$( ".selector" ).datepicker( "option", "maxDate", '+1m +1w' );

  • minDate

    Type:
    Date, Number, String
    Default:
    null

    Set a minimum selectable date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '-1y -1m'), or null for no limit.

    Code examples

    Initialize a datepicker with the minDate option specified.
    $( ".selector" ).datepicker({ minDate: new Date(2007, 1 - 1, 1) });
    Get or set the minDate option, after init.
    //getter
var minDate = $( ".selector" ).datepicker( "option", "minDate" );
//setter
$( ".selector" ).datepicker( "option", "minDate", new Date(2007, 1 - 1, 1) );

  • monthNames

    Type:
    Array
    Default:
    ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

    The list of full month names, for use as requested via the dateFormat setting. This attribute is one of the regionalisation attributes.

    Code examples

    Initialize a datepicker with the monthNames option specified.
    $( ".selector" ).datepicker({ monthNames: ['Januar','Februar','Marts','April','Maj','Juni','Juli','August','September','Oktober','November','December'] });
    Get or set the monthNames option, after init.
    //getter
var monthNames = $( ".selector" ).datepicker( "option", "monthNames" );
//setter
$( ".selector" ).datepicker( "option", "monthNames", ['Januar','Februar','Marts','April','Maj','Juni','Juli','August','September','Oktober','November','December'] );

  • monthNamesShort

    Type:
    Array
    Default:
    ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

    The list of abbreviated month names, as used in the month header on each datepicker and as requested via the dateFormat setting. This attribute is one of the regionalisation attributes.

    Code examples

    Initialize a datepicker with the monthNamesShort option specified.
    $( ".selector" ).datepicker({ monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun','Jul','Aug','Sep','Okt','Nov','Dec'] });
    Get or set the monthNamesShort option, after init.
    //getter
var monthNamesShort = $( ".selector" ).datepicker( "option", "monthNamesShort" );
//setter
$( ".selector" ).datepicker( "option", "monthNamesShort", ['Jan','Feb','Mar','Apr','Maj','Jun','Jul','Aug','Sep','Okt','Nov','Dec'] );

  • navigationAsDateFormat

    Type:
    Boolean
    Default:
    false

    When true the formatDate function is applied to the prevText, nextText, and currentText values before display, allowing them to display the target month names for example.

    Code examples

    Initialize a datepicker with the navigationAsDateFormat option specified.
    $( ".selector" ).datepicker({ navigationAsDateFormat: true });
    Get or set the navigationAsDateFormat option, after init.
    //getter
var navigationAsDateFormat = $( ".selector" ).datepicker( "option", "navigationAsDateFormat" );
//setter
$( ".selector" ).datepicker( "option", "navigationAsDateFormat", true );

  • nextText

    Type:
    String
    Default:
    'Next'

    The text to display for the next month link. This attribute is one of the regionalisation attributes. With the standard ThemeRoller styling, this value is replaced by an icon.

    Code examples

    Initialize a datepicker with the nextText option specified.
    $( ".selector" ).datepicker({ nextText: 'Later' });
    Get or set the nextText option, after init.
    //getter
var nextText = $( ".selector" ).datepicker( "option", "nextText" );
//setter
$( ".selector" ).datepicker( "option", "nextText", 'Later' );

  • numberOfMonths

    Type:
    Number, Array
    Default:
    1

    Set how many months to show at once. The value can be a straight integer, or can be a two-element array to define the number of rows and columns to display.

    Code examples

    Initialize a datepicker with the numberOfMonths option specified.
    $( ".selector" ).datepicker({ numberOfMonths: [2, 3] });
    Get or set the numberOfMonths option, after init.
    //getter
var numberOfMonths = $( ".selector" ).datepicker( "option", "numberOfMonths" );
//setter
$( ".selector" ).datepicker( "option", "numberOfMonths", [2, 3] );

  • prevText

    Type:
    String
    Default:
    'Prev'

    The text to display for the previous month link. This attribute is one of the regionalisation attributes. With the standard ThemeRoller styling, this value is replaced by an icon.

    Code examples

    Initialize a datepicker with the prevText option specified.
    $( ".selector" ).datepicker({ prevText: 'Earlier' });
    Get or set the prevText option, after init.
    //getter
var prevText = $( ".selector" ).datepicker( "option", "prevText" );
//setter
$( ".selector" ).datepicker( "option", "prevText", 'Earlier' );

  • selectOtherMonths

    Type:
    Boolean
    Default:
    false

    When true days in other months shown before or after the current month are selectable. This only applies if showOtherMonths is also true.

    Code examples

    Initialize a datepicker with the selectOtherMonths option specified.
    $( ".selector" ).datepicker({ selectOtherMonths: true });
    Get or set the selectOtherMonths option, after init.
    //getter
var selectOtherMonths = $( ".selector" ).datepicker( "option", "selectOtherMonths" );
//setter
$( ".selector" ).datepicker( "option", "selectOtherMonths", true );

  • shortYearCutoff

    Type:
    String, Number
    Default:
    '+10'

    Set the cutoff year for determining the century for a date (used in conjunction with dateFormat 'y'). If a numeric value (0-99) is provided then this value is used directly. If a string value is provided then it is converted to a number and added to the current year. Once the cutoff year is calculated, any dates entered with a year value less than or equal to it are considered to be in the current century, while those greater than it are deemed to be in the previous century.

    Code examples

    Initialize a datepicker with the shortYearCutoff option specified.
    $( ".selector" ).datepicker({ shortYearCutoff: 50 });
    Get or set the shortYearCutoff option, after init.
    //getter
var shortYearCutoff = $( ".selector" ).datepicker( "option", "shortYearCutoff" );
//setter
$( ".selector" ).datepicker( "option", "shortYearCutoff", 50 );

  • showAnim

    Type:
    String
    Default:
    'show'

    Set the name of the animation used to show/hide the datepicker. Use 'show' (the default), 'slideDown', 'fadeIn', any of the show/hide jQuery UI effects, or '' for no animation.

    Code examples

    Initialize a datepicker with the showAnim option specified.
    $( ".selector" ).datepicker({ showAnim: 'fold' });
    Get or set the showAnim option, after init.
    //getter
var showAnim = $( ".selector" ).datepicker( "option", "showAnim" );
//setter
$( ".selector" ).datepicker( "option", "showAnim", 'fold' );

  • showButtonPanel

    Type:
    Boolean
    Default:
    false

    Whether to show the button panel.

    Code examples

    Initialize a datepicker with the showButtonPanel option specified.
    $( ".selector" ).datepicker({ showButtonPanel: true });
    Get or set the showButtonPanel option, after init.
    //getter
var showButtonPanel = $( ".selector" ).datepicker( "option", "showButtonPanel" );
//setter
$( ".selector" ).datepicker( "option", "showButtonPanel", true );

  • showCurrentAtPos

    Type:
    Number
    Default:
    0

    Specify where in a multi-month display the current month shows, starting from 0 at the top/left.

    Code examples

    Initialize a datepicker with the showCurrentAtPos option specified.
    $( ".selector" ).datepicker({ showCurrentAtPos: 3 });
    Get or set the showCurrentAtPos option, after init.
    //getter
var showCurrentAtPos = $( ".selector" ).datepicker( "option", "showCurrentAtPos" );
//setter
$( ".selector" ).datepicker( "option", "showCurrentAtPos", 3 );

  • showMonthAfterYear

    Type:
    Boolean
    Default:
    false

    Whether to show the month after the year in the header. This attribute is one of the regionalisation attributes.

    Code examples

    Initialize a datepicker with the showMonthAfterYear option specified.
    $( ".selector" ).datepicker({ showMonthAfterYear: true });
    Get or set the showMonthAfterYear option, after init.
    //getter
var showMonthAfterYear = $( ".selector" ).datepicker( "option", "showMonthAfterYear" );
//setter
$( ".selector" ).datepicker( "option", "showMonthAfterYear", true );

  • showOn

    Type:
    String
    Default:
    'focus'

    Have the datepicker appear automatically when the field receives focus ('focus'), appear only when a button is clicked ('button'), or appear when either event takes place ('both').

    Code examples

    Initialize a datepicker with the showOn option specified.
    $( ".selector" ).datepicker({ showOn: 'both' });
    Get or set the showOn option, after init.
    //getter
var showOn = $( ".selector" ).datepicker( "option", "showOn" );
//setter
$( ".selector" ).datepicker( "option", "showOn", 'both' );

  • showOptions

    Type:
    Options
    Default:
    {}

    If using one of the jQuery UI effects for showAnim, you can provide additional settings for that animation via this option.

    Code examples

    Initialize a datepicker with the showOptions option specified.
    $( ".selector" ).datepicker({ showOptions: {direction: 'up' });
    Get or set the showOptions option, after init.
    //getter
var showOptions = $( ".selector" ).datepicker( "option", "showOptions" );
//setter
$( ".selector" ).datepicker( "option", "showOptions", {direction: 'up' );

  • showOtherMonths

    Type:
    Boolean
    Default:
    false

    Display dates in other months (non-selectable) at the start or end of the current month. To make these days selectable use selectOtherMonths.

    Code examples

    Initialize a datepicker with the showOtherMonths option specified.
    $( ".selector" ).datepicker({ showOtherMonths: true });
    Get or set the showOtherMonths option, after init.
    //getter
var showOtherMonths = $( ".selector" ).datepicker( "option", "showOtherMonths" );
//setter
$( ".selector" ).datepicker( "option", "showOtherMonths", true );

  • showWeek

    Type:
    Boolean
    Default:
    false

    When true a column is added to show the week of the year. The calculateWeek option determines how the week of the year is calculated. You may also want to change the firstDay option.

    Code examples

    Initialize a datepicker with the showWeek option specified.
    $( ".selector" ).datepicker({ showWeek: true });
    Get or set the showWeek option, after init.
    //getter
var showWeek = $( ".selector" ).datepicker( "option", "showWeek" );
//setter
$( ".selector" ).datepicker( "option", "showWeek", true );

  • stepMonths

    Type:
    Number
    Default:
    1

    Set how many months to move when clicking the Previous/Next links.

    Code examples

    Initialize a datepicker with the stepMonths option specified.
    $( ".selector" ).datepicker({ stepMonths: 3 });
    Get or set the stepMonths option, after init.
    //getter
var stepMonths = $( ".selector" ).datepicker( "option", "stepMonths" );
//setter
$( ".selector" ).datepicker( "option", "stepMonths", 3 );

  • weekHeader

    Type:
    String
    Default:
    'Wk'

    The text to display for the week of the year column heading. This attribute is one of the regionalisation attributes. Use showWeek to display this column.

    Code examples

    Initialize a datepicker with the weekHeader option specified.
    $( ".selector" ).datepicker({ weekHeader: 'W' });
    Get or set the weekHeader option, after init.
    //getter
var weekHeader = $( ".selector" ).datepicker( "option", "weekHeader" );
//setter
$( ".selector" ).datepicker( "option", "weekHeader", 'W' );

  • yearRange

    Type:
    String
    Default:
    'c-10:c+10'

    Control the range of years displayed in the year drop-down: either relative to today's year (-nn:+nn), relative to the currently selected year (c-nn:c+nn), absolute (nnnn:nnnn), or combinations of these formats (nnnn:-nn). Note that this option only affects what appears in the drop-down, to restrict which dates may be selected use the minDate and/or maxDate options.

    Code examples

    Initialize a datepicker with the yearRange option specified.
    $( ".selector" ).datepicker({ yearRange: '2000:2010' });
    Get or set the yearRange option, after init.
    //getter
var yearRange = $( ".selector" ).datepicker( "option", "yearRange" );
//setter
$( ".selector" ).datepicker( "option", "yearRange", '2000:2010' );

  • yearSuffix

    Type:
    String
    Default:
    ''

    Additional text to display after the year in the month headers. This attribute is one of the regionalisation attributes.

    Code examples

    Initialize a datepicker with the yearSuffix option specified.
    $( ".selector" ).datepicker({ yearSuffix: 'CE' });
    Get or set the yearSuffix option, after init.
    //getter
var yearSuffix = $( ".selector" ).datepicker( "option", "yearSuffix" );
//setter
$( ".selector" ).datepicker( "option", "yearSuffix", 'CE' );

Events

  • create

    Type:
    datepickercreate

    This event is triggered when datepicker is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).datepicker({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: datepickercreate.
    $( ".selector" ).bind( "datepickercreate", function(event, ui) {
  ...
});

  • beforeShow

    function(input, inst)

    Can be a function that takes an input field and current datepicker instance and returns an options object to update the datepicker with. It is called just before the datepicker is displayed.

    Code examples

    Supply a callback function to handle the beforeShow event as an init option.
    $('.selector').datepicker({
   beforeShow: function(input, inst) { ... }
});

  • beforeShowDay

    function(date)

    The function takes a date as a parameter and must return an array with [0] equal to true/false indicating whether or not this date is selectable, [1] equal to a CSS class name(s) or '' for the default presentation, and [2] an optional popup tooltip for this date. It is called for each day in the datepicker before it is displayed.

    Code examples

    Supply a callback function to handle the beforeShowDay event as an init option.
    $('.selector').datepicker({
   beforeShowDay: function(date) { ... }
});

  • onChangeMonthYear

    function(year, month, inst)

    Allows you to define your own event when the datepicker moves to a new month and/or year. The function receives the selected year, month (1-12), and the datepicker instance as parameters. this refers to the associated input field.

    Code examples

    Supply a callback function to handle the onChangeMonthYear event as an init option.
    $('.selector').datepicker({
   onChangeMonthYear: function(year, month, inst) { ... }
});

  • onClose

    function(dateText, inst)

    Allows you to define your own event when the datepicker is closed, whether or not a date is selected. The function receives the selected date as text ('' if none) and the datepicker instance as parameters. this refers to the associated input field.

    Code examples

    Supply a callback function to handle the onClose event as an init option.
    $('.selector').datepicker({
   onClose: function(dateText, inst) { ... }
});

  • onSelect

    function(dateText, inst)

    Allows you to define your own event when the datepicker is selected. The function receives the selected date as text and the datepicker instance as parameters. this refers to the associated input field.

    Code examples

    Supply a callback function to handle the onSelect event as an init option.
    $('.selector').datepicker({
   onSelect: function(dateText, inst) { ... }
});

Methods

  • destroy

    Signature:
    .datepicker( "destroy" )

    Remove the datepicker functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .datepicker( "disable" )

    Disable the datepicker.

  • enable

    Signature:
    .datepicker( "enable" )

    Enable the datepicker.

  • option

    Signature:
    .datepicker( "option" , optionName , [value] )

    Get or set any datepicker option. If no value is specified, will act as a getter.

  • option

    Signature:
    .datepicker( "option" , options )

    Set multiple datepicker options at once by providing an options object.

  • widget

    Signature:
    .datepicker( "widget" )

    Returns the .ui-datepicker element.

  • dialog

    Signature:
    .datepicker( "dialog" , date , [onSelect] , [settings] , [pos] )

    Open a datepicker in a "dialog" box.

    dateText: the initial date for the date picker as either a Date or a string in the current date format.

    onSelect: A callback function when a date is selected. The function receives the date text and date picker instance as parameters.

    settings: The new settings for the date picker.

    pos: The position of the top/left of the dialog as [x, y] or a MouseEvent that contains the coordinates. If not specified the dialog is centered on the screen.

  • isDisabled

    Signature:
    .datepicker( "isDisabled" )

    Determine whether a date picker has been disabled.

  • hide

    Signature:
    .datepicker( "hide" )

    Close a previously opened date picker.

  • show

    Signature:
    .datepicker( "show" )

    Call up a previously attached date picker.

  • refresh

    Signature:
    .datepicker( "refresh" )

    Redraw a date picker, after having made some external modifications.

  • getDate

    Signature:
    .datepicker( "getDate" )

    Returns the current date for the datepicker or null if no date has been selected.

  • setDate

    Signature:
    .datepicker( "setDate" , date )

    Sets the current date for the datepicker. The new date may be a Date object or a string in the current date format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected date.

Theming

The jQuery UI Datepicker plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.datepicker.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible">
<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-all">
<a class="ui-datepicker-prev ui-corner-all">title="Prev"><span class="ui-icon ui-icon-circle-triangle-w">Prev</span></a>
<a class="ui-datepicker-next ui-corner-all" title="Next"><span class="ui-icon ui-icon-circle-triangle-e">Next</span></a>
<div class="ui-datepicker-title">
<span class="ui-datepicker-month">January</span><span class="ui-datepicker-year">2009</span>
</div>
</div>
<table class="ui-datepicker-calendar">
<thead>
<tr>
<th class="ui-datepicker-week-end"><span title="Sunday">Su</span></th>
...
</tr>
</thead>
<tbody><tr>
<td class="ui-datepicker-week-end ui-datepicker-other-month "> 1 </td>
...
</tr>
</tbody>
</table>
<div class="ui-datepicker-buttonpane ui-widget-content">
<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all">Today</button>
<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all">Done</button>
</div>
</div>

Note: This is a sample of markup generated by the datepicker plugin, not markup you should use to create a datepicker. The only markup needed for that is <input type="text" /> or <div></div>.


Dialog – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Dialog

Overview

A dialog is a floating window that contains a title bar and a content area. The dialog window can be moved, resized and closed with the 'x' icon by default.

If the content length exceeds the maximum height, a scrollbar will automatically appear.

A bottom button bar and semi-transparent modal overlay layer are common options that can be added.

A call to $(foo).dialog() will initialize a dialog instance and will auto-open the dialog by default. If you want to reuse a dialog, the easiest way is to disable the "auto-open" option with: $(foo).dialog({ autoOpen: false }) and open it with $(foo).dialog('open'). To close it, use $(foo).dialog('close'). A more in-depth explanation with a full demo is available on the Nemikor blog.

Dependencies

  • UI Core
  • UI Position
  • UI Widget
  • UI Mouse (Optional; only needed if using UI Draggable or UI Resizable)
  • UI Draggable (Optional)
  • UI Resizable (Optional)

Example

  • Demo
  • View Source

A simple jQuery UI Dialog.

$("#dialog").dialog();

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("#dialog").dialog();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="dialog" title="Dialog Title">I'm in a dialog</div>

</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the dialog. Can be set when initialising (first creating) the dialog.

    Code examples

    Initialize a dialog with the disabled option specified.
    $( ".selector" ).dialog({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).dialog( "option", "disabled" );
//setter
$( ".selector" ).dialog( "option", "disabled", true );

  • autoOpen

    Type:
    Boolean
    Default:
    true

    When autoOpen is true the dialog will open automatically when dialog is called. If false it will stay hidden until .dialog("open") is called on it.

    Code examples

    Initialize a dialog with the autoOpen option specified.
    $( ".selector" ).dialog({ autoOpen: false });
    Get or set the autoOpen option, after init.
    //getter
var autoOpen = $( ".selector" ).dialog( "option", "autoOpen" );
//setter
$( ".selector" ).dialog( "option", "autoOpen", false );

  • buttons

    Type:
    Object
    Default:
    { }

    Specifies which buttons should be displayed on the dialog. The property key is the text of the button. The value is the callback function for when the button is clicked. The context of the callback is the dialog element; if you need access to the button, it is available as the target of the event object.

    Code examples

    Initialize a dialog with the buttons option specified.
    $( ".selector" ).dialog({ buttons: { "Ok": function() { $(this).dialog("close"); } } });
    Get or set the buttons option, after init.
    //getter
var buttons = $( ".selector" ).dialog( "option", "buttons" );
//setter
$( ".selector" ).dialog( "option", "buttons", { "Ok": function() { $(this).dialog("close"); } } );

  • buttons

    Type:
    Array
    Default:
    [ ]

    Specifies which buttons should be displayed on the dialog. Each element of the array must be an Object defining the properties to set on the button.

    Code examples

    Initialize a dialog with the buttons option specified.
    $( ".selector" ).dialog({ buttons: [
    {
        text: "Ok",
        click: function() { $(this).dialog("close"); }
    }
] });
    Get or set the buttons option, after init.
    //getter
var buttons = $( ".selector" ).dialog( "option", "buttons" );
//setter
$( ".selector" ).dialog( "option", "buttons", [
    {
        text: "Ok",
        click: function() { $(this).dialog("close"); }
    }
] );

  • closeOnEscape

    Type:
    Boolean
    Default:
    true

    Specifies whether the dialog should close when it has focus and the user presses the esacpe (ESC) key.

    Code examples

    Initialize a dialog with the closeOnEscape option specified.
    $( ".selector" ).dialog({ closeOnEscape: false });
    Get or set the closeOnEscape option, after init.
    //getter
var closeOnEscape = $( ".selector" ).dialog( "option", "closeOnEscape" );
//setter
$( ".selector" ).dialog( "option", "closeOnEscape", false );

  • closeText

    Type:
    String
    Default:
    'close'

    Specifies the text for the close button. Note that the close text is visibly hidden when using a standard theme.

    Code examples

    Initialize a dialog with the closeText option specified.
    $( ".selector" ).dialog({ closeText: 'hide' });
    Get or set the closeText option, after init.
    //getter
var closeText = $( ".selector" ).dialog( "option", "closeText" );
//setter
$( ".selector" ).dialog( "option", "closeText", 'hide' );

  • dialogClass

    Type:
    String
    Default:
    ''

    The specified class name(s) will be added to the dialog, for additional theming.

    Code examples

    Initialize a dialog with the dialogClass option specified.
    $( ".selector" ).dialog({ dialogClass: 'alert' });
    Get or set the dialogClass option, after init.
    //getter
var dialogClass = $( ".selector" ).dialog( "option", "dialogClass" );
//setter
$( ".selector" ).dialog( "option", "dialogClass", 'alert' );

  • draggable

    Type:
    Boolean
    Default:
    true

    If set to true, the dialog will be draggable will be draggable by the titlebar.

    Code examples

    Initialize a dialog with the draggable option specified.
    $( ".selector" ).dialog({ draggable: false });
    Get or set the draggable option, after init.
    //getter
var draggable = $( ".selector" ).dialog( "option", "draggable" );
//setter
$( ".selector" ).dialog( "option", "draggable", false );

  • height

    Type:
    Number
    Default:
    'auto'

    The height of the dialog, in pixels. Specifying 'auto' is also supported to make the dialog adjust based on its content.

    Code examples

    Initialize a dialog with the height option specified.
    $( ".selector" ).dialog({ height: 530 });
    Get or set the height option, after init.
    //getter
var height = $( ".selector" ).dialog( "option", "height" );
//setter
$( ".selector" ).dialog( "option", "height", 530 );

  • hide

    Type:
    String
    Default:
    null

    The effect to be used when the dialog is closed.

    Code examples

    Initialize a dialog with the hide option specified.
    $( ".selector" ).dialog({ hide: 'slide' });
    Get or set the hide option, after init.
    //getter
var hide = $( ".selector" ).dialog( "option", "hide" );
//setter
$( ".selector" ).dialog( "option", "hide", 'slide' );

  • maxHeight

    Type:
    Number
    Default:
    false

    The maximum height to which the dialog can be resized, in pixels.

    Code examples

    Initialize a dialog with the maxHeight option specified.
    $( ".selector" ).dialog({ maxHeight: 400 });
    Get or set the maxHeight option, after init.
    //getter
var maxHeight = $( ".selector" ).dialog( "option", "maxHeight" );
//setter
$( ".selector" ).dialog( "option", "maxHeight", 400 );

  • maxWidth

    Type:
    Number
    Default:
    false

    The maximum width to which the dialog can be resized, in pixels.

    Code examples

    Initialize a dialog with the maxWidth option specified.
    $( ".selector" ).dialog({ maxWidth: 600 });
    Get or set the maxWidth option, after init.
    //getter
var maxWidth = $( ".selector" ).dialog( "option", "maxWidth" );
//setter
$( ".selector" ).dialog( "option", "maxWidth", 600 );

  • minHeight

    Type:
    Number
    Default:
    150

    The minimum height to which the dialog can be resized, in pixels.

    Code examples

    Initialize a dialog with the minHeight option specified.
    $( ".selector" ).dialog({ minHeight: 300 });
    Get or set the minHeight option, after init.
    //getter
var minHeight = $( ".selector" ).dialog( "option", "minHeight" );
//setter
$( ".selector" ).dialog( "option", "minHeight", 300 );

  • minWidth

    Type:
    Number
    Default:
    150

    The minimum width to which the dialog can be resized, in pixels.

    Code examples

    Initialize a dialog with the minWidth option specified.
    $( ".selector" ).dialog({ minWidth: 400 });
    Get or set the minWidth option, after init.
    //getter
var minWidth = $( ".selector" ).dialog( "option", "minWidth" );
//setter
$( ".selector" ).dialog( "option", "minWidth", 400 );

  • modal

    Type:
    Boolean
    Default:
    false

    If set to true, the dialog will have modal behavior; other items on the page will be disabled (i.e. cannot be interacted with). Modal dialogs create an overlay below the dialog but above other page elements.

    Code examples

    Initialize a dialog with the modal option specified.
    $( ".selector" ).dialog({ modal: true });
    Get or set the modal option, after init.
    //getter
var modal = $( ".selector" ).dialog( "option", "modal" );
//setter
$( ".selector" ).dialog( "option", "modal", true );

  • position

    Type:
    String, Array
    Default:
    'center'

    Specifies where the dialog should be displayed. Possible values:
    1) a single string representing position within viewport: 'center', 'left', 'right', 'top', 'bottom'.
    2) an array containing an x,y coordinate pair in pixel offset from left, top corner of viewport (e.g. [350,100])
    3) an array containing x,y position string values (e.g. ['right','top'] for top right corner).

    Code examples

    Initialize a dialog with the position option specified.
    $( ".selector" ).dialog({ position: 'top' });
    Get or set the position option, after init.
    //getter
var position = $( ".selector" ).dialog( "option", "position" );
//setter
$( ".selector" ).dialog( "option", "position", 'top' );

  • resizable

    Type:
    Boolean
    Default:
    true

    If set to true, the dialog will be resizeable.

    Code examples

    Initialize a dialog with the resizable option specified.
    $( ".selector" ).dialog({ resizable: false });
    Get or set the resizable option, after init.
    //getter
var resizable = $( ".selector" ).dialog( "option", "resizable" );
//setter
$( ".selector" ).dialog( "option", "resizable", false );

  • show

    Type:
    String
    Default:
    null

    The effect to be used when the dialog is opened.

    Code examples

    Initialize a dialog with the show option specified.
    $( ".selector" ).dialog({ show: 'slide' });
    Get or set the show option, after init.
    //getter
var show = $( ".selector" ).dialog( "option", "show" );
//setter
$( ".selector" ).dialog( "option", "show", 'slide' );

  • stack

    Type:
    Boolean
    Default:
    true

    Specifies whether the dialog will stack on top of other dialogs. This will cause the dialog to move to the front of other dialogs when it gains focus.

    Code examples

    Initialize a dialog with the stack option specified.
    $( ".selector" ).dialog({ stack: false });
    Get or set the stack option, after init.
    //getter
var stack = $( ".selector" ).dialog( "option", "stack" );
//setter
$( ".selector" ).dialog( "option", "stack", false );

  • title

    Type:
    String
    Default:
    ''

    Specifies the title of the dialog. Any valid HTML may be set as the title. The title can also be specified by the title attribute on the dialog source element.

    Code examples

    Initialize a dialog with the title option specified.
    $( ".selector" ).dialog({ title: 'Dialog Title' });
    Get or set the title option, after init.
    //getter
var title = $( ".selector" ).dialog( "option", "title" );
//setter
$( ".selector" ).dialog( "option", "title", 'Dialog Title' );

  • width

    Type:
    Number
    Default:
    300

    The width of the dialog, in pixels.

    Code examples

    Initialize a dialog with the width option specified.
    $( ".selector" ).dialog({ width: 460 });
    Get or set the width option, after init.
    //getter
var width = $( ".selector" ).dialog( "option", "width" );
//setter
$( ".selector" ).dialog( "option", "width", 460 );

  • zIndex

    Type:
    Integer
    Default:
    1000

    The starting z-index for the dialog.

    Code examples

    Initialize a dialog with the zIndex option specified.
    $( ".selector" ).dialog({ zIndex: 3999 });
    Get or set the zIndex option, after init.
    //getter
var zIndex = $( ".selector" ).dialog( "option", "zIndex" );
//setter
$( ".selector" ).dialog( "option", "zIndex", 3999 );

Events

  • create

    Type:
    dialogcreate

    This event is triggered when dialog is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).dialog({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: dialogcreate.
    $( ".selector" ).bind( "dialogcreate", function(event, ui) {
  ...
});

  • beforeClose

    Type:
    dialogbeforeclose

    This event is triggered when a dialog attempts to close. If the beforeClose event handler (callback function) returns false, the close will be prevented.

    Code examples

    Supply a callback function to handle the beforeClose event as an init option.
    $( ".selector" ).dialog({
   beforeClose: function(event, ui) { ... }
});
    Bind to the beforeClose event by type: dialogbeforeclose.
    $( ".selector" ).bind( "dialogbeforeclose", function(event, ui) {
  ...
});

  • open

    Type:
    dialogopen

    This event is triggered when dialog is opened.

    Code examples

    Supply a callback function to handle the open event as an init option.
    $( ".selector" ).dialog({
   open: function(event, ui) { ... }
});
    Bind to the open event by type: dialogopen.
    $( ".selector" ).bind( "dialogopen", function(event, ui) {
  ...
});

  • focus

    Type:
    dialogfocus

    This event is triggered when the dialog gains focus.

    Code examples

    Supply a callback function to handle the focus event as an init option.
    $( ".selector" ).dialog({
   focus: function(event, ui) { ... }
});
    Bind to the focus event by type: dialogfocus.
    $( ".selector" ).bind( "dialogfocus", function(event, ui) {
  ...
});

  • dragStart

    Type:
    dialogdragstart

    This event is triggered at the beginning of the dialog being dragged.

    Code examples

    Supply a callback function to handle the dragStart event as an init option.
    $( ".selector" ).dialog({
   dragStart: function(event, ui) { ... }
});
    Bind to the dragStart event by type: dialogdragstart.
    $( ".selector" ).bind( "dialogdragstart", function(event, ui) {
  ...
});

  • drag

    Type:
    dialogdrag

    This event is triggered when the dialog is dragged.

    Code examples

    Supply a callback function to handle the drag event as an init option.
    $( ".selector" ).dialog({
   drag: function(event, ui) { ... }
});
    Bind to the drag event by type: dialogdrag.
    $( ".selector" ).bind( "dialogdrag", function(event, ui) {
  ...
});

  • dragStop

    Type:
    dialogdragstop

    This event is triggered after the dialog has been dragged.

    Code examples

    Supply a callback function to handle the dragStop event as an init option.
    $( ".selector" ).dialog({
   dragStop: function(event, ui) { ... }
});
    Bind to the dragStop event by type: dialogdragstop.
    $( ".selector" ).bind( "dialogdragstop", function(event, ui) {
  ...
});

  • resizeStart

    Type:
    dialogresizestart

    This event is triggered at the beginning of the dialog being resized.

    Code examples

    Supply a callback function to handle the resizeStart event as an init option.
    $( ".selector" ).dialog({
   resizeStart: function(event, ui) { ... }
});
    Bind to the resizeStart event by type: dialogresizestart.
    $( ".selector" ).bind( "dialogresizestart", function(event, ui) {
  ...
});

  • resize

    Type:
    dialogresize

    This event is triggered when the dialog is resized. demo

    Code examples

    Supply a callback function to handle the resize event as an init option.
    $( ".selector" ).dialog({
   resize: function(event, ui) { ... }
});
    Bind to the resize event by type: dialogresize.
    $( ".selector" ).bind( "dialogresize", function(event, ui) {
  ...
});

  • resizeStop

    Type:
    dialogresizestop

    This event is triggered after the dialog has been resized.

    Code examples

    Supply a callback function to handle the resizeStop event as an init option.
    $( ".selector" ).dialog({
   resizeStop: function(event, ui) { ... }
});
    Bind to the resizeStop event by type: dialogresizestop.
    $( ".selector" ).bind( "dialogresizestop", function(event, ui) {
  ...
});

  • close

    Type:
    dialogclose

    This event is triggered when the dialog is closed.

    Code examples

    Supply a callback function to handle the close event as an init option.
    $( ".selector" ).dialog({
   close: function(event, ui) { ... }
});
    Bind to the close event by type: dialogclose.
    $( ".selector" ).bind( "dialogclose", function(event, ui) {
  ...
});

Methods

  • destroy

    Signature:
    .dialog( "destroy" )

    Remove the dialog functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .dialog( "disable" )

    Disable the dialog.

  • enable

    Signature:
    .dialog( "enable" )

    Enable the dialog.

  • option

    Signature:
    .dialog( "option" , optionName , [value] )

    Get or set any dialog option. If no value is specified, will act as a getter.

  • option

    Signature:
    .dialog( "option" , options )

    Set multiple dialog options at once by providing an options object.

  • widget

    Signature:
    .dialog( "widget" )

    Returns the .ui-dialog element.

  • close

    Signature:
    .dialog( "close" )

    Close the dialog.

  • isOpen

    Signature:
    .dialog( "isOpen" )

    Returns true if the dialog is currently open.

  • moveToTop

    Signature:
    .dialog( "moveToTop" )

    Move the dialog to the top of the dialogs stack.

  • open

    Signature:
    .dialog( "open" )

    Open the dialog.

Theming

The jQuery UI Dialog plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.dialog.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable ui-resizable">
<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
<span id="ui-dialog-title-dialog" class="ui-dialog-title">Dialog title</span>
<a class="ui-dialog-titlebar-close ui-corner-all" href="#"><span class="ui-icon ui-icon-closethick">close</span></a>
</div>
<div style="height: 200px; min-height: 109px; width: auto;" class="ui-dialog-content ui-widget-content" id="dialog">
<p>Dialog content goes here.</p>
</div>
</div>

Note: This is a sample of markup generated by the dialog plugin, not markup you should use to create a dialog. The only markup needed for that is <div></div>.


Progressbar – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Progressbar

Overview

The progress bar is designed to simply display the current % complete for a process. The bar is coded to be flexibly sized through CSS and will scale to fit inside it's parent container by default.

This is a determinate progress bar, meaning that it should only be used in situations where the system can accurately update the current status complete. A determinate progress bar should never fill from left to right, then loop back to empty for a single process -- if the actual percent complete status cannot be calculated, an indeterminate progress bar (coming soon) or spinner animation is a better way to provide user feedback.

Dependencies

  • UI Core
  • UI Widget

Example

  • Demo
  • View Source

A simple jQuery UI Progressbar.

$("#progressbar").progressbar({ value: 37 });

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("#progressbar").progressbar({ value: 37 });
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="progressbar"></div>

</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the progressbar. Can be set when initialising (first creating) the progressbar.

    Code examples

    Initialize a progressbar with the disabled option specified.
    $( ".selector" ).progressbar({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).progressbar( "option", "disabled" );
//setter
$( ".selector" ).progressbar( "option", "disabled", true );

  • value

    Type:
    Number
    Default:
    0

    The value of the progressbar.

    Code examples

    Initialize a progressbar with the value option specified.
    $( ".selector" ).progressbar({ value: 37 });
    Get or set the value option, after init.
    //getter
var value = $( ".selector" ).progressbar( "option", "value" );
//setter
$( ".selector" ).progressbar( "option", "value", 37 );

Events

  • create

    Type:
    progressbarcreate

    This event is triggered when progressbar is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).progressbar({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: progressbarcreate.
    $( ".selector" ).bind( "progressbarcreate", function(event, ui) {
  ...
});

  • change

    Type:
    progressbarchange

    This event is triggered when the value of the progressbar changes.

    Code examples

    Supply a callback function to handle the change event as an init option.
    $( ".selector" ).progressbar({
   change: function(event, ui) { ... }
});
    Bind to the change event by type: progressbarchange.
    $( ".selector" ).bind( "progressbarchange", function(event, ui) {
  ...
});

  • complete

    Type:
    progressbarcomplete

    This event is triggered when the value of the progressbar reaches the maximum value of 100.

    Code examples

    Supply a callback function to handle the complete event as an init option.
    $( ".selector" ).progressbar({
   complete: function(event, ui) { ... }
});
    Bind to the complete event by type: progressbarcomplete.
    $( ".selector" ).bind( "progressbarcomplete", function(event, ui) {
  ...
});

Methods

  • destroy

    Signature:
    .progressbar( "destroy" )

    Remove the progressbar functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .progressbar( "disable" )

    Disable the progressbar.

  • enable

    Signature:
    .progressbar( "enable" )

    Enable the progressbar.

  • option

    Signature:
    .progressbar( "option" , optionName , [value] )

    Get or set any progressbar option. If no value is specified, will act as a getter.

  • option

    Signature:
    .progressbar( "option" , options )

    Set multiple progressbar options at once by providing an options object.

  • widget

    Signature:
    .progressbar( "widget" )

    Returns the .ui-progressbar element.

  • value

    Signature:
    .progressbar( "value" , [value] )

    This method gets or sets the current value of the progressbar.

Theming

The jQuery UI Progressbar plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.progressbar.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<div class="ui-progressbar ui-widget ui-widget-content ui-corner-all">
<div style="width: 37%;" class="ui-progressbar-value ui-widget-header ui-corner-left"></div>
</div>

Note: This is a sample of markup generated by the progressbar plugin, not markup you should use to create a progressbar. The only markup needed for that is <div></div>.


Slider – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Slider

Overview

The jQuery UI Slider plugin makes selected elements into sliders. There are various options such as multiple handles, and ranges. The handle can be moved with the mouse or the arrow keys.

All callbacks receive two arguments: The original browser event and a prepared ui object, view below for a documentation of this object (if you name your second argument 'ui'):

The slider widget will create handle elements with the class 'ui-slider-handle' on initialization. You can specify custom handle elements by creating and appending the elements and adding the 'ui-slider-handle' class before init. It will only create the number of handles needed to match the length of value/values. For example, if you specify 'values: [1, 5, 18]' and create one custom handle, the plugin will create the other two.

  • ui.handle: DOMElement - the current focused handle
  • ui.value: Integer - the current handle's value

Dependencies

  • UI Core
  • UI Widget
  • UI Mouse

Example

  • Demo
  • View Source

A simple jQuery UI Slider.

$("#slider").slider();

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
    <style type="text/css">
    #slider { margin: 10px; }
  </style>
  <script>
  $(document).ready(function() {
    $("#slider").slider();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="slider"></div>

</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the slider. Can be set when initialising (first creating) the slider.

    Code examples

    Initialize a slider with the disabled option specified.
    $( ".selector" ).slider({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).slider( "option", "disabled" );
//setter
$( ".selector" ).slider( "option", "disabled", true );

  • animate

    Type:
    Boolean, String, Number
    Default:
    false

    Whether to slide handle smoothly when user click outside handle on the bar. Will also accept 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).

    Code examples

    Initialize a slider with the animate option specified.
    $( ".selector" ).slider({ animate: true });
    Get or set the animate option, after init.
    //getter
var animate = $( ".selector" ).slider( "option", "animate" );
//setter
$( ".selector" ).slider( "option", "animate", true );

  • max

    Type:
    Number
    Default:
    100

    The maximum value of the slider.

    Code examples

    Initialize a slider with the max option specified.
    $( ".selector" ).slider({ max: 7 });
    Get or set the max option, after init.
    //getter
var max = $( ".selector" ).slider( "option", "max" );
//setter
$( ".selector" ).slider( "option", "max", 7 );

  • min

    Type:
    Number
    Default:
    0

    The minimum value of the slider.

    Code examples

    Initialize a slider with the min option specified.
    $( ".selector" ).slider({ min: -7 });
    Get or set the min option, after init.
    //getter
var min = $( ".selector" ).slider( "option", "min" );
//setter
$( ".selector" ).slider( "option", "min", -7 );

  • orientation

    Type:
    String
    Default:
    'horizontal'

    This option determines whether the slider has the min at the left, the max at the right or the min at the bottom, the max at the top. Possible values: 'horizontal', 'vertical'.

    Code examples

    Initialize a slider with the orientation option specified.
    $( ".selector" ).slider({ orientation: 'vertical' });
    Get or set the orientation option, after init.
    //getter
var orientation = $( ".selector" ).slider( "option", "orientation" );
//setter
$( ".selector" ).slider( "option", "orientation", 'vertical' );

  • range

    Type:
    Boolean, String
    Default:
    false

    If set to true, the slider will detect if you have two handles and create a stylable range element between these two. Two other possible values are 'min' and 'max'. A min range goes from the slider min to one handle. A max range goes from one handle to the slider max.

    Code examples

    Initialize a slider with the range option specified.
    $( ".selector" ).slider({ range: 'min' });
    Get or set the range option, after init.
    //getter
var range = $( ".selector" ).slider( "option", "range" );
//setter
$( ".selector" ).slider( "option", "range", 'min' );

  • step

    Type:
    Number
    Default:
    1

    Determines the size or amount of each interval or step the slider takes between min and max. The full specified value range of the slider (max - min) needs to be evenly divisible by the step.

    Code examples

    Initialize a slider with the step option specified.
    $( ".selector" ).slider({ step: 5 });
    Get or set the step option, after init.
    //getter
var step = $( ".selector" ).slider( "option", "step" );
//setter
$( ".selector" ).slider( "option", "step", 5 );

  • value

    Type:
    Number
    Default:
    0

    Determines the value of the slider, if there's only one handle. If there is more than one handle, determines the value of the first handle.

    Code examples

    Initialize a slider with the value option specified.
    $( ".selector" ).slider({ value: 37 });
    Get or set the value option, after init.
    //getter
var value = $( ".selector" ).slider( "option", "value" );
//setter
$( ".selector" ).slider( "option", "value", 37 );

  • values

    Type:
    Array
    Default:
    null

    This option can be used to specify multiple handles. If range is set to true, the length of 'values' should be 2.

    Code examples

    Initialize a slider with the values option specified.
    $( ".selector" ).slider({ values: [1,5,9] });
    Get or set the values option, after init.
    //getter
var values = $( ".selector" ).slider( "option", "values" );
//setter
$( ".selector" ).slider( "option", "values", [1,5,9] );

Events

  • create

    Type:
    slidecreate

    This event is triggered when slider is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).slider({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: slidecreate.
    $( ".selector" ).bind( "slidecreate", function(event, ui) {
  ...
});

  • start

    Type:
    slidestart

    This event is triggered when the user starts sliding.

    Code examples

    Supply a callback function to handle the start event as an init option.
    $( ".selector" ).slider({
   start: function(event, ui) { ... }
});
    Bind to the start event by type: slidestart.
    $( ".selector" ).bind( "slidestart", function(event, ui) {
  ...
});

  • slide

    Type:
    slide

    This event is triggered on every mouse move during slide. Use ui.value (single-handled sliders) to obtain the value of the current handle, $(..).slider('value', index) to get another handles' value.

    Return false in order to prevent a slide, based on ui.value.

    Code examples

    Supply a callback function to handle the slide event as an init option.
    $( ".selector" ).slider({
   slide: function(event, ui) { ... }
});
    Bind to the slide event by type: slide.
    $( ".selector" ).bind( "slide", function(event, ui) {
  ...
});

  • change

    Type:
    slidechange

    This event is triggered on slide stop, or if the value is changed programmatically (by the value method). Takes arguments event and ui. Use event.orginalEvent to detect whether the value changed by mouse, keyboard, or programmatically. Use ui.value (single-handled sliders) to obtain the value of the current handle, $(this).slider('values', index) to get another handle's value.

    Code examples

    Supply a callback function to handle the change event as an init option.
    $( ".selector" ).slider({
   change: function(event, ui) { ... }
});
    Bind to the change event by type: slidechange.
    $( ".selector" ).bind( "slidechange", function(event, ui) {
  ...
});

  • stop

    Type:
    slidestop

    This event is triggered when the user stops sliding.

    Code examples

    Supply a callback function to handle the stop event as an init option.
    $( ".selector" ).slider({
   stop: function(event, ui) { ... }
});
    Bind to the stop event by type: slidestop.
    $( ".selector" ).bind( "slidestop", function(event, ui) {
  ...
});

Methods

  • destroy

    Signature:
    .slider( "destroy" )

    Remove the slider functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .slider( "disable" )

    Disable the slider.

  • enable

    Signature:
    .slider( "enable" )

    Enable the slider.

  • option

    Signature:
    .slider( "option" , optionName , [value] )

    Get or set any slider option. If no value is specified, will act as a getter.

  • option

    Signature:
    .slider( "option" , options )

    Set multiple slider options at once by providing an options object.

  • widget

    Signature:
    .slider( "widget" )

    Returns the .ui-slider element.

  • value

    Signature:
    .slider( "value" , [value] )

    Gets or sets the value of the slider. For single handle sliders.

  • values

    Signature:
    .slider( "values" , index , [value] )

    Gets or sets the values of the slider. For multiple handle or range sliders.

Theming

The jQuery UI Slider plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.slider.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<div class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">
<a style="left: 0%;" class="ui-slider-handle ui-state-default ui-corner-all" href="#"></a>
</div>

Note: This is a sample of markup generated by the slider plugin, not markup you should use to create a slider. The only markup needed for that is <div><div>.


Tabs – jQuery API

  • Overview
  • Options
  • Events
  • Methods
  • Theming

jQuery UI Tabs

Overview

Tabs are generally used to break content into multiple sections that can be swapped to save space, much like an accordion.

By default a tab widget will swap between tabbed sections onClick, but the events can be changed to onHover through an option. Tab content can be loaded via Ajax by setting an href on a tab.

NOTE: Tabs created dynamically using .tabs( "add", ... ) are given an id of ui-tabs-NUM, where NUM is an auto-incrementing id. If you use this naming convention for your own elements, you may encounter problems.

Contents

  • 1 Events
  • 2 Ajax mode
    • 2.1 Back button and bookmarking
  • 3 How to...
    • 3.1 ...retrieve the index of the currently selected tab
    • 3.2 ...open links in the current tab instead of leaving the page
    • 3.3 ...select a tab from a text link instead of clicking a tab itself
    • 3.4 ...prevent switching to the tab on click depending on form validation
    • 3.5 ...immediately select a just added tab
    • 3.6 ...follow a tab's URL instead of loading its content via ajax
    • 3.7 ...prevent a FOUC (Flash of Unstyled Content) before tabs are initialized
  • 4 Why does...
    • 4.1 ...my slider, Google Map, sIFR etc. not work when placed in a hidden (inactive) tab?
[edit]

Events

A series of events fire when interacting with a tabs interface:

  • tabsselect, tabsload, tabsshow (in that order)
  • tabsadd, tabsremove
  • tabsenable, tabsdisable

Event binding example:

$('#example').bind('tabsselect', function(event, ui) {

    // Objects available in the function context:
    ui.tab     // anchor element of the selected (clicked) tab
    ui.panel   // element, that contains the selected/clicked tab contents
    ui.index   // zero-based index of the selected (clicked) tab

});

Note that if a handler for the tabsselect event returns false, the clicked tab will not become selected (useful for example if switching to the next tab requires a form validation).

[edit]

Ajax mode

Tabs supports loading tab content via Ajax in an unobtrusive manner.

The HTML you need is slightly different from the one that is used for static tabs: A list of links pointing to existing resources (from where the content gets loaded) and no additional containers at all (unobtrusive!). The containers' markup is going to be created on the fly:

<div id="example">
     <ul>
         <li><a href="ahah_1.html"><span>Content 1</span></a></li>
         <li><a href="ahah_2.html"><span>Content 2</span></a></li>
         <li><a href="ahah_3.html"><span>Content 3</span></a></li>
     </ul>
</div>

Obviously this degrades gracefully - the links, e.g. the content, will still be accessible with JavaScript disabled.

Note that if you wish to reuse an existing container, you could do so by matching a title attribute and the container's id:

<li><a href="hello/world.html" title="Todo Overview"> ... </a></li>

and a container like:

<div id="Todo_Overview"> ... </div>

(Note how white space is replaced with an underscore)

This is useful if you want a human readable hash in the URL instead of a cryptic generated one.

[edit]

Back button and bookmarking

Tabs 2 already supported this functionality, although the history plugin needs a rewrite first (it doesn't support Safari 3 and is in general a little inflexible) before it can be build back into the tabs. It is planned and Klaus is working on it whenever he finds the time. Actual bugs in the UI Tabs plugin itself always have higher priority though.

[edit]

How to...

[edit]

...retrieve the index of the currently selected tab

var $tabs = $('#example').tabs();
var selected = $tabs.tabs('option', 'selected'); // => 0
[edit]

...open links in the current tab instead of leaving the page

"Hijax" links after tab content has been loaded:

$('#example').tabs({
    load: function(event, ui) {
        $('a', ui.panel).click(function() {
            $(ui.panel).load(this.href);
            return false;
        });
    }
});
[edit]

...select a tab from a text link instead of clicking a tab itself

var $tabs = $('#example').tabs(); // first tab selected

$('#my-text-link').click(function() { // bind click event to link
    $tabs.tabs('select', 2); // switch to third tab
    return false;
});
[edit]

...prevent switching to the tab on click depending on form validation

Returning false in the tabs select handler prevents the clicked tab from becoming selected.

$('#example').tabs({
    select: function(event, ui) {
        var isValid = ... // form validation returning true or false
        return isValid;
    }
});
[edit]

...immediately select a just added tab

var $tabs = $('#example').tabs({
    add: function(event, ui) {
        $tabs.tabs('select', '#' + ui.panel.id);
    }
});
[edit]

...follow a tab's URL instead of loading its content via ajax

Note that opening a tab in a new window is unexpected, e.g. inconsistent behaviour exposing a usablity problem (http://www.useit.com/alertbox/tabs.html).

$('#example').tabs({
    select: function(event, ui) {
        var url = $.data(ui.tab, 'load.tabs');
        if( url ) {
            location.href = url;
            return false;
        }
        return true;
    }
});

[edit]

...prevent a FOUC (Flash of Unstyled Content) before tabs are initialized

Add the necessary classes to hide an inactive tab panel to the HTML right away - note that this will not degrade gracefully with JavaScript being disabled:

<div id="example" class="ui-tabs">
  ...
  <div id="a-tab-panel" class="ui-tabs-hide"> </div>
  ...
</div>
[edit]

Why does...

[edit]

...my slider, Google Map, sIFR etc. not work when placed in a hidden (inactive) tab?

Any component that requires some dimensional computation for its initialization won't work in a hidden tab, because the tab panel itself is hidden via display: none so that any elements inside won't report their actual width and height (0 in most browsers).

There's an easy workaround. Use the off-left technique for hiding inactive tab panels. E.g. in your style sheet replace the rule for the class selector ".ui-tabs .ui-tabs-hide" with

.ui-tabs .ui-tabs-hide {
    position: absolute;
    left: -10000px;
}

For Google maps you can also resize the map once the tab is displayed like this:

$('#example').bind('tabsshow', function(event, ui) {
    if (ui.panel.id == "map-tab") {
        resizeMap();
    }
});
resizeMap() will call Google Maps' checkResize() on the particular map.

Dependencies

  • UI Core
  • UI Widget
  • Optional: jquery.cookie.js for use with cookie option (also included in development-bundle>external folder.)

Example

  • Demo
  • View Source

A simple jQuery UI Tabs.

$("#tabs").tabs();

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("#tabs").tabs();
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="tabs">
    <ul>
        <li><a href="#fragment-1"><span>One</span></a></li>
        <li><a href="#fragment-2"><span>Two</span></a></li>
        <li><a href="#fragment-3"><span>Three</span></a></li>
    </ul>
    <div id="fragment-1">
        <p>First tab is active by default:</p>
        <pre><code>$('#example').tabs();</code></pre>
    </div>
    <div id="fragment-2">
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
    </div>
    <div id="fragment-3">
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
    </div>
</div>
</body>
</html>

Options

  • disabled

    Type:
    Boolean
    Default:
    false

    Disables (true) or enables (false) the tabs. Can be set when initialising (first creating) the tabs.

    Code examples

    Initialize a tabs with the disabled option specified.
    $( ".selector" ).tabs({ disabled: true });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).tabs( "option", "disabled" );
//setter
$( ".selector" ).tabs( "option", "disabled", true );

  • ajaxOptions

    Type:
    Options
    Default:
    null

    Additional Ajax options to consider when loading tab content (see $.ajax).

    Code examples

    Initialize a tabs with the ajaxOptions option specified.
    $( ".selector" ).tabs({ ajaxOptions: { async: false } });
    Get or set the ajaxOptions option, after init.
    //getter
var ajaxOptions = $( ".selector" ).tabs( "option", "ajaxOptions" );
//setter
$( ".selector" ).tabs( "option", "ajaxOptions", { async: false } );

  • cache

    Type:
    Boolean
    Default:
    false

    Whether or not to cache remote tabs content, e.g. load only once or with every click. Cached content is being lazy loaded, e.g once and only once for the first click. Note that to prevent the actual Ajax requests from being cached by the browser you need to provide an extra cache: false flag to ajaxOptions.

    Code examples

    Initialize a tabs with the cache option specified.
    $( ".selector" ).tabs({ cache: true });
    Get or set the cache option, after init.
    //getter
var cache = $( ".selector" ).tabs( "option", "cache" );
//setter
$( ".selector" ).tabs( "option", "cache", true );

  • collapsible

    Type:
    Boolean
    Default:
    false

    Set to true to allow an already selected tab to become unselected again upon reselection.

    Code examples

    Initialize a tabs with the collapsible option specified.
    $( ".selector" ).tabs({ collapsible: true });
    Get or set the collapsible option, after init.
    //getter
var collapsible = $( ".selector" ).tabs( "option", "collapsible" );
//setter
$( ".selector" ).tabs( "option", "collapsible", true );

  • cookie

    Type:
    Object
    Default:
    null

    Store the latest selected tab in a cookie. The cookie is then used to determine the initially selected tab if the selected option is not defined. Requires cookie plugin, which can also be found in the development-bundle>external folder from the download builder. The object needs to have key/value pairs of the form the cookie plugin expects as options. Available options (example): { expires: 7, path: '/', domain: 'jquery.com', secure: true }. Since jQuery UI 1.7 it is also possible to define the cookie name being used via name property.

    Code examples

    Initialize a tabs with the cookie option specified.
    $( ".selector" ).tabs({ cookie: { expires: 30 } });
    Get or set the cookie option, after init.
    //getter
var cookie = $( ".selector" ).tabs( "option", "cookie" );
//setter
$( ".selector" ).tabs( "option", "cookie", { expires: 30 } );

  • deselectable

    Type:
    Boolean
    Default:
    false

    deprecated in jQuery UI 1.7, use collapsible.

    Code examples

    Initialize a tabs with the deselectable option specified.
    $( ".selector" ).tabs({ deselectable: true });
    Get or set the deselectable option, after init.
    //getter
var deselectable = $( ".selector" ).tabs( "option", "deselectable" );
//setter
$( ".selector" ).tabs( "option", "deselectable", true );

  • disabled

    Type:
    Array<Number>
    Default:
    []

    An array containing the position of the tabs (zero-based index) that should be disabled on initialization.

    Code examples

    Initialize a tabs with the disabled option specified.
    $( ".selector" ).tabs({ disabled: [1, 2] });
    Get or set the disabled option, after init.
    //getter
var disabled = $( ".selector" ).tabs( "option", "disabled" );
//setter
$( ".selector" ).tabs( "option", "disabled", [1, 2] );

  • event

    Type:
    String
    Default:
    'click'

    The type of event to be used for selecting a tab.

    Code examples

    Initialize a tabs with the event option specified.
    $( ".selector" ).tabs({ event: 'mouseover' });
    Get or set the event option, after init.
    //getter
var event = $( ".selector" ).tabs( "option", "event" );
//setter
$( ".selector" ).tabs( "option", "event", 'mouseover' );

  • fx

    Type:
    Options, Array<Options>
    Default:
    null

    Enable animations for hiding and showing tab panels. The duration option can be a string representing one of the three predefined speeds ("slow", "normal", "fast") or the duration in milliseconds to run an animation (default is "normal").

    Code examples

    Initialize a tabs with the fx option specified.
    $( ".selector" ).tabs({ fx: { opacity: 'toggle' } });
    Get or set the fx option, after init.
    //getter
var fx = $( ".selector" ).tabs( "option", "fx" );
//setter
$( ".selector" ).tabs( "option", "fx", { opacity: 'toggle' } );

  • idPrefix

    Type:
    String
    Default:
    'ui-tabs-'

    If the remote tab, its anchor element that is, has no title attribute to generate an id from, an id/fragment identifier is created from this prefix and a unique id returned by $.data(el), for example "ui-tabs-54".

    Code examples

    Initialize a tabs with the idPrefix option specified.
    $( ".selector" ).tabs({ idPrefix: 'ui-tabs-primary' });
    Get or set the idPrefix option, after init.
    //getter
var idPrefix = $( ".selector" ).tabs( "option", "idPrefix" );
//setter
$( ".selector" ).tabs( "option", "idPrefix", 'ui-tabs-primary' );

  • panelTemplate

    Type:
    String
    Default:
    '<div></div>'

    HTML template from which a new tab panel is created in case of adding a tab with the add method or when creating a panel for a remote tab on the fly.

    Code examples

    Initialize a tabs with the panelTemplate option specified.
    $( ".selector" ).tabs({ panelTemplate: '<li></li>' });
    Get or set the panelTemplate option, after init.
    //getter
var panelTemplate = $( ".selector" ).tabs( "option", "panelTemplate" );
//setter
$( ".selector" ).tabs( "option", "panelTemplate", '<li></li>' );

  • selected

    Type:
    Number
    Default:
    0

    Zero-based index of the tab to be selected on initialization. To set all tabs to unselected pass -1 as value.

    Code examples

    Initialize a tabs with the selected option specified.
    $( ".selector" ).tabs({ selected: 3 });
    Get or set the selected option, after init.
    //getter
var selected = $( ".selector" ).tabs( "option", "selected" );
//setter
$( ".selector" ).tabs( "option", "selected", 3 );

  • spinner

    Type:
    String
    Default:
    '<em>Loading&#8230;</em>'

    The HTML content of this string is shown in a tab title while remote content is loading. Pass in empty string to deactivate that behavior. An span element must be present in the A tag of the title, for the spinner content to be visible.

    Code examples

    Initialize a tabs with the spinner option specified.
    $( ".selector" ).tabs({ spinner: 'Retrieving data...' });
    Get or set the spinner option, after init.
    //getter
var spinner = $( ".selector" ).tabs( "option", "spinner" );
//setter
$( ".selector" ).tabs( "option", "spinner", 'Retrieving data...' );

  • tabTemplate

    Type:
    String
    Default:
    '<li><a href="#{href}"><span>#{label}</span></a></li>'

    HTML template from which a new tab is created and added. The placeholders #{href} and #{label} are replaced with the url and tab label that are passed as arguments to the add method.

    Code examples

    Initialize a tabs with the tabTemplate option specified.
    $( ".selector" ).tabs({ tabTemplate: '<div><a href="#{href}"><span>#{label}</span></a></div>' });
    Get or set the tabTemplate option, after init.
    //getter
var tabTemplate = $( ".selector" ).tabs( "option", "tabTemplate" );
//setter
$( ".selector" ).tabs( "option", "tabTemplate", '<div><a href="#{href}"><span>#{label}</span></a></div>' );

Events

  • create

    Type:
    tabscreate

    This event is triggered when tabs is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).tabs({
   create: function(event, ui) { ... }
});
    Bind to the create event by type: tabscreate.
    $( ".selector" ).bind( "tabscreate", function(event, ui) {
  ...
});

  • select

    Type:
    tabsselect

    This event is triggered when clicking a tab.

    Code examples

    Supply a callback function to handle the select event as an init option.
    $( ".selector" ).tabs({
   select: function(event, ui) { ... }
});
    Bind to the select event by type: tabsselect.
    $( ".selector" ).bind( "tabsselect", function(event, ui) {
  ...
});

  • load

    Type:
    tabsload

    This event is triggered after the content of a remote tab has been loaded.

    Code examples

    Supply a callback function to handle the load event as an init option.
    $( ".selector" ).tabs({
   load: function(event, ui) { ... }
});
    Bind to the load event by type: tabsload.
    $( ".selector" ).bind( "tabsload", function(event, ui) {
  ...
});

  • show

    Type:
    tabsshow

    This event is triggered when a tab is shown.

    Code examples

    Supply a callback function to handle the show event as an init option.
    $( ".selector" ).tabs({
   show: function(event, ui) { ... }
});
    Bind to the show event by type: tabsshow.
    $( ".selector" ).bind( "tabsshow", function(event, ui) {
  ...
});

  • add

    Type:
    tabsadd

    This event is triggered when a tab is added.

    Code examples

    Supply a callback function to handle the add event as an init option.
    $( ".selector" ).tabs({
   add: function(event, ui) { ... }
});
    Bind to the add event by type: tabsadd.
    $( ".selector" ).bind( "tabsadd", function(event, ui) {
  ...
});

  • remove

    Type:
    tabsremove

    This event is triggered when a tab is removed.

    Code examples

    Supply a callback function to handle the remove event as an init option.
    $( ".selector" ).tabs({
   remove: function(event, ui) { ... }
});
    Bind to the remove event by type: tabsremove.
    $( ".selector" ).bind( "tabsremove", function(event, ui) {
  ...
});

  • enable

    Type:
    tabsenable

    This event is triggered when a tab is enabled.

    Code examples

    Supply a callback function to handle the enable event as an init option.
    $( ".selector" ).tabs({
   enable: function(event, ui) { ... }
});
    Bind to the enable event by type: tabsenable.
    $( ".selector" ).bind( "tabsenable", function(event, ui) {
  ...
});

  • disable

    Type:
    tabsdisable

    This event is triggered when a tab is disabled.

    Code examples

    Supply a callback function to handle the disable event as an init option.
    $( ".selector" ).tabs({
   disable: function(event, ui) { ... }
});
    Bind to the disable event by type: tabsdisable.
    $( ".selector" ).bind( "tabsdisable", function(event, ui) {
  ...
});

Methods

  • destroy

    Signature:
    .tabs( "destroy" )

    Remove the tabs functionality completely. This will return the element back to its pre-init state.

  • disable

    Signature:
    .tabs( "disable" )

    Disable the tabs.

  • enable

    Signature:
    .tabs( "enable" )

    Enable the tabs.

  • option

    Signature:
    .tabs( "option" , optionName , [value] )

    Get or set any tabs option. If no value is specified, will act as a getter.

  • option

    Signature:
    .tabs( "option" , options )

    Set multiple tabs options at once by providing an options object.

  • widget

    Signature:
    .tabs( "widget" )

    Returns the .ui-tabs element.

  • add

    Signature:
    .tabs( "add" , url , label , [index] )

    Add a new tab. The second argument is either a URL consisting of a fragment identifier only to create an in-page tab or a full url (relative or absolute, no cross-domain support) to turn the new tab into an Ajax (remote) tab. The third is the zero-based position where to insert the new tab. Optional, by default a new tab is appended at the end.

  • remove

    Signature:
    .tabs( "remove" , index )

    Remove a tab. The second argument is the zero-based index of the tab to be removed.

  • enable

    Signature:
    .tabs( "enable" , index )

    Enable a disabled tab. To enable more than one tab at once reset the disabled property like: $('#example').tabs("option","disabled",[]);. The second argument is the zero-based index of the tab to be enabled.

  • disable

    Signature:
    .tabs( "disable" , index )

    Disable a tab. The selected tab cannot be disabled. To disable more than one tab at once use: $('#example').tabs("option","disabled", [1, 2, 3]); The second argument is the zero-based index of the tab to be disabled.

  • select

    Signature:
    .tabs( "select" , index )

    Select a tab, as if it were clicked. The second argument is the zero-based index of the tab to be selected or the id selector of the panel the tab is associated with (the tab's href fragment identifier, e.g. hash, points to the panel's id).

  • load

    Signature:
    .tabs( "load" , index )

    Reload the content of an Ajax tab programmatically. This method always loads the tab content from the remote location, even if cache is set to true. The second argument is the zero-based index of the tab to be reloaded.

  • url

    Signature:
    .tabs( "url" , index , url )

    Change the url from which an Ajax (remote) tab will be loaded. The specified URL will be used for subsequent loads. Note that you can not only change the URL for an existing remote tab with this method, but also turn an in-page tab into a remote tab. The second argument is the zero-based index of the tab of which its URL is to be updated. The third is a URL the content of the tab is loaded from.

  • length

    Signature:
    .tabs( "length" )

    Retrieve the number of tabs of the first matched tab pane.

  • abort

    Signature:
    .tabs( "abort" )

    Terminate all running tab ajax requests and animations.

  • rotate

    Signature:
    .tabs( "rotate" , ms , [continuing] )

    Set up an automatic rotation through tabs of a tab pane. The second argument is an amount of time in milliseconds until the next tab in the cycle gets activated. Use 0 or null to stop the rotation. The third controls whether or not to continue the rotation after a tab has been selected by a user. Default: false.

Theming

The jQuery UI Tabs plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.tabs.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<div class="ui-tabs ui-widget ui-widget-content ui-corner-all" id="tabs">
<ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#tabs-1">Nunc tincidunt</a></li>
<li class="ui-state-default ui-corner-top"><a href="#tabs-2">Proin dolor</a></li>
<div class="ui-tabs-panel ui-widget-content ui-corner-bottom" id="tabs-1">
<p>Tab one content goes here.</p>
</div>
...
</div>

Note: This is a sample of markup generated by the tabs plugin, not markup you should use to create a tabs. The only markup needed for that is
<div id="tabs">
<ul>
<li><a href="#tabs-1">Nunc tincidunt</a></li>
<li><a href="#tabs-2">Proin dolor</a></li>
<li><a href="#tabs-3">Aenean lacinia</a></li>
</ul>
<div id="tabs-1">
<p>Tab 1 content</p>
</div>
<div id="tabs-2">
<p>Tab 2 content</p>
</div>
<div id="tabs-3">
<p>Tab 3 content</p>
</div>
</div>.


Position – jQuery API

  • Overview
  • Arguments

jQuery UI Position Utility

Overview

Utility script for positioning any widget relative to the window, document, a particular element, or the cursor/mouse.

Note: jQuery UI does not support positioning hidden elements.

Does not need ui.core.js or effects.core.js.

Dependencies

  • none (only jQuery core)

Example

  • Demo
  • View Source

Clicking on the green element transfers to the other.

$("#position1").position({
  my: "center",
  at: "center",
  of: "#targetElement"
});
$("#position2").position({
  my: "left top",
  at: "left top",
  of: "#targetElement"
});
$("#position3").position({
  my: "right center",
  at: "right bottom",
  of: "#targetElement"
});
$(document).mousemove(function(ev){
  $("#position4").position({
    my: "left bottom",
    of: ev,
    offset: "3 -3",
    collision: "fit"
  });
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
#targetElement { width:240px;height:200px;background-color:#999;margin:30px auto; }
.positionDiv { width:50px;height:50px;opacity:0.6; }
#position1 {background-color:#F00;}
#position2 {background-color:#0F0;}
#position3 {background-color:#00F;}
#position4 {background-color:#FF0;}
</style>

  <script>
  $(document).ready(function() {

$("#position1").position({
  my: "center",
  at: "center",
  of: "#targetElement"
});
$("#position2").position({
  my: "left top",
  at: "left top",
  of: "#targetElement"
});
$("#position3").position({
  my: "right center",
  at: "right bottom",
  of: "#targetElement"
});
$(document).mousemove(function(ev){
  $("#position4").position({
    my: "left bottom",
    of: ev,
    offset: "3 -3",
    collision: "fit"
  });
});

  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="targetElement">
  <div class="positionDiv" id="position1"></div>
  <div class="positionDiv" id="position2"></div>
  <div class="positionDiv" id="position3"></div>
  <div class="positionDiv" id="position4"></div>
</div>

</body>
</html>

Arguments

  • my

    Type:
    String

    Defines which position on the element being positioned to align with the target element: "horizontal vertical" alignment. A single value such as "right" will default to "right center", "top" will default to "center top" (following CSS convention). Acceptable values: "top", "center", "bottom", "left", "right". Example: "left top" or "center center"

  • at

    Type:
    String

    Defines which position on the target element to align the positioned element against: "horizontal vertical" alignment. A single value such as "right" will default to "right center", "top" will default to "center top" (following CSS convention). Acceptable values: "top", "center", "bottom", "left", "right". Example: "left top" or "center center"

  • of

    Type:
    Selector, Element, jQuery, Event

    Element to position against. If you provide a selector, the first matching element will be used. If you provide a jQuery object, the first element will be used. If you provide an event object, the pageX and pageY properties will be used. Example: "#top-menu"

  • offset

    Type:
    String

    Add these left-top values to the calculated position, eg. "50 50" (left top) A single value such as "50" will apply to both.

  • collision

    Type:
    String

    When the positioned element overflows the window in some direction, move it to an alternative position. Similar to my and at, this accepts a single value or a pair for horizontal/vertical, eg. "flip", "fit", "fit flip", "fit none".

    • flip: to the opposite side and the collision detection is run again to see if it will fit. If it won't fit in either position, the center option should be used as a fall back.
    • fit: so the element keeps in the desired direction, but is re-positioned so it fits.
    • none: not do collision detection.

  • using

    Type:
    Function

    When specified the actual property setting is delegated to this callback. Receives a single parameter which is a hash of top and left values for the position that should be set.


Effects – jQuery API

[edit]

effects.core.js

This is the core dependency of the effects of jQuery UI. This file is needed by all other effects and can also be used stand-alone. Please note that ui.core.js is not a dependency for the effects to work.

The core comes with the following exclusive functionality

  • Color animations
  • Class transitions
  • Advanced easing
[edit]

Individual effects

Name Type
Individual effect API:
Name Type

tbd

Name Type
Configurations:
Name Type

Effects that can be used with Show/Hide/Toggle:

  • Blind - Blinds the element away or shows it by blinding it in.
  • Clip - Clips the element on or off, vertically or horizontally.
  • Drop - Drops the element away or shows it by dropping it in.
  • Explode - Explodes the element into multiple pieces.
  • Fade - Fades the element, by gradually changing its opacity.
  • Fold - Folds the element like a piece of paper.
  • Puff - Scale and fade out animations create the puff effect.
  • Slide - Slides the element out of the viewport.
  • Scale - Shrink or grow an element by a percentage factor.

Effects that can be only used stand-alone:

  • Bounce - Bounces the element vertically or horizontally n-times.
  • Highlight - Highlights the background with a defined color.
  • Pulsate - Pulsates the opacity of the element multiple times.
  • Shake - Shakes the element vertically or horizontally n-times.
  • Size - Resize an element to a specified width and height.
  • Transfer - Transfers the outline of an element to another.


Effects – jQuery API

There is currently no text in this page, you can search for this page title in other pages or edit this page.


Blind – jQuery API

  • Overview
  • Arguments

jQuery UI Blind Effect

Overview

Blinds the element away or shows it by blinding it in.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Hides the element by blinding it horizontally.

$("div").click(function () {
      $(this).hide("blind", { direction: "horizontal" }, 1000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).hide("blind", { direction: "horizontal" }, 1000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

Arguments

  • direction

    Type:
    String
    Default:
    "vertical"

    The direction of the effect. Can be "vertical" or "horizontal".

  • mode

    Type:
    String
    Default:
    "hide"

    The mode of the effect. Can be "show" or "hide".


Clip – jQuery API

  • Overview
  • Arguments

jQuery UI Clip Effect

Overview

Clips the element on or off, vertically or horizontally.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Hides the element by clipping it off horizontal.

$("div").click(function () {
      $(this).hide("clip", { direction: "horizontal" }, 1000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).hide("clip", { direction: "horizontal" }, 1000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

Arguments

  • direction

    Type:
    String
    Default:
    "vertical"

    The direction of the effect. Can be "vertical" or "horizontal".

  • mode

    Type:
    String
    Default:
    "hide"

    The mode of the effect. Can be "show" or "hide".


Drop – jQuery API

  • Overview
  • Arguments

jQuery UI Drop Effect

Overview

Drops the element away or shows it by dropping it in.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Hides the element by dropping it down.

$("div").click(function () {
      $(this).hide("drop", { direction: "down" }, 1000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).hide("drop", { direction: "down" }, 1000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

Arguments

  • direction

    Type:
    String
    Default:
    "left"

    The direction of the effect. Can be "left", "right", "up", "down".

  • mode

    Type:
    String
    Default:
    "hide"

    The mode of the effect. Can be "show" or "hide".


Explode – jQuery API

  • Overview
  • Arguments

jQuery UI Explode Effect

Overview

Explodes or implodes the element into/from many pieces.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Hides the element by exploding it into 9 pieces.

$("div").click(function () {
      $(this).hide("explode", 1000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).hide("explode", 1000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

  • Demo
  • View Source
Shows the element by imploding it from 16 pieces.

$("div").click(function () {
      $(this).show("explode", { pieces: 16 }, 2000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

<script src="http://dev.jquery.com/view/tags/ui/latest/ui/effects.core.js"></script>
<script src="http://dev.jquery.com/view/tags/ui/latest/ui/effects.explode.js"></script>
<style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).show("explode", { pieces: 16 }, 2000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

Arguments

  • mode

    Type:
    String

    The mode of the animation. Can be set to "show" or "hide".

  • pieces

    Type:
    Integer
    Default:
    9

    Number of pieces to be exploded to/imploded from.


Fade – jQuery API

  • Overview
  • Arguments

jQuery UI Fade Effect

Overview

Fades the element. The same effect as jQuery's fadeIn/Out/To methods, but exposes it to the show, hide and effect methods.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Hides the element by fading it out.

$("div").click(function () {
      $(this).hide("fade", {}, 1000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).hide("fade", {}, 1000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

Arguments

    The fade effect has no arguments

© 2010 The jQuery Project


Fold – jQuery API

  • Overview
  • Arguments

jQuery UI Fold Effect

Overview

Folds the element like a piece of paper.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Hides the element by folding it first to 15px, then completely.

$("div").click(function () {
      $(this).hide("fold", {}, 1000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

<script src="http://jqueryui.com/latest/ui/effects.core.js"></script>
<script src="http://jqueryui.com/latest/ui/effects.fold.js"></script>
<style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).hide("fold", {}, 1000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

Arguments

  • horizFirst

    Type:
    Boolean
    Default:
    false

    Whether to fold horizontally first or not. Can be true or false.

  • mode

    Type:
    String
    Default:
    "hide"

    The mode of the effect. Can be "show" or "hide".

  • size

    Type:
    Integer
    Default:
    15

    Size to be folded to.


Puff – jQuery API

  • Overview
  • Arguments

jQuery UI Puff Effect

Overview

This is the only effect without seperate file, it uses effects.scale.js. It creates a puff effect by scaling the element up and hiding it at the same time.

Dependencies

  • Effects Core
  • Scale effect

Example

  • Demo
  • View Source

Puff the element away.

$("div").click(function () {
      $(this).hide("puff", {}, 1000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).hide("puff", {}, 1000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

Arguments

  • mode

    Type:
    String
    Default:
    "hide"

    The mode of the effect. Can be "show" or "hide"

  • percent

    Type:
    Integer
    Default:
    150

    The percentage to scale to.


Slide – jQuery API

  • Overview
  • Arguments

jQuery UI Slide Effect

Overview

Slides the element out of the viewport.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Hides the element by sliding it down.

$("div").click(function () {
      $(this).hide("slide", { direction: "down" }, 1000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).hide("slide", { direction: "down" }, 1000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

Arguments

  • direction

    Type:
    String
    Default:
    "left"

    The direction of the effect. Can be "left", "right", "up", "down".

  • distance

    Type:
    Integer
    Default:
    el.outerWidth

    The distance of the effect. Is set to either the height or width of the elemenet depending on the direction option. Can be set to any integer less than the width/height of the element.

  • mode

    Type:
    String
    Default:
    "show"

    The mode of the effect. Can be "show" or "hide".


Scale – jQuery API

  • Overview
  • Arguments

jQuery UI Scale Effect

Overview

Shrink or grow an element by a percentage factor.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Scale the element to 0%, with the hide method (center vanishing point).

$("div").click(function () {
      $(this).hide("scale", {}, 1000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).hide("scale", {}, 1000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

  • Demo
  • View Source
Scale the element to 200%, only horizontal.

$("div").click(function () {
      $(this).effect("scale", { percent: 200, direction: 'horizontal' }, 1000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).effect("scale", { percent: 200, direction: 'horizontal' }, 1000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

Arguments

  • direction

    Type:
    String
    Default:
    "both"

    The direction of the effect. Can be "both", "vertical" or "horizontal".

  • from

    Type:
    Object

    state at beginning, usually not needed.{ height: .., width: .. }

  • origin

    Type:
    Array
    Default:
    ['middle','center']

    the vanishing point, default for show/hide

  • percent

    Type:
    Integer
    Default:
    0/100

    the percentage to scale to, number.

  • scale

    Type:
    String
    Default:
    "both"

    Which areas of the element will be resized: 'both', 'box', 'content' Box resizes the border and padding of the element Content resizes any content inside of the element


Bounce – jQuery API

  • Overview
  • Arguments

jQuery UI Bounce Effect

Overview

Bounces the element multiple times, vertically or horizontally.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Bounces 3 times when clicking on the element.

$("div").click(function () {
      $(this).effect("bounce", { times:3 }, 300);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).effect("bounce", { times:3 }, 300);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <p></p><p></p><p></p><p></p><div></div>
</body>
</html>

Arguments

  • direction

    Type:
    String
    Default:
    "up"

    The direction of the effect. Can be "up", "down", "left", "right".

  • distance

    Type:
    Integer
    Default:
    20

    Distance to bounce.

  • mode

    Type:
    String
    Default:
    "effect"

    The mode of the effect. Can be "show", "hide" or "effect". .

  • times

    Type:
    Integer
    Default:
    5

    Times to bounce.


Highlight – jQuery API

  • Overview
  • Arguments

jQuery UI Highlight Effect

Overview

Highlights the element's background with a specific color, default is yellow.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Simple highlight when clicking on the element.

$("div").click(function () {
      $(this).effect("highlight", {}, 3000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: #666; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).effect("highlight", {}, 3000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

Arguments

  • color

    Type:
    String
    Default:
    "#ffff99"

    Highlight color

  • mode

    Type:
    String
    Default:
    "show"

    The mode of the effect. Can be "show" or "hide".


Pulsate – jQuery API

  • Overview
  • Arguments

jQuery UI Pulsate Effect

Overview

Pulsates the opacity of the element multiple times.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Pulsate 3 times when clicking on the element.

$("div").click(function () {
      $(this).effect("pulsate", { times:3 }, 2000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).effect("pulsate", { times:3 }, 2000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

Arguments

  • mode

    Type:
    String
    Default:
    "show"

    The mode of the effect. Can be "show" or "hide".

  • times

    Type:
    Integer
    Default:
    5

    Times to pulsate.


Shake – jQuery API

  • Overview
  • Arguments

jQuery UI Shake Effect

Overview

Shakes the element multiple times, vertically or horizontally.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Shakes 3 times when clicking on the element.

$("div").click(function () {
      $(this).effect("shake", { times:3 }, 300);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).effect("shake", { times:3 }, 300);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <p></p><p></p><p></p><p></p><div></div>
</body>
</html>

Arguments

  • direction

    Type:
    String
    Default:
    "left"

    The direction of the effect. Can be "up", "down", "left", "right".

  • distance

    Type:
    Integer
    Default:
    20

    Distance to shake.

  • times

    Type:
    Integer
    Default:
    3

    Times to shake.


Size – jQuery API

  • Overview
  • Arguments

jQuery UI Size Effect

Overview

Resize an element to a specified width and height.

Dependencies

  • Effects Core
  • Scale effect

Example

  • Demo
  • View Source

Size an element to 200 x 60.

$("div").click(function () {
      $(this).effect("size", { to: {width: 200,height: 60} }, 1000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).effect("size", { to: {width: 200,height: 60} }, 1000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>

Arguments

  • from

    Type:
    Object

    state at beginning, usually not needed.{ height: .., width: .. }

  • to

    Type:
    Object

    Height and width to resize to.{ height: .., width: .. }

  • origin

    Type:
    Array
    Default:
    ['top','left']

    the vanishing point, default for show/hide

  • scale

    Type:
    String
    Default:
    "both"

    Which areas of the element will be resized: 'both', 'box', 'content' Box resizes the border and padding of the element Content resizes any content inside of the element


Transfer – jQuery API

  • Overview
  • Arguments

jQuery UI Transfer Effect

Overview

Transfers the outline of an element to another element. Very useful when trying to visualize interaction between two elements.

The transfer element iself has the class name "ui-effects-transfer", and needs to be styled by you, for example by adding a background or border.

Dependencies

  • Effects Core

Example

  • Demo
  • View Source

Clicking on the green element transfers to the other.

$("div").click(function () {
      var i = 1 - $("div").index(this);
      $(this).effect("transfer", { to: $("div").eq(i) }, 1000);
});

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
  div.green { margin: 0px; width: 100px; height: 80px; background: green; border: 1px solid black; position: relative; }
  div.red { margin-top: 10px; width: 50px; height: 30px; background: red; border: 1px solid black; position: relative; }
  .ui-effects-transfer { border: 2px solid black; }

</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      var i = 1 - $("div").index(this);
      $(this).effect("transfer", { to: $("div").eq(i) }, 1000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div class="green"></div>
<div class="red"></div>

</body>
</html>

Arguments

  • className

    Type:
    String

    Optional class name the transfer element will receive.

  • to

    Type:
    String

    jQuery selector, the element to transfer to.


jQuery.error – jQuery API

Returns: jQuery.error( [ String ] message )

Categories: Internals, Version 1.4.1
Description: Takes a string and throws an exception containing it.
  • version added: 1.4.1
  • jQuery.error( [ String ] message )
  • message The message to send out.

This method exists primarily for plugin developers who wish to override it and provide a better display (or more information) for the error messages.

Examples:

Example:

Override jQuery.error for display in Firebug.
jQuery.error = console.error;


pushStack – jQuery API

Returns: jQueryjQuery .pushStack( [ Array ] elements, [ String ] name, [ Array ] arguments )

Categories: Internals, Version 1.0, Version 1.3
Description: Add a collection of DOM elements onto the jQuery stack.
  • version added: 1.0
  • .pushStack( [ Array ] elements )
  • elements An array of elements to push onto the stack and make into a new jQuery object.
  • version added: 1.3
  • .pushStack( [ Array ] elements, [ String ] name, [ Array ] arguments )
  • elements An array of elements to push onto the stack and make into a new jQuery object.
  • name The name of a jQuery method that generated the array of elements.
  • arguments The arguments that were passed in to the jQuery method (for serialization).

Examples:

Example:

Add some elements onto the jQuery stack, then pop back off again.
jQuery([])
    .pushStack( document.getElementsByTagName("div") )
        .remove()
    .end();